Lua:了解表数组部分和哈希部分 [英] Lua: understanding table array part and hash part
问题描述
在表的第4部分中, Lua 5.0的实现中有一个示例:
local t = {100, 200, 300, x = 9.3}
In section 4, Tables, in The Implementation of Lua 5.0 there is and example:
local t = {100, 200, 300, x = 9.3}
所以我们有t[4] == nil
.如果我写t[0] = 0
,它将转到哈希部分.
如果我写t[5] = 500
它会去哪里? 数组部分还是哈希部分?
如果有区别,我很想听听Lua 5.1,Lua 5.2和LuaJIT 2实施的答案.
So we have t[4] == nil
. If I write t[0] = 0
, this will go to hash part.
If I write t[5] = 500
where it will go? Array part or hash part?
I would eager to hear answer for Lua 5.1, Lua 5.2 and LuaJIT 2 implementation if there is difference.
推荐答案
从1开始的连续整数键始终位于数组部分.
Contiguous integer keys starting from 1 always go in the array part.
不是正整数的键总是放在哈希部分.
Keys that are not positive integers always go in the hash part.
除此之外,它是未指定的,因此您无法根据规范预测t[5]
的存储位置(并且它可能会或可能不会在这两者之间移动,例如,如果创建然后删除t[4]
.)
Other than that, it is unspecified, so you cannot predict where t[5]
will be stored according to the spec (and it may or may not move between the two, for example if you create then delete t[4]
.)
LuaJIT 2稍有不同-它还将在阵列部分中存储t[0]
.
LuaJIT 2 is slightly different - it will also store t[0]
in the array part.
如果您需要它可预测(可能是设计异味),请坚持使用纯数组表(从1开始的连续整数键-如果要留空,请使用值false
而不是
If you need it to be predictable (which is probably a design smell), stick to pure-array tables (contiguous integer keys starting from 1 - if you want to leave gap use a value of false
instead of nil
) or pure hash tables (avoid non-negative integer keys.)
这篇关于Lua:了解表数组部分和哈希部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!