目录
lua_getfield
- 原型:void lua_getfield (lua_State *L, int index, const char *k);
- 解释:把 t[k] 值压入堆栈 。
用于获取table中的键值,键k固定为字符串
lua_getglobal(L, "mytable") <== push mytable
lua_getfield(L, -1, "x") <== push mytable["x"],作用同下面两行调用
const char *value= lua_tostring(L, -1) 如果是字符串的值,获取方式
lua_setfield
- 原型:void lua_setfield (lua_State *L, int index, const char *k);
- 解释:这个函数将把这个值弹出堆栈
设置table的键值,键K固定为字符串。设置后建和值都被自动移除堆栈
ua_getglobal(L, "mytable") <== push mytable
lua_pushstring(L, "abc") <== push value "abc"
lua_setfield(L, -2, "x") <== mytable["x"] = "abc", pop value "abc"
lua_gettable
- 原型:void lua_gettable (lua_State *L, int index);
- 解释:将值推到堆栈上,在给定有效索引中值在哪里,在堆栈顶部推入值。t[k]tk
用于获取table中的键值,键k可以为任意类型,键优先压入堆栈
此功能从堆栈中弹出密钥,值在栈顶
lua_getglobal(L, "mytable") <== push mytable
lua_pushnumber(L, 1) <== push key 1
lua_gettable(L, -2) <== pop key 1, push mytable[1]
lua_settable
- 原型:void lua_settable (lua_State *L, int index);
- 解释:作一个等价于 t[k] = v 的操作, 这里 t 是一个给定有效索引 index 处的值, v 指栈顶的值, 而 k 是栈顶之下的那个值。这个函数会把键和值都从堆栈中弹出
lua_getglobal(L, "mytable") <== push mytable
lua_pushnumber(L, 1) <== push key 1
lua_pushstring(L, "abc") <== push value "abc"
lua_settable(L, -3) <== mytable[1] = "abc", pop key & value
lua_rawget
用法同lua_gettable,但更快(因为当key不存在时不用访问元方法__index)
lua_rawset
用法同lua_settable,但更快(因为当key不存在时不用访问元方法__newindex)
lua_rawgeti
必须为数值键
lua_getglobal(L, "mytable") <== push mytable
lua_rawgeti(L, -1, 1) <== push mytable[1],作用同下面两行调用
--lua_pushnumber(L, 1) <== push key 1
--lua_rawget(L,-2) <== pop key 1, push mytable[1]
lua_rawseti
必须为数值键
lua_getglobal(L, "mytable") <== push mytable
lua_pushstring(L, "abc") <== push value "abc"
lua_rawseti(L, -2, 1) <== mytable[1] = "abc", pop value "abc"
堆栈顺序是table在栈低方向,依次时key,value
区别
| 获取 | 设置 |
|
直接操作键,键不需要压堆栈 | lua_getfield | lua_setfield | 键固定位字符串 |
lua_rawgeti | lua_rawseti | 键固定位数值 | |
键需要压堆栈,键类型不限定
| lua_gettable | lua_settable | 两者的区别没测,未知 |
lua_rawget | lua_rawset |