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

How would I create a table of maps in an efficient way?

Asked by
SuperFryX 130
8 years ago

I'm currently in the process of rewriting an old stage selection script I made. The code is extremely messy, making it hard to implement new stages and features, so I would like to use this opportunity to increase my limited knowledge of tables.

So say that the stages are located in game.ServerStorage.Maps and its children are called Map1, Map 2 and so on. How would I create a table that I could easily identify these stages in an efficient way?

3 answers

Log in to vote
5
Answered by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
8 years ago

Great question. What you need to identify all children, is the generic for loop. It goes through the target's children, and in this case, we'll add its name to a table!

local MapTable = {}
local Maps = game.ServerStorage.Maps

for i,v in pairs(Maps:GetChildren()) do
    table.insert(Maps, v.Name) -- you may want to double check this. I'm not at home, so no studio for me.
end
Ad
Log in to vote
2
Answered by
Necrorave 560 Moderation Voter
8 years ago

The best way I can think of is creating the table by using :GetChildren()

Using your info:

local maps = game.ServerStorage.Maps:GetChildren() --Creating the table of maps

--Maps are usually chosen at random, so I will provide a simple method of how to do so.

local rand = math.random(#maps) --Creates a random number with the number of maps as the range

print (maps[rand].Name) --Should print the name of the map its chosen

Let me know if you have any questions!

Log in to vote
0
Answered by 8 years ago

If you don't know, you can put objects, parts and even functions in tables. Use:GetChildren() to get all the maps and put all your maps in a folder or model, :GetChildren() is a better way than making a custom table because you can put alot of maps without having to keep on adding to the table.

You can make a script like this :

local mapHolder = serverStorage:WaitForChild('Maps')
local maps = mapHolder:GetChildren()

local randomMap = math.Random(1, #maps) -- This is a better way than making a custom table because you can have an infinite amount of maps without having to change a table.

print(maps[randomMap].name) -- You can do whatever you wan't here, this just prints the chosen map name.

Answer this question