Lua是一门动态类型语言,因此我们需要一个专门的数据结构来存放Lua的变量。在Lua源码中,使用结构体lua_TValue来存放变量的类型和值。代码如下:
/*
** Union of all Lua values
*/
typedef union Value {
GCObject *gc; /* collectable objects */
void *p; /* light userdata */
int b; /* booleans */
lua_CFunction f; /* light C functions */
lua_Integer i; /* integer numbers */
lua_Number n; /* float numbers */
} Value;
#define TValuefields Value value_; int tt_
typedef struct lua_TValue {
TValuefields;
} TValue;
lua_TValue结构体中只包含两个成员value_和tt_,value_代表变量的值,tt_代表数据类型。先解释数据类型,在Lua源码中声明了一些宏来表示不同的数据类型。
/*
** basic types
*/
#define LUA_TNONE (-1) //无类型
#define LUA_TNIL 0 //nil
#define LUA_TBOOLEAN 1 //布尔
#define LUA_TLIGHTUSERDATA 2 //指针(需要自己管理)
#define LUA_TNUMBER 3 //整数
#define LUA_TSTRING 4 //字符串
#define LUA_TTABLE 5 //表
#define LUA_TFUNCTION 6 //函数
#define LUA_TUSERDATA 7 //指针(GC管理)
#define LUA_TTHREAD 8 //协程
#define LUA_NUMTAGS 9 //共9种类型(不包含LUA_TNONE)
观察Value联合中的成员变量。根据源码中的宏定义我们可以知道Lua变量类型底层的表示。例如Lua中的整型采用的long long,浮点类型采用的double。
#define LUA_INTEGER long long
#define LUA_NUMBER double
typedef int (*lua_CFunction) (lua_State *L)
有人问,Lua中有Table,String等数据类型,但是Value联合中没有,会不会有什么问题。因为Table,String等数据类型属于GC数据类型,它们都属于Value联合中的GCObject。
/*
** Common Header for all collectable objects (in macro form, to be
** included in other objects)
*/
#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked
/*
** Common type has only the common header
*/
struct GCObject {
CommonHeader;
};
阅读GCObject源代码发现只有三个成员变量。
- next表示GCObject链表的next指针
- tt表示数据类型
- marked表示是否被GC
源码中存在包含所有需要GC类型的一个联合GCUnion。
/*
** Union of all collectable objects (only for conversions)
*/
union GCUnion {
GCObject gc; /* common header */
struct TString ts;
struct Udata u;
union Closure cl;
struct Table h;
struct Proto p;
struct lua_State th; /* thread */
};
每个GC结构(TString,Table 等)的第一个成员都是GCObject,否则GCObject->GCUnion 强制类型转换是错误的,源码中相应的宏如下:
#define cast(t, exp) ((t)(exp))
#define cast_u(o) cast(union GCUnion *, (o)) //o是GCObject*
因此GC数据结构的整个流程是 TValue->TValuefields->GCObject->GCUnion->具体数据类型。