当前位置: 首页 > news >正文

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

通过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:%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

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");  //整体输入一个大的 tablefor (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,但是数字应该只能写中括号的形式

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

http://www.lryc.cn/news/240283.html

相关文章:

  • 算法复杂度分析
  • 几款Java源码扫描工具(FindBugs、PMD、SonarQube、Fortify、WebInspect)
  • java springboot测试类鉴定虚拟MVC请求 返回内容与预期值是否相同
  • MongoDB随记
  • 839 - Not so Mobile (UVA)
  • php字符串处理函数的使用
  • UEC++ day8
  • 学习记录——ipv4、ipv6与ip、DNS、网络协议
  • cefsharp119.4.30(cef119.4.3,Chromium119.0.6045.159)版本升级体验支持H264及其他多个H264版本
  • “index“ should always be multi-word
  • 服务器64GB内存、8核CPU的MySQL 8配置参数
  • Python+Qt虹膜检测识别
  • 我的创作纪念日——365天
  • 安卓手机便签APP用哪个,手机上好用的便签APP是什么
  • 前端Date对象的使用锦集
  • 如何将ONLYOFFICE与Python应用程序集成
  • vector的简单模拟实现_C++
  • 合并两个有序链表,剑指offer,力扣
  • Delphi 12 Athens 发布了!
  • 基于Haclon的Blob分析
  • 安卓手机好用的清单软件有哪些?
  • 【追求卓越02】数据结构--链表
  • qt按照不同编码格式读取文字(UTF-16LE,UTF-8,UTF-8BOM,UTF-16BE)
  • R语言和RStudio的下载安装(非常简便舒适)
  • SQL注入漏洞发现和利用,以及SQL注入的防护
  • Jmeter 分布式压测
  • Docker 安装 Apache
  • python变量、常量、数据类型
  • 注册中心CAP架构剖析
  • SVN创建分支