Lua表
表的数据结构:数组+哈希表(链地址法)
typedef struct Table {
CommonHeader;
lu_byte flags; /* 1<<p means tagmethod(p) is not present */
lu_byte lsizenode; /* log2 of size of 'node' array */
unsigned int alimit; /* "limit" of 'array' array */
TValue *array; /* array part */
Node *node;
Node *lastfree; /* any free position is before this position */
struct Table *metatable; /* 原表 */
GCObject *gclist;
} Table;
哈希表节点数据结构:
typedef union Node {
struct NodeKey {
TValuefields; /* fields for value */
lu_byte key_tt; /* key type */
int next; /* for chaining */
Value key_val; /* key value */
} u;
TValue i_val; /* direct access to node's value as a proper 'TValue' */
} Node;
创建新表:
Table *luaH_new (lua_State *L) {
GCObject *o = luaC_newobj(L, LUA_VTABLE, sizeof(Table));
Table *t = gco2t(o);
t->metatable = NULL;
t->flags = cast_byte(maskflags); /* table has no metamethod fields */
t->array = NULL;
t->alimit = 0;
setnodevector(L, t, 0);
return t;
}
存入一个整数键的值:查找表中是否有该值(数组和哈希表两部分), 如果key不大于数组的大小,则直接取对应下标的数组地址。 否则,如果’alimit’不等于数组的实际大小,且key不大于数组实际大小,返回对应下标的数组地址。 在这种情况下,请尝试避免在key仅比限制多一个时调用“ luaH_realasize”(以便可以在不更改数组实际大小的情况下对其进行扩展;如果没有找到,就往哈希表里面查找。
void luaH_setint (lua_State *L, Table