函数格式:
optional_function_scope function function_name( argument1, argument2, argument3..., argumentn)
function_body
return result_params
end
参数说明:
参数 | 说明 |
---|---|
optional_function_scope | 指定函数是全局函数还是局部函数 |
function_name | 函数名称 |
argument | 函数参数 |
function_body | 函数体 |
result_params | 函数返回值 |
多个返回值
function swap(x,y)
x,y=y,x
return x,y
end
x,y=10,20
a,b=swap(x,y)
print(a..','..b)
--20,10
将函数作为参数
test1=function(a,b)
su=a+b
print("sum is:"..su)
end
function mymax(a,b,func)
func(a,b)
if a>b
then
return a
else
return b
end
end
x,y=10,20
zz=mymax(x,y,test1)
print("the max number is:"..zz)
--sum is:30
--the max number is:20
参数个数可变
在函数参数列表中使用三点 … 表示函数有可变的参数
function summ(...)
local s=0
for i,k in ipairs{...} do
s=s+k
end
return s
end
print(summ(2,3,4,6,7))
--22