I'm not sure if there's a specific term for this, but I'll describe it the best I can:
I have a function that uses math.random to pick 1 or 2. If it picks either, I'd want the function to repeat and pick 1 or 2 again. Then, after it picks that second time, I'd want a different function to execute.
Any simple ways to put this into a script?
EDIT: Basically shortening this:
local num = math.random(1,2) if num == 1 then local num2 = math.random(1,2) if num2 == 1 then --code elseif num2 == 2 then --code end elseif num == 2 then local num2 = math.random(1,2) if num2 == 1 then --code elseif num2 == 2 then --code end end
Are the values of num
and num2
important (ie are they used in the --code
sections?) If so, what you've got is probably as short as you're going to get, unless each --code
section is identical - if that's the case, do this:
local num = math.random(1, 2) local num2 = math.random(1, 2) --code
Since num will always be 1 or 2 and you want to do the same thing in either case, there's no point in using an 'if' statement in that case.
Do you only have two different functions (that use the value of num, but not num2)? If so, you could do this:
local num = math.random(1, 2) if math.random(1, 2) == 1 then --run function 1 here referencing 'num' as needed else --run function 2 here referencing 'num' as needed end
Do you have 4 different functions? You could simplify the logic - just select your function based on a random number from 1 to 4:
local num = math.random(1, 4) if num == 1 then --function1 here elseif num == 2 then --function2 here elseif num == 3 then --function3 here else --function4 here end
Or you could even get fancy and put your functions in a list:
--Define the list: functions = {function1, function2, function3, function4} --Elsewhere: functions[math.random(1, #functions)]()
That last line selects a random number between 1 and 4 (because #functions is 4), accesses the function from the list, then runs it (that's what the ending ()
are for).
You could also use recursion (you did say "I'd want the function to repeat"), but you have to have an end condition to prevent an infinite loop. I wouldn't use recursion in the example you provided, but if you have a more complex scenario it might become useful. ex:
function DoSomething(attemptsLeft) --attempt to DoSomething if attemptsLeft < 0 then return end --prevent infinite recursion attemptsLeft = attemptsLeft or 5 --if attemptsLeft is not provided, it will default to 5 --do processing here if somethingWentWrong then DoSomething(attemptsLeft - 1) end --can do more processing here if required end