Lua:了解表数组部分和哈希部分 [英] Lua: understanding table array part and hash part

查看:897
本文介绍了Lua:了解表数组部分和哈希部分的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在表的第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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