I'm still learning how to script and stuff so I don't really know much about everything. I'm really confused on parameters and how they work. Can someone please explain the various uses and give me some examples? Thanks!
In order to explain functions and their usage, we need to go on to a more abstract level first. Think of a function as a machine. You can give the machine a certain set of input and it will spit out some output. Let's say we have a function called foo()
. We can give this function some input by doing foo(5 , 4)
. Here, we gave the foo
function the numbers 5
and 4
. How do we get the output of this function? In order to get the output we can do output = foo(5 , 4)
. In this case, the output
variable would represent the output. This foo()
function can be implemented in Lua like this:
function foo (x , y) --Do something with the input x and input y local sum = x + y --Return the output return sum end local output = foo(5 , 4) --This changes the x variable to 5 and the y variable to 4 inside the function print(output) --This prints out 9
I'll try to explain this the best I can.
Parameters are used to pass data to the function which then can be used inside the function's scope. You can then read the data by using it's name (identifier) or maybe even assign a new value to that data with the assignment operator (=). It's very useful to create functions so you don't duplicate code later and instead you could just call the function again! Parameters can be used like this, for example:
local firstNumber = 5 local secondNumber = 10 -- Heres where you can use parameters to pass data to the function local function printAddedNumbers (x, y) local totalValue = x + y print (x.." + "..y.." = "..totalValue) end