Lua interacts with C through a virtual stack, with a positive index from the bottom up and a negative index from the top down.
The table (table) structure in Lua can be evaluated with any data as a key. There are two ways to access elements in a Table using the C API:
Copy Code code as follows:
Lua_getglobal (L, T);
Lua_pushinteger (L, k); --This can be replaced by other types of lua_pushxxxx (L, k) pressure data to the top of the stack as key
Lua_gettable (L,-2);
Lua_getglobal (L, T);
Lua_getfield (L,-1, k);
At the end of the stack, the case is: Stack top is t[k], the second top element is table type T. The second method is actually the first method in "key as a string" when the special wording. "
C API Traversal Table
Copy Code code as follows:
Lua_getglobal (L, T);
Lua_pushnil (L);
while (Lua_next (L,-2)) {
/* At this time on the stack-1 for value,-2 for key * *
Lua_pop (L, 1);
}
The Lua_next function iterates over the Table at-2 (parameter specified). Pop-up-1 (top of the stack) value as the last key (as the first key for nil), pressing into the next key and value in the Table. The return value indicates whether the next key exists.
In addition to processing values in the loop to remember to clean the stack at any time, otherwise the Table is not 2. (You can also consider a positive index that saves a Table with Lua_gettop after Lua_getglobal.) )
Although this is a manual of the traversal method, but this method in the history does not have a certain sequence of traversal, so there is the following method.
Do a less-than-perfect traversal with an integer Key
Copy Code code as follows:
Lua_getglobal (L, T);
Len = Lua_objlen (L,-1);
for (i = 1; I <= len i++) {
Lua_pushinteger (L, i);
Lua_gettable (L,-2);
/* At this time the top of the stack is t[i] element * *
Lua_pop (L, 1);
}
This method ignores the non-integer key, but can guarantee the traversal order. If you only focus on the integer key, consider using this traversal method:)