I'm trying to learn Lua as my first programming language. I'm learning about functions right now. I understand why we would want them, but I'm still confused on the arguments part of them. I have had a lot of people explain them to me clear as day, but I still cannot wrap my head around them. I am very confused on the return part of them. Why do we have to return something, what are we returning, and where are we returning "it"? Can someone please break down this code to me in monkey terms or like I'm 5?
Example:
Operate = function(a, b, operation)
return operation(a, b)
end
local c = Operate(10, 42, function(a, b) return a b end)
print(c)
CodePudding user response:
I won't write a complete beginners tutorial on functions here. There are plenty available online.
The code provided does the following:
It defines a local reference c
to the return value of the function call
Operate(10, 42, function(a, b) return a b end)
where
function(a, b) return a b end
defines a function value with two parameters a
and b
that when called returns the sum of a
and b
.
This function value is provided as the third argument to Operate
.
It then calls the print function and provides the local variable c
as the only argument where c
resolves to the return value of the Operate
call.
What Operate
does and returns is unknown as you did not provide any information.
Often functions create results. As the sum a b
in your example. The function doesn't care what you do with that result or where you want to store it. So it just returns it. It basically says, here's the sum of a and be. Do with it whatever you want.
CodePudding user response:
In simple terms, an argument is a value that the function can use. For example, let's try summing two numbers, without arguments:
local summand1
local summand2
local result
function sum()
result = summand1 summand2
end
summand1 = 3
summand2 = 4
sum()
print(result)
There are many problems here.
First of all, you need 3 statements to sum something. Why would anyone want that when you can use a single expression?
And also, why should anyone complicate the thing by using 3 additional variables? More variables create more confusion.
Let's improve it.
function sum(summand1, summand2)
return summand1 summand2
end
print(sum(3,4))
This function can be used in an expression (it can be directly used as a value), because it returns a value. Returning isn't that complicated, it just gives you a value. That's it. It's just like using the name of a variable to get the value: You can call a function to get a value it returns.
You can use the return value like any value: 1
, or a variable called x
, or "This string"
...
For example, you've probably heard of math.random
. math.random
is also a function, and it takes 2 arguments. It returns a random number between the two given arguments.