Lua Functions
In Lua, functions are the primary method for abstracting statements and expressions. They can be used both to handle specific tasks and to compute values.
Lua provides many built-in functions that you can conveniently call in your programs. For example, the print() function prints the passed parameters to the console.
Lua functions mainly have two uses:
- 1. Complete specified tasks; in this case, the function is used as a call statement;
- 2. Calculate and return values; in this case, the function is used as an expression in an assignment statement.
Function Definition
The function definition format in the Lua programming language is as follows:
optional_function_scope function function_name( argument1, argument2, argument3..., argumentn) function_body return result_params_comma_separated end
Explanation:
optional_function_scope:This parameter is optional and specifies whether the function is a global or local function. If this parameter is not set, the function is global by default. If you need to set the function as a local function, use the keywordlocal。
function_name: Specify the function name.
argument1, argument2, argument3..., argumentn: Function parameters; multiple parameters are separated by commas. The function can also have no parameters.
function_body: Function body: the block of code statements that need to be executed in the function.
result_params_comma_separated: Function return values. Lua functions can return multiple values, each separated by commas.
Example
The following example defines the functionmax(), with parameters num1, num2, used to compare the two values and return the maximum value:
Example
function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end
-- Call the function
print("The maximum of the two values is ",max(10,4))
print("The maximum of the two values is ",max(5,6))
The output of the above code is:
两值比较最大值为 10 两值比较最大值为 6
In Lua, we can pass functions as arguments to other functions, as in the following example:
Example
print("This is the print function - ##",param,"##")
end
function add(num1,num2,functionPrint)
result = num1 + num2
-- Call the passed function parameter
functionPrint(result)
end
myprint(10)
-- myprint function is passed as an argument
add(2,5,myprint)
The output of the above code is:
这是打印函数 - ## 10 ## 这是打印函数 - ## 7 ##
Multiple Return Values
Lua functions can return multiple result values, such as string.find, which returns the "start and end indices" of the matched string (or nil if no match is found).
> s, e = string.find("www.example.com", "example")
> print(s, e)
5 10
In Lua functions, list the values to return after return to return multiple values, for example:
Example
local mi = 1 -- Index of the maximum value
local m = a[mi] -- Maximum value
for i,val in ipairs(a) do
if val > m then
mi = i
m = val
end
end
return m, mi
end
print(maximum({8,10,23,12,5}))
The output of the above code is:
23 3
Variable Arguments
Lua functions can accept a variable number of parameters. Similar to C, use three dots in the function parameter list... to indicate that the function has variable parameters.
function add(...)
local s = 0
for i, v in ipairs{...} do --> {...} 表示一个由所有变长参数构成的数组
s = s + v
end
return s
end
print(add(3,4,5,6,7)) --->25
We can assign the variable arguments to a variable.
For example, let's calculate the average of several numbers:
Example
result = 0
local arg={...} --> arg is a table, local variable
for i,v in ipairs(arg) do
result = result + v
end
print("Total passed " .. #arg .. " numbers")
return result/#arg
end
print("The average is",average(10,5,3,4,5,6))
The output of the above code is:
总共传入 6 个数 平均值为 5.5
We can also use select("#",...) to get the number of variable arguments:
Example
result = 0
local arg={...}
for i,v in ipairs(arg) do
result = result + v
end
print("Total passed " .. select("#",...) .. " numbers")
return result/select("#",...)
end
print("The average is",average(10,5,3,4,5,6))
The output of the above code is:
总共传入 6 个数 平均值为 5.5
Sometimes we may need a few fixed parameters plus variable arguments. Fixed parameters must be placed before the variable arguments:
Example
return io.write(string.format(fmt, ...))
end
fwrite("example\n") ---> fmt = "example", no variable arguments.
fwrite("%d%d\n", 1, 2) ---> fmt = "%d%d", variable arguments are 1 and 2
The output is:
example 12
Usually when iterating over variable arguments, you only need to use{…}, however, variable arguments may contain somenil, then you can useselectfunction to access the variable arguments:select('#', …)orselect(n, …)
- select('#', …)Returns the length of the variable arguments.
- select(n, …)Used to return from the start positionnthe list of all arguments from the start to the end position.
When calling select, you must pass a fixed actual argument selector (selector switch) and a series of variable arguments. If selector is the number n, then select returns the argument list from indexnto the end position, all argument lists; otherwise it can only be the string#, in which case select returns the total number of variable arguments.
Example
a = select(3,...) --> Starting from the third position, variable a corresponds to the first parameter in the variable list on the right
print (a)
print (select(3,...)) --> Print all list parameters
end
f(0,1,2,3,4,5)
The output is:
2 2 3 4 5
Example
function foo(...)
for i = 1, select('#', ...) do --> Get the total number of parameters
local arg = select(i, ...); --> Read parameters; arg corresponds to the first parameter in the variable list on the right
print("arg", arg);
end
end
foo(1, 2, 3, 4);
end
The output is:
arg 1 arg 2 arg 3 arg 4Other Extensions