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)
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
else
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
elseif num == 2 then
elseif num == 3 then
else
end
Or you could even get fancy and put your functions in a list:
functions = {function1, function2, function3, function4}
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)
if attemptsLeft < 0 then return end
attemptsLeft = attemptsLeft or 5
if somethingWentWrong then
DoSomething(attemptsLeft - 1)
end
end
2 comments
Does it do a different function depending on the numbers or is it the same function? Or are those numbers supposed to be parameters or something
It does the same function no matter the number, just with slightly different parameters depending on whether what's picked is one or two. Those aren't parameters though, just the fastest way I could think of picking a random yes/no type of thing.