在lua5.3版本中,当key作为table的key值时,会根据string的hash值去映射到数组上面。
string的hash值在创建的时候会对hash复制
//lua5.3 lstring.c:167
static TString *internshrstr (lua_State *L, const char *str, size_t l) {
TString *ts;
global_State *g = G(L);
unsigned int h = luaS_hash(str, l, g->seed);
...
ts = createstrobj(L, l, LUA_TSHRSTR, h);
...
return ts;
}
//lstring.c:133
static TString *createstrobj (lua_State *L, size_t l, int tag, unsigned int h) {
TString *ts;
GCObject *o;
size_t totalsize; /* total size of TString object */
totalsize = sizelstring(l);
o = luaC_newobj(L, tag, totalsize);
ts = gco2ts(o);
ts->hash = h;
ts->extra = 0;
getstr(ts)[l] = '\0'; /* ending 0 */
return ts;
}
每次计算hash时都会用到hash种子也就是g->seed, hash种子在每次启动时都设置为当前时间
//lstate.c:295
LUA_API lua_State *lua_newstate (lua_Alloc f, void *ud) {
...
g->seed = mak