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);输出: