I am new to this Lua thing, but I am confuse what is a parameter, and how it works. Can anyone give me an simple and east answer. Thank you!
A parameter, also called an argument (although they don't exactly mean the same, functionally they do), is something you provide to a function for it to know more precisely what you want to do - it provides it any information it might require to run.
A function is an element which runs code it's been given. This way, you can avoid repeating the same lines of code every time you want to do the same thing. But every time you repeat that thing, you might want it to do something different.
Imagine you have a show_text()
function. This function displays a text on the player's screen when it is run. The code to show a text is complicated, and you don't want to repeat it everytime you display text. But there's a problem - you don't want the text to be always the same! This is where parameters are useful.
By introducing a parameter to show_text()
, which we are going to call text
, we can specify exactly what text we want to use, like this:
show_text("Hello world!")
The code inside show_text()
will be able to read this parameter and use it to display text.
Here's how you define a parameter:
function MyFunction(parameter1, parameter2) -- your code end
Here's how you use it:
MyFunction("This is parameter 1", "and this is 2")
There's other, more complicated types of parameters. In Lua, all parameters are mandatory: not giving a parameter when the function has one would cause an error. The way to get around this is by using ...
. This allows for a variable amount of arguments, which are passed as a tuple. (See Variable Number of Arguments).
Parameters also don't have specified type checks, so to raise an error if an argument provided is invalid, you'd use assert.