gopher-lua icon indicating copy to clipboard operation
gopher-lua copied to clipboard

LTable length function doesn't work correctly in some edge cases.

Open mttsner opened this issue 5 years ago • 2 comments

Issue

When using the # unary operator on a lua array that has index = value, the returned length is the highest index.

Example

print(#{
	[20] = 0;
	[600] = 0;
}) --Output: 600

Expected behaviour

print(#{
	[20] = 0;
	[600] = 0;
}) --Output: 0

How the length operator should work

The length operator returns the last numeric key whose value is not nil for tables starting from 1. The length operator returns zero for tables when the first numeric key is nil or there are no numeric keys.

mttsner avatar Nov 10 '20 01:11 mttsner

I think this is because OP_LEN iterates from the end like MaxN.

tongson avatar Jun 06 '21 10:06 tongson

How the length operator should work

The length operator returns the last numeric key whose value is not nil for tables starting from 1. The length operator returns zero for tables when the first numeric key is nil or there are no numeric keys.

No.
According to Lua manual, the length operator applied on a table returns a border in that table. A border in a table is any positive integer index present in the table that is followed by an absent index.

The table {[20]=0, [600]=0} has 3 borders: 0, 20 and 600.
So, #{[20]=0, [600]=0} may return any of these 3 numbers, all of them are correct.

See table length definition

Egor-Skriptunoff avatar Jun 24 '22 15:06 Egor-Skriptunoff