C++将结构体传给lua

来源:互联网 发布:关于网络的手抄报图片 编辑:程序博客网 时间:2024/05/01 04:51

简单概要

就是将结构体传给lua。

代码

C++代码

[cpp] view plain copy
 print?
  1. void CProject1Dlg::OnBnClickedButton2()  
  2. {  
  3.     // 打开换为 luaL_newstate  
  4.     lua_State *L = luaL_newstate() ; /* 打开 Lua */  
  5.     luaL_openlibs(L); /* 加载 .lib 文件 */  
  6.   
  7.     // 加载脚本文件,需要放在程序目录  
  8.     luaL_loadfile( L, "test.lua" );  
  9.     lua_resume( L, 0 , 0);  
  10.       
  11.     typedef struct  
  12.     {  
  13.         int a;  
  14.         CString strTest;  
  15.   
  16.         struct test  
  17.         {  
  18.             int b;  
  19.         }c;  
  20.     }A;  
  21.   
  22.     A a;  
  23.     a.a = 10;  
  24.     a.c.b = 322;  
  25.     a.strTest = _T("yes");  
  26.     lua_getglobal(L,"structTest");    
  27.   
  28.     lua_newtable(L);  
  29.     lua_pushinteger(L,a.a);  
  30.     lua_setfield(L,-2,"a");  
  31.     lua_newtable(L);  
  32.     lua_pushinteger(L,a.c.b);  
  33.     lua_setfield(L,-2,"b");  
  34.     lua_setfield(L,-2,"c");  
  35.     lua_pushstring(L,CStringA(a.strTest).GetString());  
  36.     lua_setfield(L,-2,"strTest");  
  37.   
  38.     lua_pcall(L,1,1,NULL);  //   
  39.   
  40.     // 输出计算结果  
  41.     CString c = CString(lua_tostring(L,-1)) ;  
  42.     lua_pop(L,1) ;          // 清除堆栈 清除计算结果  
  43.   
  44.     // 调用结束  
  45.     lua_close(L);  
  46.   
  47.     MessageBox(c);  
  48. }  

Lua代码


[plain] view plain copy
 print?
  1. function structTest(a)  
  2.   
  3.     return string.format("做个测试 \r\n a.a = %d \n a.b = %d \n a.strTest = %s",  
  4.     a.a,a.c.b,a.strTest);  
  5.   
  6. end  

运行结果


0 0