环境vs2010,lua版本5.2新件一个空项目,添加所有src内的文件,然后移除lua.c, lua.h, luac.c, print.c文件.
选择项目-属性-配置属性-常规-配置类型,即可选择生成静态库或动态库.
下面演示一个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++代码
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
};
#pragma comment(lib, "../Debug/lua.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;
printf("%s Max = %f Min = %f\n", c, n1, n2);
//元素出栈
lua_pop(L, 3);
}
int main()
{
lua_State* L = luaL_newstate();
if(!luaL_loadfile(L, "D:\\DEMO\\LUA\\FirstLua\\Debug\\test.lua"))
{
if(!lua_pcall(L, 0, 0, 0))
{
MaxMin(L, 1, 2);
MaxMin(L, 3, 3);
MaxMin(L, 9, 8);
}
}
lua_close(L);
system("pause");
return 0;
}

4163

被折叠的 条评论
为什么被折叠?



