Hello, pretty new to OOP, and a little embarrassed to ask but can someone explain return types in functions to me. What determines the use of “Return true”, “Return False”, or “Return”? Perhaps provide small examples? Just can’t get my head around it ATM. Thanks [import]uid: 132483 topic_id: 23488 reply_id: 323488[/import]
you can send parameters to a function,
do something with it and return every data type as result
function addNumbers (num1, num2)
local number1 = num1
local number2 = num2
local addedNumbers = number1 + number2
return addedNumbers
end
local newSum = addNumbers (2, 8) -- newSum = 10
-finefin [import]uid: 70635 topic_id: 23488 reply_id: 94209[/import]
You can also return multiple values if you want:
function addNumbers (num1, num2)
local number1 = num1
local number2 = num2
local addedNumbers = number1 + number2
local number3 = 3.14
local text1 = "Hello world"
local flag1 = false
return addedNumbers, number3, text1, flag1
end
local newSum, newNumber, newText, newFlag = addNumbers (2, 8)
[import]uid: 123200 topic_id: 23488 reply_id: 94261[/import]
Returning values isn’t too hard to grasp, but what about Return True/False or just Return? [import]uid: 132483 topic_id: 23488 reply_id: 94267[/import]
Do you mean something like:
local function myFunc( values )
--do something
return true
end
if myFunc(values) then
--do more
end
Basically I guess it’s up to you if and when you want to use return true/false.
It is good practice to return true from listeners.
[import]uid: 123200 topic_id: 23488 reply_id: 94273[/import]
I guess I’m just confused. If you are always returning true at the end of the function, won’t the “If” statement always be true? [import]uid: 132483 topic_id: 23488 reply_id: 94299[/import]
No, ofc you are correct. This specific way you’re right.
It was just an example to illustrate.
I guess it’s me who’s confused :-). I guess I don’t really understand what you are referring to. Sorry.
If you return anything and what is up to you. You do not need to return anything if you don’t need it.
[import]uid: 123200 topic_id: 23488 reply_id: 94307[/import]
maybe you’re looking for something like this
[code]
function isBiggerThan (num1, num2)
if num1 > num2 then
return true
elseif num1 < num2 then
return false
else
print (“error”)
return
end
end
isBiggerThan (10, 5) – true
isBiggerThan (2, 3) – false
[/code] [import]uid: 70635 topic_id: 23488 reply_id: 94323[/import]