gpt4 book ai didi

c++ - 如何从 lua 函数返回两个或多个表?

转载 作者:太空宇宙 更新时间:2023-11-04 02:16:08 24 4
gpt4 key购买 nike

如果有人向我解释当从 C 调用的 lua 函数返回两个表或内部嵌套表的表时 lua-C 堆栈如何工作,我将不胜感激

当我尝试这样做时,它看起来不错,但只是乍一看:

if ( lua_istable(L, -1) )
printf("its OK\n");

if ( lua_istable(L, -2) )
printf("its OK\n");

lua_pushnil(L);

while ( lua_next(L, -2) )
{
if(lua_isnumber(L, -1))
{
int i = (int)lua_tonumber(L, -1);
const char *key = lua_tostring(L, -2);
printf("%d %s \n", i, key);
}
lua_pop(L, 1);
}
lua_pop(L, 1);

在这种情况下,我收到两条消息,第一个表在级别 -1,第二个在级别 -2,但是在这段代码之后,当我试图获取下一个表时,我的程序崩溃了当我检查表是否存在堆栈时

for ( int i = -2; ; --i)
if ( lua_istable(L, i) )
printf("its %d OK\n", i);

我得到了以下结果:

its -233 OK
its -645 OK
its -1245 OK
its -1549 OK
its -2807 OK
its -2815 OK
its -2816 OK

有人可以帮我解决这个问题吗?

最佳答案

请注意,当 lua_next 返回 0 时,键已弹出,但什么也没压,所以在 while 循环结束时,您有你的两个表在堆栈上。

while 循环之后的 lua_pop 将顶层表格弹出堆栈。

随后的 for 循环从索引 -2 开始,该索引在表格之后,可以包含任何内容。此外,for 循环永远不会终止。

关于c++ - 如何从 lua 函数返回两个或多个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7473924/

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