环境vs2012,lua版本5.2.1
新件一个空项目,添加所有src内的文件,然后移除lua.c, lua.h, luac.c,文件(如果有 print.c也移除)
选择项目-属性-配置属性-常规-配置类型,即可选择生成静态库lib或动态库dll.
下面演示一个c++调用lua函数的例子.
test.lua代码
- function MaxMin(x, y)
- if x > y then
- return "x > y", x, y
- elseif x == y then
- return "x = y", x, y
- else
- return "y > x", y, x
- end
- end
在建一新的C程序:
c++代码
- extern "C" {
- #include "../lua5.2/src/lua.h"
- #include "../lua5.2/src/lauxlib.h"
- #include "../lua5.2/src/lualib.h"
- };
- #pragma comment(lib, "../Release/lua5.2.lib")
- void MaxMin(lua_State* L, int x, int y)
- {
- lua_getglobal(L, "MaxMin");
- //参数1
- lua_pushnumber(L, x);
- //参数2
- lua_pushnumber(L, y);
- //2个参数,3个返回值
- lua_pcall(L, 2, 3, 0);
- const char* c = lua_tostring(L, -3);
- lua_Number n1 = lua_tonumber(L, -2);
- lua_Number n2 = lua_tonumber(L, -1);
- cout<<c<<" "<<"Max = "<<n1<<", Min = "<<n2<<endl;
- //元素出栈
- lua_pop(L, 3);
- }
- int _tmain(int argc, _TCHAR* argv[])
- {
- lua_State* L = luaL_newstate();
- if(!luaL_loadfile(L, "d:\\test.lua"))
- {
- if(!lua_pcall(L, 0, 0, 0))
- {
- MaxMin(L, 1, 2);
- MaxMin(L, 3, 3);
- MaxMin(L, 9, 8);
- }
- }
- lua_close(L);
- return 0;
- }
- y > x Max = 2, Min = 1
- x = y Max = 3, Min = 3
- x > y Max = 9, Min = 8
- 请按任意键继续. . .