How would I get random data from a table?

How would I be able to get a random table from a table?

whenever I try to get a random table, it seems to return an error.
(invalid argument #2 to ‘random’ (interval is empty))

I’ve looked everywhere on the Developer Hub, and I have seen no result.

I’ll try and find other solutions that may help.

This is what I’ve done:

local EventStuff = {
	Speed = {
		["Name"] = "2x Speed",
	},
	test = {
		["Name"] = "thing",
	},
}

local Data = EventStuff[math.random(1, #EventStuff)]
print(Data)

I think you can try this

local tabl = {1,2,3,4,5}
local RandomTable = tabl[Random.new():NextInterger(1, #tabl)]

I didn’t write this on studio so the gammar might wrong

Thank you for replying! I’ll try this out!

From what i know “#table” only return index not dictionary
u can try loop table like this

local EventStuff = {
	Speed = {
		["Name"] = "2x Speed",
	},
	test = {
		["Name"] = "thing",
	},
}

local i = 0
for _, v in EventStuff do
	i += 1
end

local Data = table.find(EventStuff, math.random(1, i))
print(Data)

i accident delete old reply…

I’m sorry if I did anything wrong but I believe that it returns a nil value?

ahh sorry my mistake, table.find dont work with dictionary

local EventStuff = {
	Speed = {
		["Name"] = "2x Speed",
	},
	test = {
		["Name"] = "thing",
	},
}

local i = 0
for _, v in EventStuff do
	i += 1
end

local rng = math.random(1, i)
local Data
for ii, v in EventStuff do
	if ii == rng then
		Data = v
		break
	end
end
print(Data)

this should work

1 Like

It returned nil again. However, for some reason it thinks ii is the data(v).

If unable to find a more suitable solution, you could try rewriting your dictionary like this.

local EventStuff = {
	{EventName = "Speed", Description = "2x speed"},
	{EventName = "Test", Description = "Test"}
}

This way, it still counts as a table and you’re able to index a random table of info.

I edited the script a bit and decided to give the tables a RNG value which helped detect if the value == rng. I was able to get a random value every time! Thank you so much for helping with my problem!

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