Lua learning (7)--Lua functions

There are two main purposes of Lua functions:
1. To complete the specified task, in this case, the function is used as a call statement;
2. To calculate and return a value, in this case, the function is used as an expression of an assignment statement.

function definition

The Lua programming language function definition format is as follows:

optional_function_scope function function_name( argument1, argument2, argument3..., argumentn)
    function_body
    return result_params_comma_separated
end
  • optional_function_scope:
    This parameter is optional and specifies whether the function is global or local. If this parameter is not set, it defaults to a global function. Local functions need to use the keyword local .
  • function_name:
    Specifies the function name.
  • argument1, argument2, argument3..., argumentn:
    function parameters, multiple parameters are separated by commas, and the function can also have no parameters.
  • function_body:
    The function body, the code statement block that needs to be executed in the function.
  • result_params_comma_separated: The
    function return value, you can return multiple values , each value is separated by a comma.

example

The following example defines a function max() with parameters num1, num2, which compares 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 result of executing the above code is:

两值比较最大值为     10
两值比较最大值为     6

Note:
add then after the above if.

In Lua, we can pass functions as parameters to functions , as in the following example:

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 result of executing the above code is:

这是打印函数 -   ##    10    ##
这是打印函数 -   ##    7    ##

Note: print("This is the print function - ##",param,"##"), the concatenation of strings and variables in the output function is to use commas.

Multiple return values

Lua functions can return multiple result values , such as string.find, which returns the "start and end index" of the matching string (nil if no matching string exists).

> s, e = string.find("www.runoob.com", "runoob") 
> print(s, e)
5    10

In Lua functions, you can return multiple values ​​by listing the list of values ​​to be returned after return, 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 result of executing the above code is:

23    3

variable parameter

Lua functions can accept a variable number of parameters , similar to the C language, using three dots in the function parameter list... indicates 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

Note: for i, v in ipairs{…} do variadic loop here is curly braces not parentheses



We can assign a variable parameter to a variable.
For example, we calculate the average of several numbers:

function average(...)
   result = 0
   local arg={...}    --> arg 为一个表,局部变量
   for i,v in ipairs(arg) do
      result = result + v
   end
   print("总共传入 " .. #arg .. " 个数")
   return result/#arg
end

print("平均值为",average(10,5,3,4,5,6))

The result of executing the above code is:

总共传入 6 个数
平均值为    5.5

We can also get the number of varargs with select("#",...):

function average(...)
   result = 0
   local arg={...}
   for i,v in ipairs(arg) do
      result = result + v
   end
   print("总共传入 " .. select("#",...) .. " 个数")
   return result/select("#",...)
end

print("平均值为",average(10,5,3,4,5,6))

The result of executing the above code is:

总共传入 6 个数
平均值为    5.5

Sometimes we may need several fixed parameters plus variable parameters, the fixed parameters must be placed before the variable-length parameters:

function fwrite(fmt, ...)  ---> 固定的参数fmt
    return io.write(string.format(fmt, ...))     
end

fwrite("runoob\n")       --->fmt = "runoob", 没有变长参数。  
fwrite("%d%d\n", 1, 2)   --->fmt = "%d%d", 变长参数为 12

The output is:

runoob
12

Usually, you only need to use {…} when traversing variable-length parameters. However, variable-length parameters may contain some nil, so you can use the select function to access variable-length parameters: select('#', …) or select(n , …)
select('#', …) returns the length of variable parameters
select(n, …) is used to access the parameters from n to select('#', …)
When calling select, a fixed argument selector must be passed in (selector switch) and a series of variable length parameters. If the selector is the number n, then select returns its n-th variable argument, otherwise it can only be the string "#", so select will return the total number of variable-length arguments. Example code:

do  
    function foo(...)  
        for i = 1, select('#', ...) do  -->获取参数总数
            local arg = select(i, ...); -->读取参数
            print("arg", arg);  
        end  
    end  

    foo(1, 2, 3, 4);  
end

The output is:

arg    1
arg    2
arg    3
arg    4

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325643090&siteId=291194637