I'm trying to make a deeply nested table in Lua. When I nest past 16 levels my program crashes.
In the example program below, when I change DEPTH to 16 instead of 17 the program does not crash. I can't find any resources that say there is a maximum table depth, and one so low seems odd. The crash is within the call to lua_close().
Am I misunderstanding how to build a table in Lua using the C API, or is there in fact a maximum depth?
#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;
}
You need to increase the stack with lua_checkstack
or luaL_checkstack
to allow 2*DEPTH
slots.