Hello, I am a beginner scripter and have been looking into returning functions. As I was checking it out I started to wonder why you’d want to return a value when you might as well just have that value be assigned to a variable. I haven’t seen any forum posts that discuss this which is why I’ve decided to make a post.
local function returnString()
return "Hello, world!"
end
-- vs
local stringVariable
local function AssignString()
stringVariable = "Hello, world!"
end
-- --
print(returnString()) -- -> Hello, world!
AssignString()
print(stringVariable) -- -> Hello, world!
if there is a difference between using these, please provide some examples.
It could work, yes, but it’d easily make your script a mess if you declared a variable for each value you wanted to return.
Additionally, a function can return another function/table of functions, which you can quickly just call on top of that initial function call, instead of storing it in a variable and then calling that variable on the next line (adding more clutter):
local function returnsSomeFunction()
local someFunction = function()
print("hello!")
end
return someFunction end
end
-- This:
returnsSomeFunction()() -- "hello!"
-- is the same as:
local returnedFunction = returnsSomeFunction()
returnedFunction() -- "hello!"
There’s probably better arguments but I’m a little slow lol
The end result is the same but setting a variable even if it’s nil will still use memory space. Both have their use cases tho. If you need to use the value in multiple other functions for example you should defenitely use a variable but otherwise it’s more convinient to just return the value.
local function returnString()
return "Hello, world!"
end
print(returnString()) -- No variable taking up memory
-- vs
local stringVariable
local function AssignString()
stringVariable = "Hello, world!"
end
local function calculate()
print(stringValue)
end
print(stringValue)
if I have the return value assigned to a variable what would be best?:
local variable
-- --
local function returnString()
return "Hello, world!"
end
variable = returnString()
-- vs
local function assignString()
variable = "Hello, world!"
end
assignString()
-- --
is anyone of them more beneficial or is there no difference?