Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
✓ ANSWER ACCEPTED

Indexing a table of functions?

So with a normal table

normaltable = {"hello", 4, 100}

I can do

normaltable[math.random(1, #normaltable)]

and I will get a random value inside the table. However if I have functions like:

functiontable = {}
functiontable.Print = function()
	print("hi")
end)

functiontable.Print2 = function()
	print("hello")
end)

I cant use the random pick as I was for the first one as it can't get the length of the table. What would be an alternative to get a random function from a table of functions?

1 answer

✓ Accepted answer

###The reason for this is because you created a dictionary.

###When a dictionary is created, the keys inside of it do not have an order. Because of that, iterating through a dictionary may not give the values in the order you wrote. And a dictionary's values are stored in keys, unlike tables that are stored in indexes. In order to fix this, you should preset the functions and make it a normal table.

local function Print() 
    print("hi")
end

local function Print2()
    print("hello")
end

local functiontable = {Print, Print2} -- Remember to use local variables. 
functiontable[math.random(1, #functiontable)]()
-- Calls a random function

----OR----
local functiontable = {}-- Remember to use local variables. 

local function Print() 
    print("hi")
end

local function Print2()
    print("hello")
end

table.insert(functiontable, Print)
table.insert(functiontable, Print2)
tablefunction[math.random(1, #functiontable)]()
-- Calls a random function 

1 comment

0

Thank you!

This discussion is preserved as it was. New answers, comments, and votes are closed.