本文介绍: 注意:table键值结构嵌套,在取值的时候采用中括号取值,如objs[0][“x“],若key值是字符串可以写成objs[0].x,但是数字应该只能写中括号的形式。通过c++调用lua接口数据存储虚拟栈中,就可以lua脚本虚拟栈中取得数据c++调用lua库,加载lua文件,以下为c++调用lua接口存储数据

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

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

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:%fn", 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堆栈中的值弹出来,indextable 在堆栈中的位置,假如 table 在 -3, 则key 应该是 -2,value 是 -1

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

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*)&amp;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,但是数字应该只能写中括号的形式

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

原文地址:https://blog.csdn.net/xiachong27/article/details/134527632

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。

如若转载,请注明出处:http://www.7code.cn/show_8921.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱:suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注