分析一下 lua 中常用的几个数据结构:
先看一下 opcode.h 中的:
typedef unsigned char Byte;
typedef unsigned short Word;
typedef union
{
struct {char c1; char c2;} m;
Word w;
} CodeWord;
typedef union
{
struct {char c1; char c2; char c3; char c4;} m;
float f;
} CodeFloat;
这两个 union 类型主要是用来做虚拟机指令用的。
lua1.1 中虚拟机的指令是一个字节,当要保存的数是一个 Word 或者 float 时,以 Word 为例,可以直接给 CodeWord 类型的 w 赋值,之后,用 CodeWord 的结构体 m 的两个字段来生成指令并存入指令数组中。
如下的 code_word 方法的实现可以看出这个结构是如何使用的
static void code_word (Word n)
{
CodeWord code;
code.w = n;
code_byte(code.m.c1);
code_byte(code.m.c2);
}
OpCode 枚举是 lua1.1 虚拟机所支持的所有指令。
Type 枚举是 lua 中的几种数据类型。
typedef enum
{
T_MARK,
T_NIL,
T_NUMBER,
T_STRING,
T_ARRAY,
T_FUNCTION,
T_CFUNCTION,
T_USERDATA
} Type;
Value 联合体是 lua 的数据定义。
typedef union
{
Cfunction f;
real n;
char *s;
Byte *b;
struct Hash *a;
void *u;
} Value;
Object 带标签的数据类型,其中 tag 字段表示 Object 的类型,Value 是 Object 的值。
typedef struct Object
{
Type tag;
Value value;
} Object;
Symbol 符号,name 符号的名字,object 符号的值,它是一个 Object 类型。
typedef struct
{
char *name;
Object object;
} Symbol;
struct List
{
Symbol *s;
struct List *next;
};
符号表就是一个符号数组,next 主要用于在 searchlist 中用于查找。
hash.h 中定义了关联数组,也就是 lua 里的 table 类型。
// table 中的无素
typedef struct node
{
Object ref; // 元素的 key
Object val; // 元素的 value
struct node *next; // 指向下一个元素的指针。
} Node;
// table 定义
typedef struct Hash
{
char mark;
unsigned int nhash;
Node **list;
} Hash;
其中:
mark 在垃圾回收时的标记
nhash table 中的元素个数
list 元素的列表
原文地址:http://my.oschina.net/xhan/blog/312390