lua table操作函数

目录

 

lua_getfield

lua_setfield

lua_gettable

lua_settable

lua_rawget

lua_rawset

lua_rawgeti

lua_rawseti

区别


lua_getfield

  1. 原型:void lua_getfield (lua_State *L, int index, const char *k);
  2. 解释:把 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

  1. 原型:void lua_setfield (lua_State *L, int index, const char *k);
  2. 解释:这个函数将把这个值弹出堆栈

设置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

  1. 原型:void lua_gettable (lua_State *L, int index);
  2. 解释:将值推到堆栈上,在给定有效索引中值在哪里,在堆栈顶部推入值。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

  1. 原型:void lua_settable (lua_State *L, int index);
  2. 解释:作一个等价于 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

 

 

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值