Lua教程(十九):C調用Lua_Lua

來源:互聯網
上載者:User

1. 基礎:

    Lua的一項重要用途就是作為一種配置語言。現在從一個簡單的樣本開始吧。
 

複製代碼 代碼如下:

    --這裡是用Lua代碼定義的視窗大小的配置資訊
    width = 200
    height = 300
 

    下面是讀取配置資訊的C/C++代碼:  

複製代碼 代碼如下:

#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>

void load(lua_State* L, const char* fname, int* w, int* h) {
    if (luaL_loadfile(L,fname) || lua_pcall(L,0,0,0)) {
        printf("Error Msg is %s.\n",lua_tostring(L,-1));
        return;
    }
    lua_getglobal(L,"width");
    lua_getglobal(L,"height");
    if (!lua_isnumber(L,-2)) {
        printf("'width' should be a number\n" );
        return;
    }
    if (!lua_isnumber(L,-1)) {
        printf("'height' should be a number\n" );
        return;
    }
    *w = lua_tointeger(L,-2);
    *h = lua_tointeger(L,-1);
}


int main()
{
    lua_State* L = luaL_newstate();
    int w,h;
    load(L,"D:/test.lua",&w,&h);
    printf("width = %d, height = %d\n",w,h);
    lua_close(L);
    return 0;
}

下面是針對新函數的解釋:

    lua_getglobal是宏,其原型為:#define lua_getglobal(L,s)  lua_getfield(L, LUA_GLOBALSINDEX, (s))。

    每次調用這個宏的時候,都會將Lua代碼中與之相應的全域變數值壓入棧中,第一次調用時將全域變數"width"的值壓入棧中,之後再次調用時再將"height"的值也壓入棧中。

    2. table操作:

    我們可以在C語言的代碼中操作Lua中的table資料,這是一個非常非常方便且實用的功能。這樣不僅可以使Lua代碼的結構更加清晰,也可以在C語言代碼中定義等同的結構體與之對應,從而大大提高代碼的可讀性。見如下代碼:

複製代碼 代碼如下:

#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>

void load(lua_State* L) {

    if (luaL_loadstring(L,"background = { r = 0.30, g = 0.10, b = 0 }")
        || lua_pcall(L,0,0,0)) {
        printf("Error Msg is %s.\n",lua_tostring(L,-1));
        return;
    }
    lua_getglobal(L,"background");
    if (!lua_istable(L,-1)) {
        printf("'background' is not a table.\n" );
        return;
    }
    lua_getfield(L,-1,"r");
    if (!lua_isnumber(L,-1)) {
        printf("Invalid component in background color.\n");
        return;
    }
    int r = (int)(lua_tonumber(L,-1) * 255);
    lua_pop(L,1);
    lua_getfield(L,-1,"g");
    if (!lua_isnumber(L,-1)) {
        printf("Invalid component in background color.\n");
        return;
    }
    int g = (int)(lua_tonumber(L,-1) * 255);
    lua_pop(L,1);

    lua_pushnumber(L,0.4);
    lua_setfield(L,-2,"b");

    lua_getfield(L,-1,"b");
    if (!lua_isnumber(L,-1)) {
        printf("Invalid component in background color.\n");
        return;
    }
    int b = (int)(lua_tonumber(L,-1) * 255);
    printf("r = %d, g = %d, b = %d\n",r,g,b);
    lua_pop(L,1);
    lua_pop(L,1);
    return;
}

int main()
{
    lua_State* L = luaL_newstate();
    load(L);
    lua_close(L);
    return 0;
}

void lua_getfield(lua_State *L, int idx, const char *k); 第二個參數是table變數在棧中的索引值,最後一個參數是table的索引值,該函數執行成功後會將欄位值壓入棧中。

void lua_setfield(lua_State *L, int idx, const char *k); 第二個參數是table變數在棧中的索引值,最後一個參數是table的鍵名稱,而欄位值是通過上一條命令lua_pushnumber(L,0.4)壓入到棧中的,該函數在執行成功後會將剛剛壓入的欄位值彈出棧。
   
