VC编译LUA与调用

环境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;  
} 


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值