The best Lua function Tutorial In 2024, In this tutorial you can learn Multiple return values,Variable parameter,
In Lua, function is the main method of abstract statements and expressions. Both can be used to deal with some special work, it can also be used to calculate some values.
Lua provides many built-in functions, you can easily call them, such as print () function can be passed parameters print on the console in the program.
Lua function There are two main purposes:
Lua programming language functions defined in the following format:
optional_function_scope function function_name( argument1, argument2, argument3/en., argumentn) function_body return result_params_comma_separated end
Resolution:
The following example defines a functionmax (), parameters num1, num2, used to compare the size of two values and returns the maximum value:
--[[ 函数返回两个值的最大值 --]] function max(num1, num2) if (num1 > num2) then result = num1; else result = num2; end return result; end -- 调用函数 print("两值比较最大值为 ",max(10,4)) print("两值比较最大值为 ",max(5,6))
The above code is executed as a result of:
两值比较最大值为 10 两值比较最大值为 6
Lua we can function as a parameter passed to the function, the following examples:
myprint = function(param) print("这是打印函数 - ##",param,"##") end function add(num1,num2,functionPrint) result = num1 + num2 -- 调用传递的函数参数 functionPrint(result) end myprint(10) -- myprint 函数作为参数传递 add(2,5,myprint)
The above code is executed as a result of:
这是打印函数 - ## 10 ## 这是打印函数 - ## 7 ##
Lua function can return multiple result values, such as string.find, which returns the matching string "beginning and end of the subscript" (if there is no match string returns nil).
> s, e = string.find("www.w3write.com", "w3big") > print(s, e) 5 10
Lua function, after the return is worth to return a list of lists can return multiple values, such as:
function maximum (a) local mi = 1 -- 最大值索引 local m = a[mi] -- 最大值 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 above code is executed as a result of:
23 3
Lua function can accept a variable number of arguments, and C language similar to using a three-point function parameter list (/en.) denotes a function with variable parameters.
Lua function parameters in a table called arg, #arg represents the number of parameters passed.
For example, we calculate the average of a few numbers:
function average(/en.) result = 0 local arg={/en.} for i,v in ipairs(arg) do result = result + v end print("总共传入 " /en #arg /en " 个数") return result/#arg end print("平均值为",average(10,5,3,4,5,6))
The above code is executed as a result of:
总共传入 6 个数 平均值为 5.5