lua_next
int lua_next (lua_State *L, int index);
//官方示例 /* table is in the stack at index 't' */ lua_pushnil(L); /* first key */ while (lua_next(L, t) != 0) { /* uses 'key' (at index -2) and 'value' (at index -1) */ printf("%s - %s\n", lua_typename(L, lua_type(L, -2)), lua_typename(L, lua_type(L, -1))); /* removes 'value'; keeps 'key' for next iteration */ lua_pop(L, 1); }
会根据栈顶的键,自动索引下一个键,并且将新键和新value返回至栈顶
-1 | -2 | idx | |
— | — | table | |
lua_pushnil(L) | nil | table | |
lua_next(L, t) | new_value_1 | new_key_1 | table |
lua_pop(L, 1) | new_key_1 | — | table |
lua_next(L, t) | new_value_2 | new_key_2 | table |
lua_pop(L, 1) | new_key_2 |
还有一点值得注意,while (lua_next(L, t) != 0),当返回值为1时,表示表中后续还有元素。当返回值为0时,表明没有找到元素。请注意,此时依旧会将栈顶的这个用于寻找下一个key的key弹出,但是并不会插入任何的数字,其实这也就做到了清理栈顶的目的。
lua_gettable
void lua_gettable (lua_State *L, int index); //这个东西会调用到元方法
取index处的table,将栈顶的key弹出,将获取到的值压入到栈顶
lua_getfield
void lua_getfield (lua_State *L, int index, const char *k); //这个东西会调用到元方法
取index处的table,通过字符串k,将获取到的值压入到栈顶 //只可以字符串哦~
lua_gettable vs lua_getfield
lua_gettable可以处理多种多样的键值,但是需要借助到栈。lua_getfield更方便,但是只可以处理字符串的键。其实这很好理解,因为基本上只有字符串时Lua和C通用的,其他类型也没办法直接通过C表达。
值得一提的是,他们的底层实现其实都是luaV_gettable,只不过后者自行创建的lua类型TValue:
setsvalue(L, &key, luaS_new(L, k));
lua_createtable
void lua_createtable (lua_State *L, int narr, int nrec);
创建table并初始化大小,调用的是luaH_new(L, narray, nrec)。LuaH的逻辑是先分配空表的空间,再根据数组部分以及哈希部分重新分配内存。
lua_settable
void lua_settable (lua_State *L, int index);
值在-1,键在-2,表在index。设置完值后,会将键和值弹出
lua_rawseti
void lua_rawseti (lua_State *L, int index, int n);
表在index,值在-1,键是n。
lua_setmetatable
int lua_setmetatable (lua_State *L, int index);
表在index,元表在-1,设置完会弹出元表。