gpt4 book ai didi

C++/Lua FFI 将用户数据呈现为表格?

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:21:07 24 4
gpt4 key购买 nike

我在 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 中运行我的代码。

最佳答案

我不完全确定你所说的“可以用作表格”是什么意思,但是如果你想打印一些不同于 print(obj) 的默认值,那么你将需要分配 __tostring metamethod 并从中返回一些字符串。如果您愿意,此字符串可能看起来像 "userdata: 0x12345678 = {foo = 123}"(或者只是 "{foo = 123}")。

如果您的意思是在为其分配新索引时使其作为表工作,则应使用 __newindex metamethod

关于C++/Lua FFI 将用户数据呈现为表格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47424323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com