English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In Lua, functions are the main method of abstraction for statements and expressions. They can be used to handle special tasks and also to calculate values.
Lua provides many built-in functions that you can easily call in your program, such as the print() function, which can print the parameters passed in on the console.
There are mainly two uses of Lua functions:
1.Complete the specified task, 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.
The function definition format of 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 to specify whether the function is a global function or a local function, if not set, it defaults to a global function. If you need to set the function as a local function, you need to use the keyword local.
function_name: Specify the function name.
argument1, argument2, argument3..., argumentn: Function parameters, multiple parameters separated by commas, functions can also be without parameters.
function_body: Function body, the code block that needs to be executed in the function.
result_params_comma_separated: Function return value, Lua functions can return multiple values, each separated by a comma.
The following example defines the function max(), parameter is num1, num2Used to compare the size of two values and return the maximum value:
--Function returns the maximum of two values --]] function max(num1, num2) if (num1 > num2) then result = num1; else result = num2; end return result; end -- Call the function print("The greater value of the two values is ", max(10,4))}} print("The greater value of the two values is ", max(5,6))}}
The execution result of the above code is:
The greater value of the two values is 10 The greater value of the two values is 6
In Lua, we can pass functions as parameters to other functions, as shown in the following example:
myprint = function(param) print("This is a print function - ##\"param\"##) end function add(num)1,num2,functionPrint) result = num1 + num2 -- Call the passed function parameter functionPrint(result) end myprint(10) -- myprint function as a parameter add(2,5,myprint)
The execution result of the above code is:
This is the print function - ## 10 ## This is the print function - ## 7 ##
Lua functions can return multiple result values, such as string.find, which returns the starting and ending indices of the matched string (nil if no matching string is found).
> s, e = string.find("www.w3,"w3codebox" > print(s, e) 5 10
In Lua functions, you can return multiple values by listing the values to be returned after return, such as:
function maximum(a) local mi = 1 -- Maximum value index 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 execution result of the above code is:
23 3
Lua functions can accept a variable number of arguments, similar to C language, using three dots ... in the function parameter list to indicate that the function has variable arguments.
function add(...) local s = 0 for i, v in ipairs{...} do --> {...} represents an array composed of all variable-length arguments s = s + v end return s end print(add(3,4,5,6,7))}} --->25
We can assign variable arguments to a variable.
For example, we calculate the average of several numbers:
function average(...) result = 0 local arg={...} --> arg is a table, a local variable for i,v in ipairs(arg) do result = result + v end print("Total number of inputs " .. #arg .. " items") return result/#arg end print("The average is",average(10,5,3,4,5,6))}}
The execution result of the above code is:
Total number of inputs 6 number Average value 5.5
We can also use select("#",...) to get the number of variable arguments:
function average(...) result = 0 local arg={...} for i,v in ipairs(arg) do result = result + v end print("Total number of inputs " .. select("#",...) .. " items") return result/select("#",...) end print("The average is",average(10,5,3,4,5,6))}}
The execution result of the above code is:
Total number of inputs 6 number Average value 5.5
Sometimes we may need several fixed parameters plus variable-length parameters, and the fixed parameters must be placed before the variable-length parameters:
function fwrite(fmt, ...) --->Fixed parameter fmt return io.write(string.format(fmt, ...)) end fwrite("w3codebox\n") --->fmt = "w3codebox fwrite("%d%d\n", 1, 2) --->fmt = "%d%d", the variable-length arguments are 1 and 2
The output result is:
w3codebox 12
Generally, when traversing variable-length arguments, it is only necessary to use {…}, but variable-length arguments may contain some nil, so you can use select function to access variable-length arguments:select('#', ...) or select(n, ...)
select('#', ...) returns the length of the variable-length arguments.
select(n, ...) is used to return the nth argument in the argument list. n th
When calling select, you must pass a fixed argument selector (selector switch) and a series of variable-length arguments. If the selector is a number n, then select returns the nth argument in the argument list. n number of arguments, otherwise it can only be a string #, so select returns the total number of variable-length arguments.
Example Code:
do function foo(...) for i = 1, select('#', ...) do -->Get Total Number of Parameters local arg = select(i, ...); -->Read Parameters print("arg", arg); end end foo(1, 2, 3, 4); end
The output result is:
arg 1 arg 2 arg 3 arg 4