lua 与 c/c++ 交互(3)c/c++ 调用 lua 数组类型 table

来源:互联网 发布:掷骰子抽奖js特效 编辑:程序博客网 时间:2024/04/29 23:43

c调用lua数组

上节说的 通过 lua_getfield获取 lua Table,只能 获取 字符型 的 table的值

这一节,补充 一下 怎么 获取 数组 型 table

test.lua  增加了 一个 数组型 table  (在 上节的 基础上)

array = {111,222,333}

cpp  (在 上节 cpp的基础上 添加)

//获取array

lua_getglobal(l,"array");

lua_pushinteger(l,1);

lua_gettable(l,-2);

if (lua_isnumber(l,-1))

{

int one = lua_tointeger(l,-1);

printf("\n获取lua 数组 %d",one);

lua_pop(l,1);

}

//设置 array

lua_pushinteger(l,1);//key

lua_pushinteger(l,99);//value

lua_settable(l,-3);

//验证

lua_getglobal(l,"array");

lua_pushinteger(l,1);

lua_gettable(l,-2);

if (lua_isnumber(l,-1))

{

int one = lua_tointeger(l,-1);

printf("\n验证lua 数组 %d",one);

lua_pop(l,1);

}


总结: 看 lua 源码 就知道 lua_getfield 其实 就是 调用了 类似 lua_gettable 的函数 ,有兴趣的可以 用源码的 方式 加载 lua 跟踪进去 看看.
LUA_API void lua_getfield (lua_State *L, int idx, const char *k) {
  StkId t;
  TValue key;
  lua_lock(L);
  t = index2adr(L, idx);
  api_checkvalidindex(L, t);
  setsvalue(L, &key, luaS_new(L, k));
  luaV_gettable(L, t, &key, L->top);
  api_incr_top(L);
  lua_unlock(L);
}


0 0
原创粉丝点击