Intentional sorting or not?

For some this loop does not order by number (1>2) but is completely random, why?
It’s suppose to be like "1<letter>" > "2<letter>"

local t = {}
for i = 1, 100 do
	t[i..string.char(math.random(65, 90))] = i
end
for v,i in t do
	print(v,v:sub(1,-2),v..string.char(math.random(65, 90)):sub(1,-2))
end

image

It’s because you’re iterating over a dictionary, and the order of that is undefined. If you’re actually expecting a proper order, use an array; you could also do something like use a separate array to track the order of keys in the dictionary…

How do I exactly define the order? And why is it random on dictionaries but not arrays?

local t = {}
for i = 1, 100 do
	table.insert(t, i..string.char(math.random(65, 90)))
end
for _,v in t do
    print(v,v:sub(1,-2),v:rep(2):sub(1, -math.random(1,4)))
end

Order for arrays is defined by their indices. When you use table.insert, it inserts the value you provide at the index that’s the length of the array + 1, creating a new index on the end. If you want to reorder your array elements, take a look at table.sort

Dictionaries have no guaranteed order because you can put anything in the keys of a dictionary (like booleans, roblox datatypes, and even other tables!), not just sortable values like numbers and strings.

1 Like

An array is a well-known data structure that quite literally goes in order as it does in memory, a dictionary/hash-map is all over the place; and while parts of it may technically sit as contiguous memory, there are sections that do not. There are implementations that exists for hash maps that do keep order when iterating, the lua/luau implementation does not track order.

To keep order, you’d might keep a mirror of insertions, a rough example.

local t = {}
local keyOrder = {}

for i = 1, 100 do
	local str = i..string.char(math.random(65, 90))
	t[str] = i
	keyOrder[i] = str
end
for i, v in pairs(keyOrder) do
	--local i = t[v]
	print(v,v:sub(1,-2),v..string.char(math.random(65, 90)):sub(1,-2))
end
1 Like

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