1

我正在尝试在 Lua 中创建一个深度嵌套的表。当我嵌套超过 16 层时,我的程序崩溃了。

在下面的示例程序中,当我将 DEPTH 更改为 16 而不是 17 时,程序不会崩溃。我找不到任何说有最大表深度的资源,而且这么低似乎很奇怪。崩溃发生在对 lua_close() 的调用中。

我是否误解了如何使用 C API 在 Lua 中构建表,或者实际上是否存在最大深度?

#include <assert.h>
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"

#define DEPTH 17

int main(int argc, char* argv[])
{
    lua_State *L = NULL;
    size_t i = 0;

    L = luaL_newstate();
    assert(NULL!=L);

    luaL_openlibs(L);

    // create the root table
    lua_newtable(L);

    // push DEPTH levels deep onto the table
    for (i=0; i<DEPTH; i++)
    {
        lua_pushstring(L, "subtable");
        lua_newtable(L);
    }

    // nest the DEPTH levels
    for (i=0; i<DEPTH; i++)
    {
        lua_settable(L, -3);
    }

    lua_close(L);

    return 0;
}
4

1 回答 1

1

您需要使用lua_checkstackluaL_checkstack允许2*DEPTH插槽来增加堆栈。

于 2016-09-01T23:44:45.957 回答