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

How do I make a random function?

Asked by
Loot_O 42
5 years ago

So I want to figure out how to make random functions, this can be useful to make a game like Horrific Housing.

function One()
       print("1")
end

function Two()
       print("2")
end

function Three()
       print("3")
end

local functions = {One(), Two(), Three()}
math.random(1, #functions)

I'm using strings because it shows whats happening. When you run this, it'll print all the numbers that are there, is there a way to fix this?

1 answer

Log in to vote
1
Answered by
royaltoe 5144 Moderation Voter Community Moderator
5 years ago

You can store your functions invariables like so:

one = function()
       print("1")
end

two = function()
       print("2")
end

three = function()
       print("3")
end

then put those variables in a table:

local functions = { one, two, three }

and pick a random function in that table/call that function

randomFunction = functions[math.random(1, #functions)]

randomFunction()

All together, it would look like this:

one = function()
       print("1")
end

two = function()
       print("2")
end

three = function()
       print("3")
end

local functions = { one, two, three }
randomFunction = functions[math.random(1, #functions)]
randomFunction()
0
Can confirm that this does work. hpenney2 53 — 5y
0
he's been online since i posted this so not sure what's up royaltoe 5144 — 5y
0
works... should be marked as answer EmbeddedHorror 299 — 5y
0
Thank you, I really needed something like this! Loot_O 42 — 5y
0
no problem if you need any more help just ask royaltoe 5144 — 5y
Ad

Answer this question