local a = {}
a[nil] = 0 – 会报错“table index is nil”
// ltable.c
TValue *luaH_newkey (lua_State *L, Table *t, const TValue *key) {
Node *mp;
TValue aux;
// error when key is nil
if (ttisnil(key)) luaG_runerror(L, "table index is nil");
// ...
}
而print(a[nil])不会报错,打印结果是nil
// ltable.c
const TValue *luaH_get (Table *t, const TValue *key) {
switch (ttype(key)) {
case LUA_TSHRSTR: return luaH_getshortstr(t, tsvalue(key));
case LUA_TNUMINT: return luaH_getint(t, ivalue(key));
// return nil when key is nil
case LUA_TNIL: return luaO_nilobject;
case LUA_TNUMFLT: {
lua_Integer k;
if (luaV_tointeger(key, &k, 0)) /* index is int? */
return luaH_getint(t, k); /* use specialized version */
/* else... */
} /* FALLTHROUGH */
default:
return getgeneric(t, key);
}
}
实际开发中还要是避免出现 a[nil]这种情况出现。