C LUA API - 获取索引处的表值

Gra*_*pes 4 c lua lua-table

假设以下lua代码:

local FooTable={ ["FooKey"]="FooValue" }
Run Code Online (Sandbox Code Playgroud)

索引"FooValue"是"FooKey".所以我可以像这样访问它而没有任何问题(假设FooTable位于堆栈顶部.):

lua_getfield(L, -1, "FooKey");
Run Code Online (Sandbox Code Playgroud)

当我尝试这样的事情时:

local FooTable={ "FooValue" }
Run Code Online (Sandbox Code Playgroud)

我会假设索引"FooValue"是"1".但以下给了我一个nil回报.

lua_getfield(L, -1, "1");
Run Code Online (Sandbox Code Playgroud)

是否有一种特殊的方法来访问表中的数字键?

Cal*_*dan 6

在第二种情况下,索引是第一个,而不是字符串"1".

获取第一个元素的一种方法是使用以下函数:

void lua_rawgeti (lua_State *L, int index, int key);
Run Code Online (Sandbox Code Playgroud)

另一种方法是在堆栈上按一个键并调用:

void lua_gettable (lua_State *L, int index);
Run Code Online (Sandbox Code Playgroud)

第一种方法不会触发元方法,第二种方法可能.