How should i reference a part in a function?

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()

Just assuming:

function Ex(Item: Instance)
end

Ex(someObject)
1 Like

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)
1 Like

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.

This works, but I’m not sure if this is entirely what they need. Then again, I’m a little confused. I don’t fully understand what they need.

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.)

1 Like

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.

1 Like

This is the best way to do it

local num = math.random(1,2) == 1 and 1 or 5

50/50 chance of setting num to either 1 or 5

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.