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

How to randomize the order in which functions fire?

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

✓ Accepted answer

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

1 comment

0

Thanks

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.

2 comments

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.

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)

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