下面的程式碼範例是在C語言代碼中構造table對象,同時初始化table的欄位值,最後再將table對象賦值給Lua中的一個全域變數。

複製代碼 代碼如下:

#include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>

void load(lua_State* L)
{
    lua_newtable(L);
    lua_pushnumber(L,0.3);
    lua_setfield(L,-2,"r");

    lua_pushnumber(L,0.1);
    lua_setfield(L,-2,"g");

    lua_pushnumber(L,0.4);
    lua_setfield(L,-2,"b");
    lua_setglobal(L,"background");

    lua_getglobal(L,"background");
    if (!lua_istable(L,-1)) {
        printf("'background' is not a table.\n" );
        return;
    }
    lua_getfield(L,-1,"r");
    if (!lua_isnumber(L,-1)) {
        printf("Invalid component in background color.\n");
        return;
    }
    int r = (int)(lua_tonumber(L,-1) * 255);
    lua_pop(L,1);
    lua_getfield(L,-1,"g");
    if (!lua_isnumber(L,-1)) {
        printf("Invalid component in background color.\n");
        return;
    }
    int g = (int)(lua_tonumber(L,-1) * 255);
    lua_pop(L,1);

    lua_getfield(L,-1,"b");
    if (!lua_isnumber(L,-1)) {
        printf("Invalid component in background color.\n");
        return;
    }
    int b = (int)(lua_tonumber(L,-1) * 255);
    printf("r = %d, g = %d, b = %d\n",r,g,b);
    lua_pop(L,1);
    lua_pop(L,1);
    return;
}

int main()
{
    lua_State* L = luaL_newstate();
    load(L);
    lua_close(L);
    return 0;
}

 上面的代碼將輸出和之前代碼相同的結果。

    lua_newtable是宏,其原型為:#define lua_newtable(L) lua_createtable(L, 0, 0)。調用該宏後,Lua會產生一個新的table對象並將其壓入棧中。

    lua_setglobal是宏,其原型為:#define lua_setglobal(L,s) lua_setfield(L,LUA_GLOBALSINDEX,(s))。調用該宏後,Lua會將當前棧頂的值賦值給第二個參數指定的全域變數名。該宏在執行成功後,會將剛剛賦值的值從棧頂彈出。

    3. 調用Lua函數:

    調用函數的API也很簡單。首先將待調用函數壓入棧,再壓入函數的參數,然後使用lua_pcall進行實際的調用,最後將調用結果從棧中彈出。見如下代碼:
 

複製代碼 代碼如下:

 #include <stdio.h>
#include <string.h>
#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>

const char* lua_function_code = "function add(x,y) return x + y end";

void call_function(lua_State* L)
{
    //luaL_dostring 等同於luaL_loadstring() || lua_pcall()
    //注意:在能夠調用Lua函數之前必須執行Lua指令碼,否則在後面實際調用Lua函數時會報錯,
    //錯誤資訊為:"attempt to call a nil value."
    if (luaL_dostring(L,lua_function_code)) {
        printf("Failed to run lua code.\n");
        return;
    }
    double x = 1.0, y = 2.3;
    lua_getglobal(L,"add");
    lua_pushnumber(L,x);
    lua_pushnumber(L,y);
    //下面的第二個參數表示帶調用的lua函數存在兩個參數。
    //第三個參數表示即使帶調用的函數存在多個傳回值,那麼也只有一個在執行後會被壓入棧中。
    //lua_pcall調用後,虛擬棧中的函數參數和函數名均被彈出。
    if (lua_pcall(L,2,1,0)) {
        printf("error is %s.\n",lua_tostring(L,-1));
        return;
    }
    //此時結果已經被壓入棧中。
    if (!lua_isnumber(L,-1)) {
        printf("function 'add' must return a number.\n");
        return;
    }
    double ret = lua_tonumber(L,-1);
    lua_pop(L,-1); //彈出傳回值。
    printf("The result of call function is %f.\n",ret);
}

int main()
{
    lua_State* L = luaL_newstate();
    call_function(L);
    lua_close(L);
    return 0;
}
 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.