Lua源码阅读(一):Lua数据类型

Lua源码阅读笔记,主要参考自《Lua设计与实现》。
源码版本为 5.1.4,下载地址:https://github.com/lichuang/Lua-5.1.4-codedump


CommonHeader

任何需要进行GC操作的Lua数据类型,都会有一个 CommonHeader宏定义的成员,且定义在结构体的最开始部分。CommonHeader类似于一个基类,需要GC处理的数据类型均继承自这个基类,所以他们的结构体定义的开头就是CommonHeader。

//lobject.h
#define CommonHeader GCObject *next; lu_byte tt; lu_byte marked

其中,next是指向下一个GC链表的成员,tt表示数据类型、marked为GC相关的标志位。

例如表数据类型 Table的定义:

//lobject.h
typedef struct Table {
  CommonHeader;
  lu_byte flags;  /* 1<<p means tagmethod(p) is not present */ 
  lu_byte lsizenode;  /* log2 of size of `node' array */
  struct Table *metatable;
  TValue *array;  /* array part */
  Node *node;
  Node *lastfree;  /* any free position is before this position */
  GCObject *gclist;
  int sizearray;  /* size of `array' array */
} Table;

GCheader

CommonHeader外面再包了一层GCheader

//lobject.h
typedef struct GCheader {
  CommonHeader;
} GCheader;

GCObject 联合体

GCObject 联合体表示需要GC的数据类型,包含了所有需要进行垃圾回收的数据类型,方便查找不同类型的数据。

//lstate.h
union GCObject {
  GCheader gch;
  union TString ts;
  union Udata u;
  union Closure cl;
  struct Table h;
  struct Proto p;
  struct UpVal uv;
  struct lua_State th;  /* thread */
};

Value联合体

此外,还有不需要GC的类型。
再用Value联合体包含了GCObject和其他不需要GC的数据类型。

//lobject.h
typedef union {
  GCObject *gc;
  void *p;
  lua_Number n;
  int b;
} Value;

TValuefields

TValuefields将Value和数据类型tt结合起来

//lobject.h
#define TValuefields	Value value; int tt

TValue

TValuefields外面再包一层,最终形成TValue结构体,用于表示Lua中的任何数据。

/lobject.h
typedef struct lua_TValue {
  TValuefields;
} TValue;

综上,Lua通用数据结构的组织如图所示


参考资料:《Lua设计与实现》

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章