【问题标题】:Storing values in a userdata object from lua从 lua 将值存储在 userdata 对象中
【发布时间】:2010-08-25 00:39:22
【问题描述】:

我想做的是这样的:

object.foo = "bar"

print(object.foo)

其中“对象”是用户数据。

我已经在谷歌上搜索了一段时间(使用关键字 __newindex 和 lua_rawset),但我找不到任何符合我要求的示例。

我想用 c++ 中的 lua api 来做这个

【问题讨论】:

  • 字符串属性foo是任意的还是代表userdata对象的一个​​属性?
  • 请注意,lua_rawset() 将跳过对元表的访问。这就是为什么它是“原始的”。您想使用任何其他操作表条目的 API 函数,以便使用元方法。
  • foo 只是一个变量,我用来表明我想在 lua 中的 userdata 中存储一些东西。

标签: lua


【解决方案1】:

让我们用 Lua 代码来写这个,这样我们就可以用代码做快速实验

function create_object()
  -- ## Create new userdatum with a metatable
  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)
-- prints '10'

如果您使用用户数据,您可能希望使用 C API 执行上述操作。然而,Lua 代码应该明确说明哪些步骤是必要的。 (newproxy(..) 函数只是从 Lua 创建一个虚拟用户数据。)

【讨论】:

  • 我忘了补充说我想在 c++ 中执行此操作,但我不知道如何在此处执行此操作。
  • 哦,我明白你的意思了。我可以尝试这样做。
  • Lua 5.2及以上版本不支持newproxy功能。
【解决方案2】:

我放弃了尝试在 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,例如 Vec3 和 Ang3 等等。

【讨论】:

    【解决方案3】:

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

    config = { tooltype1 = "Tool",   
            tooltype2 = "HopperBin",   
            number = 5,
            }   
    
    print(config.tooltype1) --"Tool"   
    print(config.tooltype2) --"HopperBin"   
    print(config.number) --5
    

    【讨论】:

      猜你喜欢
      • 2016-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-04
      • 2016-07-05
      • 2012-04-03
      • 1970-01-01
      相关资源
      最近更新 更多