Newcomers are puzzled that there is no lua_totable
or lua_tofunction
corresponding to lua_tostring
, etc. This is because Lua does not expose a general 'Lua object' type; all values are passed using the stack. The
registry provides a mechanism for saving references to tables or Lua functions, however.
int ref;
lua_newtable(L); // new table on stack ref = luaL_ref(L,LUA_REGISTRYINDEX); // pop and return a reference to the table.
Then, when you need to push this table again, you just need to access the registry using this integer reference:
lua_rawgeti(L,LUA_REGISTRYINDEX,ref);
This also works with functions; you use luaL_ref
to get a reference to a function which can then be retrieved and called later. This is needed when implementing callbacks; remember to use lua_pcall
so that a bad call does not crash your program.