How can I run a function from a table?

How would I fix this and do what the title says?

local function yay()
 print("yay")
end

local function grr()
 print("grr")
end

local functions = {yay(), grr()}

functions[math.random(1,#functions)]() -- this doesn't work

Please help.

2 Likes

Your code is mostly correct, just change the table to this:

local functions = {yay, grr}

The reason why you should remove the parenthesis is because you just want to write the reference to the function, the parenthesis call the function

5 Likes

In addition to what @HugeCoolboy2007 mentioned,

If you want to store some functions in this way , you could

local functions = {
	["Yay"] = function()
		print("Yay2")
	end,
	["Grr"] = function()
		print("Grr2")
	end,
}


for Name,Value in pairs(functions) do
	print(Name) -- "Yay", "Grr"
	Value() --> "Yay2","Grr2"
end
1 Like
local functions = {}

function functions.Yay()
	print("Yay2")
end

function functions.Grr()
	print("Grr2")
end

and the modularized way.

1 Like

You’re right man, love your notes, always infortmative.