c++操作lua表

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

输出:
这里写图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值