lua调C的返回table

第一个问题是lua调C的返回值的问题 
//测试返回table
lua调C的返回table - Dreaming - Dong Minority Tribe lua调C的返回table - Dreaming - Dong Minority Tribe /**//**
 下面代码相当lua如下:
 function return_table()
 local t = {}
 t.result = true
 t.data = "hello"
 return t
 end
 */
int tableReturnTable(lua_State * L)
lua调C的返回table - Dreaming - Dong Minority Tribe lua调C的返回table - Dreaming - Dong Minority Tribe {
 lua_newtable(L);
 int table_index = lua_gettop(L);

 lua_pushboolean(L, true);
 lua_setfield(L, table_index, "result");

 lua_pushstring(L, "hello", 5);
 lua_setfield(L, table_index, "data"); 

 return 1;
}
第二问题多参数返回
//测试多返回
/**
下面代码相当lua如下:
function mult_return()
return "hello",100,true
end
*/
int mult_return(lua_Status * L)
{
lua_pushstring(L, "hello");
lua_pushnumber(L,100);
lua_pushboolean(L,true);
return 3;
}
第三个问题,删除表中的元素
local t = {}
t.hello = "hello“
t[1] = 100
删除办法如下:
t.hello = nil
t[1] = nil
清空table
table.foreach(t, function(k,v) t[k] = nil end)
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
详细描述Lua和C之间相互传递Table类型数据 /* ====================================================== */ // 遍历Lua传入的Table类型参数, 获取它的Key/Value, 其关键操作是 lua_next() // lua_next() 返回1表示读取成功,返回0表示已经没有数据可读了 // lua_next() 会使用栈顶元素作为Key去定位本次需要取出Table里面的那个值对 // 如果Key=nil, 那就表示本次取出的是第一个元素 // 它会先将当前的这个Key弹出,然后将本次取出的Key/Value压入栈, Value在栈顶 // 一个比较隐晦的处理就是, 我们不应直接使用lua_tostring(L, -2)来读取Key // 因为lua_tostring()在Key类型不是字符串时, 它会修改栈上的Key数据 // 这样, 下次lua_next()时, 就会因为Key被修改了而导致错误 // 为此,先lua_pushvalue(L, -2),将它Copy一份到栈顶,对这个Copy进行lua_tostring() // 读取Key,Value到C变量里面后,将Value和Copy弹出,留着Key在栈顶,给下次lua_next()用 // // 指令及栈图变化如下: (假如Table的栈下标是Index) // 0. 刚进入函数时 ...Table, ... <--- 这里栈顶 // 1. lua_pushnil(L) ...Table, ..., nil <--- 这里栈顶 // 2. lua_next(L, Index) ...Table, ..., Key, Value <--- 这里栈顶 // 3. lua_pushvalue(L, -2) ...Table, ..., Key, Value, KeyCopy <--- 这里栈顶 // 4. lua_pop(L, 2), ...Table, ..., Key <--- 这里栈顶 // ... 如此重复2,3,4 // N. lua_next(L, Index)返回0 ...Table, ... <--- 这里栈顶 /* ====================================================== */
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值