【发布时间】:2018-05-05 13:54:15
【问题描述】:
我在 C++ 中有以下简单代码,其中 Object 是一个标准容器:
static int create_an_object(lua_State* L) {
auto obj = static_cast<Object*>(lua_newuserdata(L, sizeof(Object*)));
*obj = another_valid_obj;
luaL_newmetatable(L, "object_metatable");
lua_pushcfunction(L, object_metatable_function);
lua_setfield(L, -2, "__index");
lua_pop(L, 1);
return 1;
}
static int object_metatable_function(lua_State* L) {
string index = luaL_checkstring(L, -1);
if (index == "foo") {
lua_pushnumber(L, 123);
}
// Handles other indices, or throws error.
}
lua_pushcfunction(L, create_an_object);
lua_setglobal(L, "create_an_object");
通过上面的FFI,我可以在Lua中实现Object的索引如:
local obj = create_an_object()
print(obj.foo) -- 123
同时print(obj) 表明obj 是userdata: 0x12345678。
是否可以使用一些元方法魔法,以便
obj 可以用作表格,而 print(obj.foo) 仍然打印 123?我在 Lua 5.1 中运行我的代码。
【问题讨论】: