C++调用Lua

刚开始学习C++调用Lua 是获取lua脚本中的全局变量,却怎么也调用不到,找了半天原因终于找到,如下所示加粗标红的部分

lua_State *L = luaL_newstate();
    if (L == NULL)
    {
        return 1;
    }
    luaL_openlibs(L);
    //lua_register(L,"TestPush", TestPush);

    int ret = luaL_dofile(L,"main.lua");
    
    if (ret)
    {
        printf("Lua doFile Error !\n");
    }    
    //lua_getglobal(L, "width");
    ret = lua_pcall(L, 0, 0, 0);

    lua_getglobal(L, "width");//当调用lua脚本中的全局变量时必须放在lua_pcall后面
    int width = lua_tonumber(L, -1);
    printf("width = %d\n", width);
    lua_pop(L, 1);

   
    
    //无参
    lua_getglobal(L, "ruler");//当调用lua脚本中的函数时必须放在lua_pcall前面
    ret = lua_pcall(L, 0, 0, 0);
    
    if (ret)
    {
        printf("pcall error \n");    
        
    }
    
    //有参
    lua_getglobal(L,"add");
    lua_pushnumber(L, 1);
    lua_pushnumber(L, 2);

    ret = lua_pcall(L,2,1,0);
    if (ret)
    {
        printf("pcall error \n");
    }
    if (lua_isnumber(L,-1))
    {
        int result = lua_tonumber(L, -1);//先分出来再调用
        printf("the result is :%d", result);//使用printf必须先调用后打印,cout可以直接调用
    }
    lua_close(L);

    getchar();

 

脚本如下:

function ruler()
    print("this is some thing need to tell you !!!");
end

function add(a,b)
    return a+b;
end

width = 2019
 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值