5

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?

Grapes
  • 2,473
  • 3
  • 26
  • 42

1 Answers1

6

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.

Caladan
  • 1,471
  • 11
  • 13
  • Thanks, that worked. The end result would look like this: lua_pushnumber(L, 1); lua_gettable(L, -2); – Grapes Sep 30 '13 at 08:13