VC编译LUA与调用

环境vs2012,lua版本5.2.1

新件一个空项目,添加所有src内的文件,然后移除lua.c, lua.h, luac.c,文件(如果有 print.c也移除)

选择项目-属性-配置属性-常规-配置类型,即可选择生成静态库lib或动态库dll.

下面演示一个c++调用lua函数的例子.

test.lua代码

[cpp]  view plain copy
  1. function MaxMin(x, y)  
  2.     if x > y then  
  3.         return "x > y", x, y  
  4.     elseif x == y then  
  5.         return "x = y", x, y  
  6.     else  
  7.         return "y > x", y, x  
  8.     end  
  9. end  

在建一新的C程序:

c++代码

[cpp]  view plain copy
  1. extern "C" {  
  2. #include "../lua5.2/src/lua.h"  
  3. #include "../lua5.2/src/lauxlib.h"  
  4. #include "../lua5.2/src/lualib.h"  
  5. };  
  6.   
  7. #pragma comment(lib, "../Release/lua5.2.lib")  
  8.   
  9. void MaxMin(lua_State* L, int x, int y)  
  10. {  
  11.     lua_getglobal(L, "MaxMin");  
  12.     //参数1  
  13.     lua_pushnumber(L, x);  
  14.     //参数2  
  15.     lua_pushnumber(L, y);  
  16.   
  17.     //2个参数,3个返回值  
  18.     lua_pcall(L, 2, 3, 0);  
  19.     const char* c = lua_tostring(L, -3);  
  20.     lua_Number n1 = lua_tonumber(L, -2);  
  21.     lua_Number n2 = lua_tonumber(L, -1);  
  22.   
  23.     cout<<c<<"  "<<"Max = "<<n1<<", Min = "<<n2<<endl;  
  24.   
  25.     //元素出栈  
  26.     lua_pop(L, 3);  
  27. }  
  28.   
  29. int _tmain(int argc, _TCHAR* argv[])  
  30. {  
  31.     lua_State* L = luaL_newstate();  
  32.   
  33.     if(!luaL_loadfile(L, "d:\\test.lua"))  
  34.     {  
  35.         if(!lua_pcall(L, 0, 0, 0))  
  36.         {  
  37.             MaxMin(L, 1, 2);  
  38.             MaxMin(L, 3, 3);  
  39.             MaxMin(L, 9, 8);  
  40.         }  
  41.     }  
  42.   
  43.     lua_close(L);  
  44.   
  45.     return 0;  
  46. }  
输出结果:

[html]  view plain copy
  1. > x  Max = 2Min = 1  
  2. x = y  Max = 3Min = 3  
  3. > y  Max = 9Min = 8  
  4. 请按任意键继续. . .  

猜你喜欢

转载自blog.csdn.net/angel725/article/details/8675273