C LUA API – Get table value at index

clualua-table

Assuming the following lua code:

local FooTable={ ["FooKey"]="FooValue" }

The index of "FooValue" is "FooKey". So I can access it like this without any issues (Assuming FooTable is on top of the stack.):

lua_getfield(L, -1, "FooKey");

When I try something like this:

local FooTable={ "FooValue" }

I would assume that index of "FooValue" is "1". But the following gives me a nil return.

lua_getfield(L, -1, "1");

Is there a special approach to accessing numeric keys in tables?

Best Answer

In the second case the index is number one, not a string "1".

One way of getting the first element is using the following function:

void lua_rawgeti (lua_State *L, int index, int key);

Another way is to push a key on the stack and call:

void lua_gettable (lua_State *L, int index);

The first way will NOT trigger metamethods, the second one may.

Related Topic