In the beginning where i scripted i knew about returning. Now i kinda lost it and i am confused; could anyone give a brief short use of it and what it does?
You can comment, and answer. I prefer answers, but i don't really care :D
Yes, i know some of you may say it's a helping site, not a request site :)
If the following then thanks!
Functions are bits of code that you would like to reuse.
local function foo() print("hello") end
This function will print hello to the console.
When we use a function, we call it a function call.
foo()
This is a function call.
Function calls are expressions. Meaning they will evaluate/simplify to a value. In terms of function calls, they will evaluate as whatever the function returns.
local val = foo()
This will print "hello" to the console, but the value of val
will be nil. Because foo()
does not return anything. And nothing in Lua in nil.
If we want the function to not evaluate as nil then we use return
local function foo() print("hello") return 5 end local val = foo()
The value of val
is now 5.
This is helpful because we can abstract tasks with multiple terms like this
local function sum(a, b, c) return a + b + c end local val = sum(1, 2, 3)
In this case val is 6. Because 1+2+3 is six.