How to store multiple instances in table with arrays as ascending numbers?

I’m trying to store a folder’s children into a table and randomize a result so it picks a random child from the folder. (although I think I have the randomizing part done correctly)

My code: (the folder “Items” is made up of 6 folders named a,b,c,d,e,f,g)

for i,v in pairs(game.ServerStorage.Items:GetChildren()) do
	
	local Table = {}
	table.insert(Table,v.Name)
	
	local random = math.random(1,#Table)
	local result = Table[random]
	
	print(result)
end

My issue is I can’t figure out how to store the children’s name in a way the randomized result would print out as.

[4] = d

What I want to achieve:

[1] = a
[2] = b
-- and so on

What I’m getting:

a
b
c
d
e
f

I’m assuming they all get put under [1], and I think I need to change the 4th line to something else but I can’t put my finger on what exactly.

If you want to change the format on how it prints do this:

Print(“[“ … i … “] = “ … result)

Hi there,

If I’m understanding you correctly, your problem here is that you’re declaring the array Table each time inside of your for loop, hence, re-initializing an empty table each iteration of your loop. What this does is it’ll flush out everything you inserted using table.insert each iteration and all you’re left with is a single element which was left on the last iteration of the loop.

To fix this, take the array declaration outside. Give this a shot:

local ServerStorage = game:GetService("ServerStorage")
local Items = ServerStorage:WaitForChild("Items")

local Table = {}

for i,v in pairs(Items:GetChildren()) do
	table.insert(Table,v.Name)
end
print(Table)

local result = Table[math.random(1,#Table)]
print(result)

Thank you very much. I actually did think of taking it out of the for loop but didn’t actually put it in practice, this works exactly as I intended it to !

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.