c++操作lua表

来源:互联网 发布:淘宝迷你音响 编辑:程序博客网 时间:2024/06/08 08:57
/*1.取表中的元素void lua_getfield (lua_State *L, int index, const char *k)说明:从栈中取出下标为index的表,并将此表键为k的值压入栈中操作:arr = Stack[index]      取出表Stack.push( arr[k] )    将表的元素压入栈中2.给表中的元素赋值void lua_setfield (lua_State *L, int index, const char *k)说明:从栈中取出下标为index的表,并给此表键为k的元素赋值value(value为栈顶元素),最后弹出栈顶元素操作:   arr = Stack[index]       取出表arr[k] = Stack.top()     给k赋值Stack.pop()              弹出栈顶元素栈高度-1, 被弹出的是value注意, 该操作将触发 __newindex 元方法*/table.lua文本

title=”Description of personal information”–个人信息描述
ta_info={address=”guangdong”,name=”liuwen”,age=26,sex=1,birth=”1991-02-25”}

//1.创建Lua状态  lua_State *L = luaL_newstate();  if (L == NULL)  {      return ;  }  //2.加载Lua文件  int bRet = luaL_loadfile(L,"table.lua");  if(bRet)  {      OutputDebugString("lwlog::load file error");      return ;  }  //3.运行Lua文件  bRet = lua_pcall(L,0,0,0);  if(bRet)  {      OutputDebugString("lwlog::pcall error");     return ;  }  //4.读取变量  lua_getglobal(L,"title");  string str = lua_tostring(L,-1); CString lwlog;lwlog.Format("lwlog::title=%s",str.c_str());OutputDebugString(lwlog);    //5.读取table  lua_getglobal(L,"ta_info");//读取address元素lua_getfield(L,-1,"address");  str = lua_tostring(L,-1);  lwlog.Format("lwlog::ta_info::address=%s",str.c_str());OutputDebugString(lwlog);  //读取name元素lua_getfield(L,-2,"name");  str = lua_tostring(L,-1);  lwlog.Format("lwlog::ta_info::name=%s",str.c_str());OutputDebugString(lwlog); //读取age元素lua_getfield(L,-3,"age");    lwlog.Format("lwlog::ta_info::age=%f",lua_tonumber(L,-1));OutputDebugString(lwlog); //读取sex元素lua_getfield(L,-4,"sex");    lwlog.Format("lwlog::ta_info::sex=%f",lua_tonumber(L,-1));OutputDebugString(lwlog); //读取birth元素lua_getfield(L,-5,"birth");  str = lua_tostring(L,-1);lwlog.Format("lwlog::ta_info::birth=%s",str.c_str());OutputDebugString(lwlog); //改变name元素的值lua_pushstring(L,"zhangyang");lua_setfield(L,-7,"name");lua_getfield(L,-6,"name");  str = lua_tostring(L,-1);  lwlog.Format("lwlog::ta_info::name改变值=%s",str.c_str());OutputDebugString(lwlog);     lwlog.Format("lwlog::lua_gettop栈大小=%d",lua_gettop(L));OutputDebugString(lwlog);  //至此,栈中的情况是:  //=================== 栈顶 ===================   //  索引  类型      值  //  -1   string:   zhangyang//  -2   string:   1991-02-25//  -3   double:   1//  -4   double:   26 //  -5   string:   zhangyang //  -6   string:   guangdong   //  -7   table:     ta_info  //  -8   string:    Description of personal information  //=================== 栈底 ===================  //关闭state  lua_close(L); 

输出:
这里写图片描述

原创粉丝点击