Using the # operator on arrays doesn't guarantee to return the size

When trying to get the size of an array using the # operator, it does not return the correct size if the index does not start with 1, this should work on numbers indexes no matter what.

Reproduction Steps & Actual behavior

local a = {[2] = "hi"}
print(#a) --> Prints 0

Expected Behavior

local a = {[2] = "hi"}
print(#a) --> Prints 2 or 1 (Not sure which, but not 0)

Issue Area: Engine
Issue Type: Internal scripts
Impact: Medium
Frequency: Constantly

1 Like

We’ve filed a ticket into our internal database for this issue, and we will update you when we have further information!

Thanks for the report!

Hello.

This is not a bug.
Please refer to Lua 5.1 Reference Manual (Luau is based on Lua 5.1 with changes):

  • 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).

We will look at updating Roblox documentation to mention these rules.

7 Likes

Yeah, thank you for clarifying!

I thought it was a bug since the documentation on table.insert says that it would “Appends the provided value to the end of the array.”, however if the table doesnt start at index 1 the end of the array is position 1. But after your explained it, it all makes sense now!

Thanks for the clarification!

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.