【问题标题】:How does Lua's table length operator work? [duplicate]Lua 的表长度操作符是如何工作的? [复制]
【发布时间】:2016-08-19 06:29:33
【问题描述】:

谁能解释这种明显的精神错乱?

> t = {1, 2, 3} -- Table length 3. Simple
> = #t
3  -- Yep

> t[3] = nil -- Remove the last element?
> = #t
2 -- Ok it realises it is the last one (since #t = 3) and decrements the length

> t[6] = 6 -- Add a separate element?
> = #t
2 -- Ok... I guess? Although surely it knew #t = 2, and so now #t should be 6?

> t[4] = 4 -- Add another separate element
> = #t
4 -- Errr... what.

> t[5] = 5 -- Append another element
> = #t
6 -- Ok now it remembers element 6? Wtf?

好的,让我再试一次...

> t = {1, 2, 3}
> = #t
3
> t[10] = 10
> = #t
3
> t[4] = 4
> = #t
4
> t[9] = 9
> = #t
4
> t[8] = 8
> = #t
10

什么。

【问题讨论】:

  • 啊,是的,这就解释了。我不知道为什么对于未定义的情况,他们不能让#t 返回 nil 或 -1。
  • 您可以实现自己的__len 元方法来为非序列表返回不同的结果,但您仍然需要确定表是否是正确的序列。

标签: lua lua-table luajit


【解决方案1】:

只有当表是正确的序列(连续的整数键)时才定义表的长度。

Lua manual 解释长度操作符:

除非给出 __len 元方法,否则表 t 的长度仅在表是序列时才定义,即其正数字键的集合等于 {1..n} 对于一些非负整数 n。在这种情况下,n 是它的长度。请注意,像

这样的表
{10, 20, nil, 40}

不是序列,因为它有键 4 但没有键 3。 (因此,没有 n 使得集合 {1..n} 等于该表的正数字键集合。) 但是请注意,非数字键不会影响表是否为序列。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-04-07
    • 1970-01-01
    • 2016-12-04
    • 2014-10-07
    • 1970-01-01
    • 1970-01-01
    • 2015-05-28
    • 2022-12-20
    相关资源
    最近更新 更多