gpt4 book ai didi

C++ 和 Lua,推送 Lua 表作为参数

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

我正在将 Lua 集成到 C++ 中,现在我有了这个表,它的行为就像一个“类”,对于某些函数,它需要一个“self”参数,这实际上就是表。 Lua代码:

a = {
numb = 5,

create = function(a)
print(a);
end,

increment = function(self)
--self.numb = 6;
print(self.numb);
end,

decrement = function(self,i)
self.numb = self.numb-i;
print(self.numb);
end
};
b = a;

还有调用函数的 C++ 位(我让 Lua 在 C++ 中运行)

luaL_openlibs(L);

luaL_dofile (L,"main.lua");

lua_getglobal(L, "a");
lua_getfield(L, -1, "increment");

string arg = "a";

lua_pushliteral(L,"a");

lua_pcall(L ,1,0,0);

printf(" \nI am done with Lua in C++.\n");

lua_close(L);

那么,我怎样才能将 self 参数作为表格传递给函数增量?

感谢任何帮助

最佳答案

在 Lua 5.1 中你使用 lua_getglobal到,嗯,得到一个全局的,比如你的表a——你用它来得到你的表就在上面几行;您需要做的就是复制该值以将其传递给您的函数

 lua_getglobal(L, "a"); // the table a is now on the stack
lua_getfield(L, -1, "increment"); // followed by the value of a.increment

lua_pushvalue(L,-2); // get the table a as the argument

lua_pcall(L,1,0,0);

关于C++ 和 Lua,推送 Lua 表作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11215400/

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