1. 程式人生 > >用C++呼叫Lua函式--詳解

用C++呼叫Lua函式--詳解

    首先你要安裝lua的dev,安裝很簡單:

    yum install lua-devel

即可,很多Linux系統自帶Lua但是沒有dev,有點小坑。

    下面是Lua檔案,裡面就兩個函式:

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

function hello()
    print("Hello Lua!!!")
end

    之後是cpp檔案的呼叫程式碼:

#include<iostream>
#include<string>

using std::cout;
using std::endl;
using std::string;

//extern的意義,將下面檔案當成C風格檔案使用
extern "C"
{
    #include<lua.h>
    #include<lauxlib.h>
    #include<lualib.h>
}

int main()
{
    //建立環境
    lua_State *L = luaL_newstate();
    if(L == NULL)
    {   
        cout << "State error" << endl;
        return -1; 
    }   

    //載入庫
    luaL_openlibs(L);
    const string file = "func.lua";
    // 載入檔案
    int ret = luaL_dofile(L, file.c_str());
    if(ret)
    {   
        cout << "dofile error" << endl;
        return -1; 
    }   

    //hello函式沒有引數,直接呼叫
    lua_getglobal(L, "hello");
    lua_pcall(L, 0, 0, 0); //三個0含義,0實參,0返回值,0自定義錯誤處理

    lua_getglobal(L, "add");  
    //向add函式傳入兩個引數,這裡直接傳了1和2,傳變數也ok
    lua_pushnumber(L, 1);  
    lua_pushnumber(L, 2); 
    lua_pcall(L,2,1,0);        

    //返回值被放在-1的位置上
    cout << lua_tonumber(L, -1) << endl;

    lua_close(L);

    return 0;
}

    最後,還有很關鍵的一步,編譯時,我們需要加上附加選項:

    g++ main.cpp -o main -llua -ldl

看看結果:

    大功告成