TeamColors = { Red = BrickColor.new("Bright red"), Blue = BrickColor.new("Bright blue"), Yellow = BrickColor.new("Bright yellow"), Green = BrickColor.new("Bright green"), Orange = BrickColor.new("Bright orange"), Teal = BrickColor.new("Teal"), Purple = BrickColor.new("Royal purple"), Pink = BrickColor.new("Pink") } --Max teams: 8 function AddTeams(numberOfTeams) if type(numberOfTeams) == "number" then local number = 1 for i,v in pairs(TeamColors) do if (number > numberOfTeams) then return end print("Index:" .. i, "Value:" .. tostring(v)) local team = Instance.new("Team", game:WaitForChild("Teams")) team.Name = tostring(i) team.TeamColor = v number = number + 1 end end end AddTeams(3) --Output: Index:Pink Value:Pink Index:Purple Value:Royal purple Index:Blue Value:Bright blue
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?
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.
local teamColors = { BrickColor.new("Bright red"), -- index 1 BrickColor.new("Bright blue") -- index 2 } local teamNames = { "Red", -- index 1 "Blue" -- index 2 } function AddTeams(numberOfTeams) if type(numberOfTeams) == "number" then local number = 1 for i,v in pairs(TeamColors) do if (number > numberOfTeams) then return end print("Index:" .. i, "Value:" .. tostring(v)) -- output now 1, Bright red local team = Instance.new("Team", game:WaitForChild("Teams")) team.Name = teamNames[i] -- changed team.TeamColor = v number = number + 1 end end end AddTeams(3)
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.