How would I randomize functions?
function a()
end
function b()
end
function c()
end
How to randomize order in which they fire? Could I use math.random() for it?
How would I randomize functions?
function a()
end
function b()
end
function c()
end
How to randomize order in which they fire? Could I use math.random() for it?
There's a nice short, general solution that takes advantage of a simpler idea: selecting things from a list.
Functions are values, so we can make a list of functions and then select a random thing from that list:
local myFuns = {a, b, c}
local myFun = myFuns[ math.random(1, #myFuns) ]
myFun() -- Call the one we picked
You could check what math.random() equals and call the function based on that;
function a()
print("a")
end
function b()
print("b")
end
function c()
print("c")
end
while true do
wait(2)
local random = math.random(1,3)
if random == 1 then
a()
elseif random == 2 then
b()
else
c()
end
end
Although functional, this gets messy very very quickly if you have lots of functions.
I'm interested to see if anyone else has a better method.
I can't believe I forgot about that. I guess I was thinking of a straight forward method. Like "math.random(func1)". Thanks, though.
There's a better method -- using the fact that functions are values! (Posted as a separate answer -- this is still a good answer and for only a few fun's is probably preferable)
This discussion is preserved as it was. New answers, comments, and votes are closed.
1 comment
Thanks