C++对Lua中table进行读取、修改和创建

来源:互联网 发布:香港的淘宝叫什么名字 编辑:程序博客网 时间:2024/06/01 18:21

C++代码:

[cpp] view plain copy
  1. // LuaAndC.cpp : 定义控制台应用程序的入口点。  
  2. //  
  3.   
  4. #include "stdafx.h"  
  5.   
  6.   
  7. #include <iostream>    
  8. #include <string.h>    
  9. using namespace std;    
  10.      
  11. extern "C"    
  12. {    
  13.     #include "lua.h"    
  14.     #include "lauxlib.h"    
  15.     #include "lualib.h"    
  16. }    
  17.   
  18.   
  19. int _tmain(int argc, _TCHAR* argv[])  
  20. {  
  21.      //1.创建一个state    
  22.     lua_State *L = luaL_newstate();    
  23.   
  24.     luaL_openlibs(L);  
  25.     luaL_dofile(L,"Hello.lua");  
  26.       
  27.     //获取table的值  
  28.     lua_getglobal(L,"str");  
  29.   
  30.     //会将get的对应项压到栈顶  
  31.     lua_getfield(L,1,"name");  
  32.     lua_getfield(L,1,"age");  
  33.   
  34.     if(lua_isstring(L,2))  
  35.     {  
  36.         cout<<"name= "<<lua_tostring(L,-2)<<endl;  
  37.     }  
  38.     if(lua_isnumber(L,3))  
  39.     {  
  40.         cout<<"age= "<<lua_tonumber(L,-1)<<endl;  
  41.     }  
  42.     lua_pop(L,2);  
  43.   
  44.     //修改table的项  
  45.     lua_pushfstring(L,"So so");//改完弹出  
  46.     lua_setfield(L,1,"name");  
  47.     lua_getfield(L,1,"name");  
  48.     if(lua_isstring(L,2))  
  49.     {  
  50.         cout<<"name1= "<<lua_tostring(L,2)<<endl;  
  51.     }  
  52.     lua_pop(L,2);  
  53.   
  54.     //新建table  
  55.     lua_newtable(L); //压栈  
  56.     lua_pushnumber(L,11);  
  57.     lua_pushstring(L,"New");  
  58.     lua_setfield(L,1,"name");  
  59.     lua_setfield(L,1,"age");  
  60.     lua_getfield(L,1,"name");  
  61.     lua_getfield(L,1,"age");  
  62.     if(lua_isstring(L,2))  
  63.     {  
  64.         cout<<"name= "<<lua_tostring(L,2)<<endl;  
  65.     }  
  66.     if(lua_isnumber(L,3))  
  67.     {  
  68.         cout<<"age= "<<lua_tonumber(L,3)<<endl;  
  69.     }  
  70.   
  71.     lua_pop(L,3);  
  72.   
  73.     //关闭state    
  74.     lua_close(L);    
  75.       
  76.     int i;  
  77.     cin>>i;  
  78.     return 0 ;    
  79. }  


 

Lua代码:

[plain] view plain copy
  1. str={name="Hunter",age=18}  


 

阅读全文
0 0
原创粉丝点击