Lua的表模拟

大家好

我有一个具体的任务,需要在 Lua 脚本中访问 c++ 的 std::map。所期望的脚本语法是 glob["tag"] = "value" 或 glob("tag") = "value"。

我已经尝试了 luabind 绑定,代码如下:

std::string & glob(const std::string &tag)
{
    static std::string value;
    return value;
}

...

luabind::module(&state)
[
    def("glob", &glob, luabind::return_reference_to(result))
]

但在执行下面的脚本后

glob("tag") = "asdasd"
print(glob("tag"))

出现了错误 [string "glob("tag") = "asdasd"..."]:1: unexpected symbol near '='

因此,我正在等待您的建议和意见。

谢谢

更新:数据以 c++ 部分存储和序列化为全局变量,需要通过 lua 访问。luaState 是每次执行脚本时创建的,脚本执行之间不存在。其中一种解决方案是在执行脚本之前创建和填充全局变量表,并在脚本执行后将其与 map 同步,但我觉得这样的速度太慢。因此,希望能够通过 c 函数以前述语法进行访问。

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

点赞
stackoverflow用户107090
stackoverflow用户107090
`glob("tag") = "asdasd"` 绝不可能起作用,因为它不是有效的 Lua 语法。`glob["tag"] = "value"` 可以起作用。你需要将 `glob` 设置为一个具有 _index_ 和 _newindex_ 元方法的 userdata。我不知道 luabind 的任何信息,所以我无法在那里帮助你。但是使用标准 Lua API 进行操作并不难。我只是在想,当 Lua 已经有了出色的关联数组时,你为什么需要将 C++ 的 _map_ 导出到 Lua 中。 
2011-05-10 15:31:28
stackoverflow用户518541
stackoverflow用户518541

没错,是元表规则。

只需要插入一些从示例中获取的 c 代码

lua_createtable(&state, 0, 0);
lua_pushcfunction(&state, &getValue);
lua_setfield(&state, -2, "__index");
lua_pushcfunction(&state, &setValue);
lua_setfield(&state, -2, "__newindex");
lua_setmetatable(&state, -2);
lua_setglobal(&state, "global");

一切都OK,谢谢

但这里还有一个问题:为什么我应该在 lua_setfield 和 lua_setmetatable 中使用 index == -2?

2011-05-11 08:58:50