简体   繁体   中英

How to access nested Lua tables from C

Let's say I want to set a value (eg 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);

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");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM