我能否在使用lua_pushnumber时调整堆栈的最大大小?

我们的项目有一个问题,我们使用 Lua 5.1 作为脚本语言。但是当使用 lua_pushnumber 在一个函数中从 C++ 向 Lua 传递过多的数据时,Lua 栈似乎会像栈溢出一样,并且导致 C++ 中的其他部分已被写入的内存,当回调返回到 C++ 时会导致系统崩溃。我想知道是否有某些参数来控制 Lua 栈大小。我尝试更改在 lua.h 中定义的 LUA_MINSTACK 参数,但似乎不起作用。我还尝试使用 lua_checkstack() 避免向 Lua 栈推送过多的数字,但也没有作用。

当一个屏幕中有太多实体时,似乎我们的程序会崩溃。

点赞
用户1847592
用户1847592

在向 Lua 栈中推送内容之前,每次都应该检查一下 Lua 栈。

默认情况下,栈大小是 20,如果需要更多的空间,则应该手动扩大。

Lua 手册

2013-04-03 15:46:26
用户2242940
用户2242940

这可能会有帮助(来自 Lua 5.2 手册)

int lua_checkstack(lua_State *L,int extra);

"确保栈中至少有 'extra' 个空闲的栈槽。如果无法满足请求,则返回 false,因为这会使栈大于固定的最大大小(一般至少为几千个元素),或者因为它不能为新的栈大小分配内存。该函数不会缩小栈;如果栈已经大于新的大小,则会保持不变。"

下面是一个示例 c 函数...

static int l_test1 (lua_State *L) {
    int i;
    printf("test1: on the way in"); stackDump(L);
    int cnt = lua_tointeger(L, 1);
    printf("push %d items onto stack\n", cnt);
    printf("try to grow stack: %d\n", lua_checkstack(L, cnt));
    for (i=0; i<cnt; i++) {
        lua_pushinteger(L, i);                      /* loop -- push integer */
    }
    printf("test1: on the way out"); stackDump(L);
    return 1;
}

这段代码:

  • 在函数进入时转储堆栈。 (1)
  • 尝试将堆栈大小扩展为 'cnt' 个免费插槽(它返回 true,它已经运行,或 false,它没有)。
  • 在堆栈上推入 'cnt' 个整数。
  • 在函数退出时转储堆栈。

$ lua demo.lua
running stack test with 10 pushes
test1: on the way in
---1--
[1] 10
-----
push 10 items onto stack
test1: on the way out
---11--
[11] 9
[10] 8
[9] 7
[8] 6
[7] 5
[6] 4
[5] 3
[4] 2
[3] 1
[2] 0
[1] 10
-----
running stack test with 1000 pushes
test1: on the way in
---1--
[1] 1000
-----
push 1000 items onto stack
try to grow stack: 1
test1: on the way out
---1001--
[1001] 999
[1000] 998
[999] 997
[998] 996
[997] 995
[996] 994
...

当上面的代码没有 lua_checkstack() 调用时,我们尝试将 1000 个项推入堆栈时会出现错误。


running stack test with 1000 pushes
test1: on the way in
---1--
[1] 1000
-----
push 1000 items onto stack
Segmentation fault (core dumped)
$

(1) stackDump() 与在 PiL 3rd ed. 中出现的转储堆栈内容类似。

2013-04-04 01:50:52