Lua教程(四):在Lua中調用C語言、C++的函數_Lua

來源:互聯網
上載者:User

本教程將介紹如何在Lua裡面調用c/c++函數。

在Lua裡面調用c/c++函數其實是比較簡單,本文將通過兩個樣本示範具體的做法:一個是求平均數,另一個是列印lua函數的一些參數資訊。

最後,本文會介紹如何把這兩個函數定義成一個模組,這樣lua代碼裡面就可以不再使用全域的名字空間了。

前言

當我們需要在Lua裡面調用c/c++函數時,所有的函數都必須滿足以下函數簽名:

複製代碼 代碼如下:

typedef int (*lua_CFunction) (lua_State *L);

換句話說,所有的函數必須接收一個lua_State作為參數,同時返回一個整數值。因為這個函數使用Lua棧作為參數,所以它可以從棧裡面讀取任意數量和任意類型的參數。而這個函數的傳回值則表示函數返回時有多少傳回值被壓入Lua棧。(因為Lua的函數是可以返回多個值的)

樣本一

定義C++函數指標

複製代碼 代碼如下:

int average(lua_State *L)
{
    // get number of arguments
    int n = lua_gettop(L);
    double sum = 0;
    int i;
    // loop through each argument
    for (i = 1; i <= n; i++)
    {
        // total the arguments
        sum += lua_tonumber(L, i);
    }
    // push the average
    lua_pushnumber(L, sum / n);
    // push the sum
    lua_pushnumber(L, sum);
    // return the number of results
    return 2;
}

註冊此函數給Lua

複製代碼 代碼如下:

lua_register(L, "average", average);

Lua裡面調用此函數

複製代碼 代碼如下:

avg, sum = average(10, 20, 30, 40, 50)
print("The average is ", avg)
print("The sum is ", sum)

樣本二

定義C++函數

複製代碼 代碼如下:

int displayLuaFunction(lua_State *l)
{
    // number of input arguments
    int argc = lua_gettop(l);
    // print input arguments
    std::cout << "[C++] Function called from Lua with " << argc
              << " input arguments" << std::endl;
    for(int i=0; i<argc; i++)
    {
        std::cout << " input argument #" << argc-i << ": "
                  << lua_tostring(l, lua_gettop(l)) << std::endl;
        lua_pop(l, 1);
    }
    // push to the stack the multiple return values
    std::cout << "[C++] Returning some values" << std::endl;
    lua_pushnumber(l, 12);
    lua_pushstring(l, "See you space cowboy");
    // number of return values
    return 2;
}

註冊此Lua函數

複製代碼 代碼如下:

 // push the C++ function to be called from Lua
    std::cout << "[C++] Pushing the C++ function" << std::endl;
    lua_pushcfunction(L, displayLuaFunction);
    lua_setglobal(L, "displayLuaFunction");

注意,上一個樣本,我們使用的是函數是

複製代碼 代碼如下:

lua_register(L, "average", average);

它其實只是一個宏定義,其實現也是上面兩個函數組成的。

在Lua裡調用此函數

複製代碼 代碼如下:

io.write('[Lua] Calling the C functionn')
a,b = displayLuaFunction(12, 3.141592, 'hola')
-- print the return values
io.write('[Lua] The C function returned <' .. a .. '> and <' .. b .. '>\n')

實現一個Lua模組

首先,我們把這兩個C函數封裝到一個數組裡面:

複製代碼 代碼如下:

static const luaL_Reg mylibs[]=
{
    {"average", average},
    {"displayLuaFunction", displayLuaFunction},
    {NULL, NULL}
};

接下來,我們定義另一個C函數,讓它註冊我們的Lua模組:

複製代碼 代碼如下:

int lua_openmylib(lua_State *L)
{
    luaL_newlib(L, mylibs);
    return 1;
};

這裡的luaL_newlib會產生一個table,並把所有的mylibs裡面的函數填充進去。最後,lua_openmylib傳回值為1,表示會把剛剛產生的table壓入棧。

最後,我們像之前註冊Lua的標準庫一樣,註冊我們新的庫,並給它起名字為mylib:

複製代碼 代碼如下:

  static const luaL_Reg lualibs[] =
    {
        {"base", luaopen_base},
        {"io", luaopen_io},
        {"mylib", lua_openmylib},
        {NULL, NULL}
    };

此時,我們在Lua裡面調用之前的兩個函數就需要帶上模組名字首碼了:

複製代碼 代碼如下:

avg, sum = mylib.average(10, 20, 30, 40, 50)
a,b = mylib.displayLuaFunction(12, 3.141592, 'hola')

結語

注意:這裡C函數參數裡的Lua棧是私人的,每一個函數都有自己的棧。當一個c/c++函數把傳回值壓入Lua棧以後,該棧會自動被清空。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.