c++调用Lua(table嵌套写法)

通过c++调用lua接口将数据存储到虚拟栈中,就可以在lua脚本在虚拟栈中取得数据

c++调用lua库,加载lua文件,

cpp 复制代码
lua_State* L;//定义一个全局变量

***************************

    L = luaL_newstate();
    luaL_openlibs(L);
    //打开Lua脚本文件
    std::string path = SysContext::instance()->_env["WORKSPACE"] + "test.lua";
    luaL_dofile(L, path.c_str());
    lua_getglobal(L, "output");  //加载lua文件中的output函数
    pushLua(ObjsData(数据));
    int iRet = lua_pcall(L, 1, 1, 0);

    if (iRet)  // 调用出错
    {
      const char* pErrorMsg = lua_tostring(L, -1);
      lua_pop(L, 1);
      lua_close(L);
      return 1;
    }

    if (lua_isnumber(L, -1))  //取值输出
    {
      int fValue = lua_tonumber(L, -1);
      printf("fValue:%f\n", fValue);
      //do something
    }
    if (lua_isstring(L, -1))  //取值输出
    {
      std::string s = lua_tostring(L, -1);
      // do something
    }
    lua_close(L);

以下为c++调用lua接口存储数据

其中 lua_settable(L, -3);

就是把表在lua堆栈中的值弹出来,index 是table 在堆栈中的位置,假如 table 在 -3, 则key 应该是 -2,value 是 -1

结构:最外层table=count+objs,count和objs都是一个table,objs内部又包含很多个table

cpp 复制代码
void pushLua(ObjsData* obj) {
  int ntop = lua_gettop(L);
  lua_newtable(L);

  lua_pushstring(L, "count");  //这里需要output多一个输入
  lua_pushnumber(L, obj->count);
  lua_settable(L, -3);

  lua_pushstring(L, "objs");  //整体输入一个大的 table
  for (int i = 0; i < obj->count; i++) {
    const SingleObj* p = (const SingleObj*)&obj[1];
    lua_newtable(L);
    lua_pushnumber(L, i);

    lua_newtable(L);

    lua_pushstring(L, "x");
    lua_pushnumber(L, p->x);
    lua_settable(L, -3);

    lua_pushstring(L, "y");
    lua_pushnumber(L, p->y);
    lua_settable(L, -3);

    lua_pushstring(L, "z");
    lua_pushnumber(L, p->z);
    lua_settable(L, -3);

    lua_pushstring(L, "Volume");
    lua_pushnumber(L, p->volume);
    lua_settable(L, -3);

    lua_settable(L, -3);
  }
  lua_settable(L, -3);
}

lua脚本如下:

注意:table(键值对结构)嵌套,在取值的时候采用中括号取值,如objs[0]["x"],若key值是字符串,可以写成objs[0].x,但是数字应该只能写中括号的形式

Lua 复制代码
str = "test" 
function output(x)
   print(x.objs[0].x)
    res= "count="..tostring(x.count)..",x="..tostring(x.objs[0].x)..",y="..tostring(x.objs[0].y).."\n"
    return res
end

参考:[Resolved] How to create nested Lua tables using the C API

相关推荐
「QT(C++)开发工程师」1 小时前
C++语言编程规范-并发
java·linux·c++
1白天的黑夜12 小时前
递归-21.合并两个有序链表-力扣(LeetCode)
c++·leetcode·链表·递归
adny-code2 小时前
[fastgrind] 一个轻量级C++内存监控及可视化开源库
c++·内存·性能分析·高性能计算
郝学胜-神的一滴3 小时前
Linux系统函数link、unlink与dentry的关系及使用注意事项
linux·运维·服务器·开发语言·前端·c++
赵杰伦cpp3 小时前
list的迭代器
开发语言·数据结构·c++·算法·链表·list
老歌老听老掉牙3 小时前
使用 OpenCASCADE 提取布尔运算后平面图形的外轮廓
c++·平面·opencascade
闻缺陷则喜何志丹3 小时前
【动态规划】数位DP的原理、模板(封装类)
c++·算法·动态规划·原理·模板·数位dp
胖咕噜的稞达鸭4 小时前
二叉树搜索树插入,查找,删除,Key/Value二叉搜索树场景应用+源码实现
c语言·数据结构·c++·算法·gitee
进击的大海贼4 小时前
QT-C++ 自定义加工统计通用模块
开发语言·c++·qt
lingran__4 小时前
算法沉淀第四天(Winner)
c++·算法