Writing values to a table

Lua offers the lua_settable (lua_State*, int) function to set fields in a table. The function returns nothing. Its first argument is the Lua state to work on and the second argument is the index of a table on the stack.

The value being set is expected to be on top of the stack, and the key to set it to is expected to be just below that. lua_settable will pop both the key and value off the stack, but it will leave the table on the stack.

For example, the Lua code vector["y"] = 7 could be written with this API as follows:

// Push vector onto the stack
lua_gettable(L, "vector");
// Push y onto the stack
lua_pushstring(L, "y");
// Push 7 onto the stack
lua_pushnumber(L, 7);
// The stack has three new variables on it
// The index of 7 is -1
// The index of "y" is -2
// The index of "vector" is -3

// Call lua_settable on the "vector" table at index -3
lua_settable(L, -3);

// lua_settable will pop the key ("y") and value (7) off the stack
// Only one item is left on the stack, the "vector" table
// The item left on the stack should be cleaned up at some point

Lua also offers the lua_setfield (lua_State*, int, const char*) function which avoids the need to push the key onto the stack. The first two arguments are the same as lua_settable. The third argument is the key of what is being set.

The value of what is being set is expected to be at the top of the stack. The lua_setfield function will pop the value off the stack, much like lua_settable does.

The preceding code sample can be rewritten to use lua_setfield as follows:

// Push "vector" onto the stack
lua_gettable(L, "vector");
// Push 7 onto the stack
lua_pushnumber(L, 7);
// Call lua_setfield on the "vector"table at index -2
lua_setfield(L, -2, "y");

// lua_setfield will pop the value (7) off the stack
// Only one item is left on the stack, the "vector" table
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.226.88.110