Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

For loop not looping in right order as it should for some reason?

local myTable = {
	
	["First"] = 1;
	["Second"] = 2;
	["Third"] = 3;
	["Fourth"] = 4;
	
}


for myString, myWeight in pairs(myTable) do
	
	print(myString)
	
end

What it returns in the output :

15:48:24.086 Fourth - Client 15:48:24.086 First - Client 15:48:24.086 Third - Client 15:48:24.086 Second - Client

Clearly it's not printing it in order, and this applies to all the scripts i've tried it on.

1 answer

✓ Accepted answer

In Lua, there are tables and arrays. All arrays are tables, but not all tables are arrays. Only arrays can be indexed in order.

If you need to index your table in a particular order, you should to initialize it as an array.

local myTable = {
    "First",
    "Second",
    "Third",
    "Fourth"
}

Arrays should also be iterated over using ipairs (instead of pairs).

for index, myString in ipairs(myTable) do
    print(myString)
end

This discussion is preserved as it was. New answers, comments, and votes are closed.