一)function (函数)
有名函数:
optional_function_scope function function_name( argument1, argument2, argument3..., argumentn) function_body return result_params_comma_separated end
optional_function_scope: 该参数是可选的制定函数是全局函数还是局部函数,未设置该参数默认为全局函数,如果你需要设置函数为局部函数需要使用关键字 local。
function 函数定义关键字
function_name: 指定函数名称。
argument1, argument2, argument3..., argumentn: 函数参数,多个参数以逗号隔开,函数也可以不带参数。
function_body: 函数体,函数中需要执行的代码语句块。
result_params_comma_separated: 函数返回值,Lua语言函数可以返回多个值,每个值以逗号隔开
end:函数定义结束关键字
1)函数实例
--[[ 函数返回两个值的最大值 --]]
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))
=============================
匿名函数
optional_function_scope function_name = function (argument1, argument2, argument3..., argumentn) function_body return result_params_comma_separated end
有名函数的定义本质上是匿名函数对变量的赋值。为说明这一点,考虑
function foo() end 等价于 foo = function () end ---------------------------- 类似地, local function foo() end 等价于 local foo = function () end
==============================
local function 与 function 区别
1 使用function声明的函数为全局函数,在被引用时可以不会因为声明的顺序而找不到
2 使用local function声明的函数为局部函数,在引用的时候必须要在声明的函数后面
function test() test2() test1() end local function test1() print("hello test1") end function test2() print("hello test2") end test() ----------------- local function test1() print("hello test1") end function test() test2() test1() end function test2() print("hello test2") end test()
==========================
函数参数
1) 将函数作为参数传递给函数
local myprint = function(param) print("这是打印函数 - ##",param,"##") end local function add(num1,num2,functionPrint) result = num1 + num2 functionPrint(result) end add(2,5,myprint)
2)传参数,lua参数可变
local function foo(a,b,c,d)
print(a,b,c,d)
end
a、若参数个数大于形参个数,从左向右,多余的实参被忽略
b、若实参个数小于形参个数,从左向右,没有被初始化的形参被初始化为nil
------------------
c、Lua还支持变长参数。用...表示。此时访问参数也要用...,如:
function average(...) result = 0 local arg={...} for i,v in ipairs(arg) do result = result + v end print("总共传入 " .. #arg .. " 个数") return result/#arg end print("平均值为",average(1,2,3,4,5,6))
==============================
3)返回值
Lua函数允许返回多个值,返回多个值时,中间用逗号隔开
函数返回值的规则:
1)若返回值个数大于接收变量的个数,多余的返回值会被忽略掉;
2)若返回值个数小于参数个数,从左向右,没有被返回值初始化的变量会被初始化为nil
local function init() return 1,"lua"; end local x,y,z = init(); print(x,y,z);
注意:
1)当一个函数返回一个以上的返回值,且函数调用不是一个列表表达式的最后一个元素,那么函数只返回第一个返回值
local function init() return 1,"lua"; end local x,y,z = init(),2; print(x,y,z);//output:1 2 nil
local x,y,z = 2 init();
print(x,y,z) //output:2,1,lua
2)如果你确保只取函数返回值的第一个值,可以使用括号运算符
local function init() return 1,"lua"; end local x,y,z = 2,(init()); print(x,y,z);//output:2,1,nil
本文来自博客园,作者:孙龙-程序员,转载请注明原文链接:https://www.cnblogs.com/sunlong88/p/17938865