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

How to randomize the order in which functions fire?

Asked by
Shawnyg 4330 Trusted Badge of Merit Snack Break Moderation Voter Community Moderator
10 years ago

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?

2 answers

Log in to vote
3
Answered by
BlueTaslem 18071 Moderation Voter Administrator Community Moderator Super Administrator
10 years ago

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
0
Thanks Shawnyg 4330 — 10y
Ad
Log in to vote
2
Answered by
Perci1 4988 Trusted Moderation Voter Community Moderator
10 years ago

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.

0
I can't believe I forgot about that. I guess I was thinking of a straight forward method. Like "math.random(func1)". Thanks, though. Shawnyg 4330 — 10y
0
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) BlueTaslem 18071 — 10y

Answer this question