For loops and non positive indexes iterates incorrectly

Reproduction Steps

Reproduction file: Odd Looping.rbxl (37.0 KB)

Example One
local Data = {
	"Hello", 
	"World", 
	"Okay", 
	[0] = "Zero Entry", 
	[-1] = "Negative Entry (1)",
	[-5] = "Negative Entry (5)",
	[-4] = "Negative Entry (4)",
}

for i,v in Data do
	print(i, v)
end
Example Two
local Data = {}
for i = -50, 100, 6 do
	Data[i] = i
end

print(Data)

-- In this example, ipairs does not print the second loop while pairs does.
for _, value in Data do
	print(value)
end

Expected Behavior

Example one: We expect that either we print from negative to positive, or that after going to the end of the positive end it indexes consistently through the negative.

Example two: We expect that the table is printed corrected and the same as example one.

Actual Behavior

Example one: It goes through the positive and doesn’t deal well with the negatives.
ExampleA_Result

Example two: The table is printed correctly but unlike example A, the indexing goes between positive and negative at random.

Example Two Results


Workaround

Outside of the obvious not using negative values and using code like i = 1, #table do print(table[i]) end, there is no formal workaround. Although this is very much unintentional behaviour so shouldn’t be dealt with by the regular programmer.

Issue Area: Engine
Issue Type: Other
Impact: Moderate
Frequency: Rarely

5 Likes

This looks like expected behavior.

It will iterate over the ordered array (1 up to first hole, if any), and then the order is unspecified.

2 Likes

Not a bug.

Negative indices are never considered array indices in Lua, so they’re always stored in the hash part like any other arbitrary key type (so they don’t have any particular order).

6 Likes

This topic was automatically closed after 41 hours. New replies are no longer allowed.