/*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);
輸出: