|
三、Lua 通用数据结构的实现 Lua 内部用一个宏表示哪些数据类型需要进行GC ( Garbage Collection ,垃圾回收)操作: (lobject.h) 展开代码语言:C
自动换行
AI代码解释
/* Bit mark for collectable types */#define BIT_ISCOLLECTABLE (1 << 6)/* raw type tag of a TValue */#define rttype(o) ((o)->tt_)#define iscollectable(o) (rttype(o) & BIT_ISCOLLECTABLE)
LUA_TSTRING (包括LUA_TSTRING )之后的数据类型都需要进行GC操作。这些需要进行GC操作的数据类型都会有一个Common Header宏定义的成员,并且这个成员在结构体定义的最开始部分。 (lobject.h) 展开代码语言:C
自动换行
AI代码解释
/*** Header for string value; string bytes follow the end of this structure** (aligned according to 'UTString'; see next).*/typedef struct TString { CommonHeader; lu_byte extra; /* reserved words for short strings; "has hash" for longs */ lu_byte shrlen; /* length for short strings */ unsigned int hash; union { size_t lnglen; /* length for long strings */ struct TString *hnext; /* linked list for hash table */ } u;} TString;
(lobject.h) 代码语言:C
自动换行
AI代码解释
/*** 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
CommonHeader里面的几个成员定义如下: 同时,还有 个名为GCheader 的结构体,其中的成员只有Common eader: (lobject.h) 代码语言:C
自动换行
AI代码解释
/*** Common type has only the common header*/struct GCObject { CommonHeader;};
在Lua 中就使用了GCUnion 联合体将所有需要进行垃圾回收的数据类型囊括了进来: (lstate.h) 展开代码语言:C
自动换行
AI代码解释
/*** 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 */};
仅表示需要进行垃圾回收的数据类型还不够,还有几种数据类型是不需要进行垃圾回收的,中将GCObject 和它们 起放在了联合体Value 中: (lobject.h) 展开代码语言:C
自动换行
AI代码解释
/*** 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;
为了清楚数据到底是什么类型的,lua代码中又有了TValuefields ,它用于将Value 类型结合在一起:
(lobject.h) 代码语言:C
自动换行
AI代码解释
#define TValuefields Value value_; int tt_
最后形成了Lua中的TValue结构体, Lua 中的任何数据都可以通过该结构体表示:
(lobject.h) 代码语言:C
自动换行
AI代码解释
typedef struct lua_TValue { TValuefields;} TValue;
Lua通用数据结构的组织:
在具体的代码中, TValue用于统一地表示数据,而一旦知道了具体的类型,就需要使用具体的类型了 因此,代码中有不少涉及TValue与具体类型之间转换的代码,其主要逻辑都是将TValue中的tt value 具体类型的数据进行转换。
(lobject.h) 展开代码语言:C
自动换行
AI代码解释
/* Macros to set values */#define settt_(o,t) ((o)->tt_=(t))#define setfltvalue(obj,x) \ { TValue *io=(obj); val_(io).n=(x); settt_(io, LUA_TNUMFLT); }#define chgfltvalue(obj,x) \ { TValue *io=(obj); lua_assert(ttisfloat(io)); val_(io).n=(x); }
|