Hello!
I was working on my game… then I stumbled upon a way to reference items in a function…
local firstValue = 1
local secondValue = 5
local function TestFunction(Value)
print(Value)
end
num = math.random(1,2)
if num == 1 then
TestFunction(firstValue)
else
TestFunction(secondValue)
end
Should i do it the way above? or should I do it like this?
local firstValue = 1
local secondValue = 5
local num
-- being more specific.. --
local function TestFunction()
num = firstValue
end
local function TestFunction2()
num = secondValue
end
TestFunction()
TestFunction2()
There isn’t really a need for the functions in general. Not for this reason at least. You could just set the value of num inside of the math.random value. But I would change that variable name to something like randomNum, define num at the top, then set the value of num in the if statement. The function is completely pointless for the top.
In another case, if you needed to define the num variable in other parts of code, you can return it via the function, like this:
local firstValue = 1
local secondValue = 5
local function setNum()
local random = math.random(1, 2)
if random == 1 then
return firstValue
else
return secondValue
end
end
local num = setNum()
print(num)
Your 2 examples achieve very different things, you will have to use both at some point but parameters like TestFunction(Value) should be used more than global variables.
I dont necessarily need anything… I just need to know whats the better option (But i guess the replies already answered that. So i dont need any more help.)
My apologies. Though it would be more general to use what I provided (in terms of keeping code more organized), it isn’t necessary. Your first example in the original post would work the same.