YouTip LogoYouTip

Lua Functions

In Lua, functions are the primary means of abstracting statements and expressions. They can be used to handle specific tasks or to compute values. Lua provides many built-in functions that you can conveniently call in your programs. For example, the `print()` function can print the passed arguments to the console. Lua functions have two main purposes: * 1. To perform a specific task, in which case the function is used as a calling statement; * 2. To compute and return a value, in which case the function is used as an expression in an assignment statement. ### Function Definition The format for defining a function 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 Analysis: * **optional_function_scope:** This parameter is optional and specifies whether the function is global or local. If not set, the function is global by default. If you need to set the function as local, you must use the keyword **local**. * **function_name:** Specifies the function name. * **argument1, argument2, argument3..., argumentn:** Function arguments. Multiple arguments are separated by commas. A function can also have no arguments. * **function_body:** The function body, which is the block of code statements to be executed within the function. * **result_params_comma_separated:** The function's return values. Lua functions can return multiple values, each separated by a comma. ### Example The following example defines a function **max()** with parameters num1 and num2, which compares the two values and returns the larger one: ## 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 execution result of the above code is: The maximum of the two values is 10The maximum of the two values is 6 In Lua, we can pass a function as an argument to another function, as shown in the following example: ## Example myprint =function(param) print("This is the print function - ##",param,"##") end function add(num1,num2,functionPrint) result = num1 + num2 -- Call the passed function argument functionPrint(result) end myprint(10) -- myprint function is passed as an argument add(2,5,myprint) The execution result of the above code is: This is the print function - ##10##This is the print function - ##7## * * * ## Multiple Return Values Lua functions can return multiple result values. For example, `string.find` returns the "start and end indices" of a matching string (or nil if no match is found). > s, e = string.find("www..com", "") > print(s, e)510 In a Lua function, you can return multiple values by listing them after the `return` keyword, like this: ## Example function maximum (a) local mi =1-- Index of the maximum value local m = a-- 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: 233 * * * ## Variable Arguments Lua functions can accept a variable number of arguments. Similar to C, you can use 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 the variable arguments to a variable. For example, we can calculate the average of several numbers: ## Example 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("A total of "..#arg .." numbers were passed in") return result/#arg end print("The average is",average(10,5,3,4,5,6)) The execution result of the above code is: A total of 6 numbers were passed inThe average is5.5 We can also use `select("#",...)` to get the number of variable arguments: ## Example function average(...) result =0 local arg={...} for i,v in ipairs(arg)do result = result + v end print("A total of ".. select("#",...).." numbers were passed in") return result/select("#",...) end print("The average is",average(10,5,3,4,5,6)) The execution result of the above code is: A total of 6 numbers were passed inThe average is5.5 Sometimes we may need a few fixed parameters plus variable arguments. The fixed parameters must come before the variable arguments: ## Example function fwrite(fmt,...)---> Fixed parameter fmt return io.write(string.format(fmt,...)) end fwrite("tutorialn")--->fmt = "", no variable arguments. fwrite("%d%dn",1,2)--->fmt = "%d%d", variable arguments are 1 and 2 The output is: 12 Usually, when iterating over variable arguments, you only need to use `{…}`. However, variable arguments might contain some `nil` values. In that case, you can use the **select** function to access the variable arguments: **select('#', …)** or **select(n, …)** * `select('#', …)` returns the length of the variable arguments. * `select(n, …)` is used to return all arguments from the starting point **n** to the end of the argument list. When calling `select`, you must pass a fixed argument `selector` (the selection switch) and a series of variable arguments. If `selector` is a number `n`, then `select` returns all arguments from index **n** to the end of the argument list. Otherwise, it must be the string `#`, in which case `select` returns the total number of variable arguments. ## Example function f(...) 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: 22 3 4 5 ## Example do function foo(...) for i =1, select('#',...)do-->Get the total number of parameters local arg = select(i,...);-->Read the parameter, `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: arg1 arg2 arg3 arg4
← Cpp MultithreadingCpp Preprocessor β†’