将值存储在Lua的userdata对象中

我想做的是这个:

object.foo = "bar"

print(object.foo)

其中 "object" 是一个 userdata。

我已经使用关键字 __newindex 和 lua_rawset 进行搜索了一段时间,但我找不到任何可以实现我想要的功能的示例。

我想在 c++ 中使用 lua api 实现这个。

原文链接 https://stackoverflow.com/questions/3541839

点赞
stackoverflow用户137317
stackoverflow用户137317

让我们用 Lua 代码写出来,以便我们可以快速地对代码进行实验

function create_object()
  -- ## 创建一个带有元表的新用户数据
  local obj = newproxy(true)
  local store = {}
  getmetatable(obj).__index = store
  getmetatable(obj).__newindex = store
  return obj
end

ud = create_object()
ud.a = 10
print(ud.a)
-- 输出 '10'

如果你使用用户数据,则可能希望使用 C API 完成上述操作。然而,Lua 代码应该清楚地说明必须完成哪些步骤。(newproxy(..) 函数仅从 Lua 中创建一个虚拟用户数据。)

2010-08-22 15:11:40
stackoverflow用户270483
stackoverflow用户270483

你也可以使用简单的表格...

config = { tooltype1 = "Tool",
        tooltype2 = "HopperBin",
        number = 5,
        }

print(config.tooltype1) --"Tool"
print(config.tooltype2) --"HopperBin"
print(config.number) --5
2010-08-24 12:39:43
stackoverflow用户427310
stackoverflow用户427310

我放弃了尝试用 C++ 实现,所以我用 lua 实现了它。我循环遍历所有元表(\_R)并分配元方法。

_R.METAVALUES = {}

for key, meta in pairs(_R) do
    meta.__oldindex = meta.__oldindex or meta.__index

    function meta.__index(self, key)
        _R.METAVALUES[tostring(self)] = _R.METAVALUES[tostring(self)] or {}
        if _R.METAVALUES[tostring(self)][key] then
            return _R.METAVALUES[tostring(self)][key]
        end
        return meta.__oldindex(self, key)
    end

    function meta.__newindex(self, key, value)
        _R.METAVALUES[tostring(self)] = _R.METAVALUES[tostring(self)] or {}
        _R.METAVALUES[tostring(self)][key] = value
    end

    function meta:__gc()
        _R.METAVALUES[tostring(self)] = nil
    end
end

问题在于我应该使用什么索引。tostring(self) 仅适用于那些返回至 tostring 的 ID 的对象。并非所有对象都有 ID,例如 Vec3Ang3 等。

2010-08-24 16:20:31