löve2d #array 不返回数组的最后一个整数索引

löve2d #array not returning last integer index of an array

Vanilla Lua 代码(新的空项目):

local array = {1,2,3,4,5}
array[3] = nil
array[4] = nil
print(#array) -- returns 5

Löve2d 代码(新建空项目):

function love.load()
    local array = {1,2,3,4,5}
    array[3] = nil
    array[4] = nil
    print(#array) -- returns 2 (bug?)
end

这是它应该如何工作还是一个错误?

Lua wiki 说:# 运算符不计算 table 中的所有项目(!)。相反,它会找到最后一个整数(非小数)键。

所以我认为这是一个错误,但我不确定,因为我对 Lua 和 Löve2d 还很陌生。

我正要在项目网站上报告这个可能的错误,但我想先确定它是一个错误。

根据 documentation on The Length Operator #:

The length operator is denoted by the unary operator #. The length of a string is its number of bytes (that is, the usual meaning of string length when each character is one byte).

The length of a table t is defined to be any integer index n such that t[n] is not nil and t[n+1] is nil; moreover, if t[1] is nil, n can be zero. For a regular array, with non-nil values from 1 to a given n, its length is exactly that n, the index of its last value. If the array has "holes" (that is, nil values between other non-nil values), then #t can be any of the indices that directly precedes a nil value (that is, it may consider any such nil value as the end of the array).

强调我的。好像就是这么设计的。 Any nil可以认为是数组的结尾。尽管看起来很草率,但它似乎是 故意的

至于看到测试结果的差异,可能与运行不同的版本有关。检查以确保您对每个测试使用相同的版本进行测试。