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

1 #include <lua.hpp>
2 #include <lauxlib.h>
3 #include <lualib.h>
4 #include <limits.h>
5
6 #define BITS_PER_WORD (CHAR_BIT * sizeof(int))
7 #define I_WORD(i) ((unsigned int)(i))/BITS_PER_WORD
8 #define I_BIT(i) (1 << ((unsigned int)(i)%BITS_PER_WORD))
9
10 typedef struct NumArray {
11 int size; 12 unsigned int values[1];
13 } NumArray;
14
15 extern "C" int newArray(lua_State* L)
16 {
17 //1. 檢查第一個參數是否為整型。以及該參數的值是否大于等于1.
18 int n = luaL_checkint(L,1);
19 luaL_argcheck(L, n >= 1, 1, "invalid size.");
20 size_t nbytes = sizeof(NumArray) + I_WORD(n - 1) * sizeof(int);
21 //2. 參數表示Lua為userdata分配的字節(jié)數。同時將分配后的userdata對象壓入棧中。
22 NumArray* a = (NumArray*)lua_newuserdata(L,nbytes);
23 a->size = n;
24 for (int i = 0; i < I_WORD(n - 1); ++i)
25 a->values[i] = 0;
26 //獲取注冊表變量myarray,該key的值為metatable。
27 luaL_getmetatable(L,"myarray");
28 //將userdata的元表設置為和myarray關聯的table。同時將棧頂元素彈出。
29 lua_setmetatable(L,-2);
30 return 1;
31 }
32
33 extern "C" int setArray(lua_State* L)
34 {
35 //1. Lua傳給該函數的第一個參數必須是userdata,該對象的元表也必須是注冊表中和myarray關聯的table。
36 //否則該函數報錯并終止程序。
37 NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
38 int index = luaL_checkint(L,2) - 1;
39 //2. 由于任何類型的數據都可以成為布爾值,因此這里使用any只是為了確保有3個參數。
40 luaL_checkany(L,3);
41 luaL_argcheck(L,a != NULL,1,"'array' expected.");
42 luaL_argcheck(L,0 <= index && index < a->size,2,"index out of range.");
43 if (lua_toboolean(L,3))
44 a->values[I_WORD(index)] |= I_BIT(index);
45 else
46 a->values[I_WORD(index)] &= ~I_BIT(index);
47 return 0;
48 }
49
50 extern "C" int getArray(lua_State* L)
51 {
52 NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
53 int index = luaL_checkint(L,2) - 1;
54 luaL_argcheck(L, a != NULL, 1, "'array' expected.");
55 luaL_argcheck(L, 0 <= index && index < a->size,2,"index out of range");
56 lua_pushboolean(L,a->values[I_WORD(index)] & I_BIT(index));
57 return 1;
58 }
59
60 extern "C" int getSize(lua_State* L)
61 {
62 NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
63 luaL_argcheck(L,a != NULL,1,"'array' expected.");
64 lua_pushinteger(L,a->size);
65 return 1;
66 }
67
68 extern "C" int array2string(lua_State* L)
69 {
70 NumArray* a = (NumArray*)luaL_checkudata(L,1,"myarray");
71 lua_pushfstring(L,"array(%d)",a->size);
72 return 1;
73 }
74
75 static luaL_Reg arraylib_f [] = {
76 {"new", newArray},
77 {NULL, NULL}
78 };
79
80 static luaL_Reg arraylib_m [] = {
81 {"set", setArray},
82 {"get", getArray},
83 {"size", getSize},
84 {"__tostring", array2string}, //print(a)時Lua會調用該元方法。
85 {NULL, NULL}
86 };
87
88 extern "C" __declspec(dllexport)
89 int luaopen_testuserdata(lua_State* L)
90 {
91 //1. 創(chuàng)建元表,并將該元表指定給newArray函數新創(chuàng)建的userdata。在Lua中userdata也是以table的身份表現的。
92 //這樣在調用對象函數時,可以通過驗證其metatable的名稱來確定參數userdata是否合法。
93 luaL_newmetatable(L,"myarray");
94 lua_pushvalue(L,-1);
95 //2. 為了實現面對對象的調用方式,需要將元表的__index字段指向自身,同時再將arraylib_m數組中的函數注冊到
96 //元表中,之后基于這些注冊函數的調用就可以以面向對象的形式調用了。
97 //lua_setfield在執(zhí)行后會將棧頂的table彈出。
98 lua_setfield(L,-2,"__index");
99 //將這些成員函數注冊給元表,以保證Lua在尋找方法時可以定位。NULL參數表示將用棧頂的table代替第二個參數。
100 luaL_register(L,NULL,arraylib_m);
101 //這里只注冊的工廠方法。
102 luaL_register(L,"testuserdata",arraylib_f);
103 return 1;
104 }

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