Lua教程(二十二):userdata_Lua

來源:互聯網
上載者:User

在Lua中可以通過自訂類型的方式與C語言代碼更高效、更靈活的互動。這裡我們通過一個簡單完整的樣本來學習一下Lua中userdata的使用方式。需要說明的是,該樣本完全來自於Programming in Lua。其功能是用C程式實現一個Lua的布爾數組,以提供者的執行效率。見下面的代碼和關鍵性注釋。  

複製代碼 代碼如下:

#include <lua.hpp>
#include <lauxlib.h>
#include <lualib.h>
#include <limits.h>

#define BITS_PER_WORD (CHAR_BIT * sizeof(int))
#define I_WORD(i)     ((unsigned int)(i))/BITS_PER_WORD
#define I_BIT(i)      (1 << ((unsigned int)(i)%BITS_PER_WORD))

typedef struct NumArray {
    int size;
    unsigned int values[1];
} NumArray;

extern "C" int newArray(lua_State* L)
{
    //1. 檢查第一個參數是否為整型。以及該參數的值是否大於等於1.
    int n = luaL_checkint(L,1);
    luaL_argcheck(L, n >= 1, 1, "invalid size.");
    size_t nbytes = sizeof(NumArray) + I_WORD(n - 1) * sizeof(int);
    //2. 參數表示Lua為userdata分配的位元組數。同時將分配後的userdata對象壓入棧中。
    NumArray* a = (NumArray*)lua_newuserdata(L,nbytes);
    a->size = n;
    for (int i = 0; i < I_WORD(n - 1); ++i)
        a->values[i] = 0;
    //擷取註冊表變數myarray,該key的值為metatable。
    luaL_getmetatable(L,"myarray");
    //將userdata的元表設定為和myarray關聯的table。同時將棧頂元素彈出。
    lua_setmetatable(L,-2);
    return 1;
}

extern "C" int setArray(lua_State* L)
{
    //1. Lua傳給該函數的第一個參數必須是userdata,該對象的元表也必須是註冊表中和myarray關聯的table。
    //否則該函數報錯並終止程式。
    NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
    int index = luaL_checkint(L,2) - 1;
    //2. 由於任何類型的資料都可以成為布爾值,因此這裡使用any只是為了確保有3個參數。
    luaL_checkany(L,3);
    luaL_argcheck(L,a != NULL,1,"'array' expected.");
    luaL_argcheck(L,0 <= index && index < a->size,2,"index out of range.");
    if (lua_toboolean(L,3))
        a->values[I_WORD(index)] |= I_BIT(index);
    else
        a->values[I_WORD(index)] &= ~I_BIT(index);
    return 0;
}

extern "C" int getArray(lua_State* L)
{
    NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
    int index = luaL_checkint(L,2) - 1;
    luaL_argcheck(L, a != NULL, 1, "'array' expected.");
    luaL_argcheck(L, 0 <= index && index < a->size,2,"index out of range");
    lua_pushboolean(L,a->values[I_WORD(index)] & I_BIT(index));
    return 1;
}

extern "C" int getSize(lua_State* L)
{
    NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
    luaL_argcheck(L,a != NULL,1,"'array' expected.");
    lua_pushinteger(L,a->size);
    return 1;
}

extern "C" int array2string(lua_State* L)
{
    NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
    lua_pushfstring(L,"array(%d)",a->size);
    return 1;
}

static luaL_Reg arraylib_f [] = {
    {"new", newArray},
    {NULL, NULL}
};

static luaL_Reg arraylib_m [] = {
    {"set", setArray},
    {"get", getArray},
    {"size", getSize},
    {"__tostring", array2string}, //print(a)時Lua會調用該元方法。
    {NULL, NULL}
};

extern "C" __declspec(dllexport)
int luaopen_testuserdata(lua_State* L)
{
    //1. 建立元表,並將該元表指定給newArray函數新建立的userdata。在Lua中userdata也是以table的身份表現的。
    //這樣在調用對象函數時,可以通過驗證其metatable的名稱來確定參數userdata是否合法。
    luaL_newmetatable(L,"myarray");
    lua_pushvalue(L,-1);
    //2. 為了實現面對對象的調用方式,需要將元表的__index欄位指向自身,同時再將arraylib_m數組中的函數註冊到
    //元表中,之後基於這些註冊函數的調用就可以以物件導向的形式調用了。
    //lua_setfield在執行後會將棧頂的table彈出。
    lua_setfield(L,-2,"__index");
    //將這些成員函數註冊給元表,以保證Lua在尋找方法時可以定位。NULL參數表示將用棧頂的table代替第二個參數。
    luaL_register(L,NULL,arraylib_m);
    //這裡只註冊的Factory 方法。
    luaL_register(L,"testuserdata",arraylib_f);
    return 1;
}


 
輕量級userdata:

  之前介紹的是full userdata,Lua還提供了另一種輕量級userdata(light userdata)。事實上,輕量級userdata僅僅表示的是C指標的值,即(void*)。由於它只是一個值,所以不用建立。如果需要將一個輕量級userdata放入棧中,調用lua_pushlightuserdata即可。full userdata和light userdata之間最大的區別來自於相等性判斷,對於一個full userdata,它只是與自身相等,而light userdata則表示為一個C指標,因此,它與所有表示同一指標的light userdata相等。再有就是light userdata不會受到垃圾收集器的管理,使用時就像一個普通的整型數字一樣。

聯繫我們

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