Reading values from a table

Fields from a table can be retrieved with the lua_gettable (lua_State*, int) function. This function returns nothing; its first argument is the Lua state to work on. Typically, accessing a table in Lua involves both the table and a key, for example: tbl[key]. Using lua_gettable, the table (tbl) is expected to be at the index specified by the second variable. The key (key) is expected to be on the top of the stack. The following code demonstrates how to retrieve the value of the key x from a table named vector:

lua_getglobal(L, "vector");
lua_pushstring(L, "x");
lua_gettable(L, -2);

Since retrieving a variable is so common, Lua provides a handy shortcut function, lua_getfield (lua_State*, int, const char*). This helper function avoids having to push the name of the key onto the stack, and instead takes it as the third argument. The second argument is still the index of the table on the stack. The preceding example could be rewritten with lua_getfield like, as follows:

// Push vector to the top of the stack
lua_getglobal(L, "vector");
// The index -1 refers to vector, which is on top of the stack
// Leaves the value of x on the top of the stack
lua_getfield(L, -1, "x");
// The stack has 2 new values (vector & x)on it that will need to be cleaned up at some point

You might have noticed that the preceding code passes a negative index to lua_getfield. Recall from the Querying the stack section of this chapter that positive numbers index the stack from the bottom up, while negative numbers index the stack from the top down. 

Passing -1 in the previous code works because the lua_getglobal function call will leave the "vector" table on the top of the stack. At this point, we don't know (or care) how large the stack is, just that the top element is the table "vector". After calling lua_getfield, the value of "x" is on the top of the stack.

..................Content has been hidden....................

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