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

Why am I getting the wrong order on this team color table?

Asked by
MrHerkes 166
6 years ago
Edited 6 years ago
01TeamColors = {
02    Red = BrickColor.new("Bright red"),
03    Blue = BrickColor.new("Bright blue"),
04    Yellow = BrickColor.new("Bright yellow"),
05    Green = BrickColor.new("Bright green"),
06    Orange = BrickColor.new("Bright orange"),
07    Teal = BrickColor.new("Teal"),
08    Purple = BrickColor.new("Royal purple"),
09    Pink = BrickColor.new("Pink")
10} --Max teams: 8
11 
12function AddTeams(numberOfTeams)
13    if type(numberOfTeams) == "number" then
14        local number = 1
15 
View all 37 lines...

The above script add teams to the game. However, when I test out the script, the order is wrong. I wanted the table to be like it is (Red, Blue, Yellow, Green, etc.). Why is it in the wrong order?

0
do you get different results if you change pairs to ipairs? vanilla_wizard 336 — 6y
0
Nothing really appeared in the output when I changed "pairs" to "ipairs". MrHerkes 166 — 6y
0
Oh now I feel stupid for asking that, it's a dictionary. You can't exactly sort a dictionary into a desired order. There's the problem. vanilla_wizard 336 — 6y

1 answer

Log in to vote
1
Answered by 6 years ago

When you're using a dictionary, the index is no longer "1", "2", "3", "4", etc. As your output shows, it's now "Pink", "Purple", "Blue", etc. Unfortunately, you can't sort that in order.

"in pairs" doesn't care about the order of the indices, whereas "ipairs" does. You can't use "ipairs" on a dictionary.

One approach if you absolutely must have red come before blue is to simply have two tables and have their values match their indices so index 1 of one table corresponds to index 1 of another table.

01local teamColors = {
02    BrickColor.new("Bright red"), -- index 1
03    BrickColor.new("Bright blue") -- index 2
04}
05local teamNames = {
06    "Red", -- index 1
07    "Blue" -- index 2
08}
09 
10function AddTeams(numberOfTeams)
11        if type(numberOfTeams) == "number" then
12            local number = 1
13 
14            for i,v in pairs(TeamColors) do
15                if (number > numberOfTeams) then return end
View all 27 lines...

I edited that quickly so it might have some problems, but if it was helpful please upvote/mark correct, and if you have any questions or if I messed up please comment below.

2
I'd suggest using a nested table instead. RubenKan 3615 — 6y
Ad

Answer this question