You can make this automatic using loadstring!
You just write some code, that generates your if-statements!
function writeCodeForMe(n)
local code = ""
for i = 0, n do
for j = 0, n do
code ..= `if num1 == {i} and num2 == {j} then return {i + j} `
if not (i == n and j == n) then
code ..= "else"
end
end
end
code ..= " end"
return code
end
This will return our code as a string, ready for us to use. We then just need to use loadstring!
Although we also need to make sure that num1
and num2
are part of the function environment, so we do a bit of trickery with the function parameters.
The final script looks like this:
local maxNumber = 5
function writeCodeForMe(n)
local code = ""
for i = 0, n do
for j = 0, n do
code ..= `if num1 == {i} and num2 == {j} then return {i + j} `
if not (i == n and j == n) then
code ..= "else"
end
end
end
code ..= " end"
return code
end
function addition(a, b)
num1 = a
num2 = b
return loadstring(writeCodeForMe(maxNumber))()
end
And this works! Now we can just change the maxNumber
variable, and it will automatically make new if-.statements for us!