Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

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

Asked by 3 years ago
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

Log in to vote
1
Answered by 3 years ago
Edited 3 years ago

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
Ad

Answer this question