Question

Let's say I want to set a value (e.g. a function) inside a nested table from the Lua C API.

-- lua.lua
glob = { 
  nest = { 
    -- set value in here
  }
}

How would I have to set the stack to access the inner table?

Is it just calling gettable multiple times and then a settop, like in the following code?

lua_pushstring(state, "glob");
lua_gettable(state, -1);
lua_pushstring(state, "nest");
lua_gettable(state, -1);

lua_pushcclosure(state, &func, 0);
lua_settop(state, "funkyfunc");

lua_pop(state, 2);
Was it helpful?

Solution

This code sets glob.nest.name to a C function:

lua_getglobal(state, "glob");
lua_getfield(state, -1, "nest");
lua_pushcclosure(state, &func, 0);
lua_setfield(state, -1, "name");

To add others field to glob.nest, just keep going:

...
lua_pushcclosure(state, &anotherfunc, 0);
lua_setfield(state, -1, "anothername");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top