函数
- 例一
function hello()
print('hello')
end
hello '3'
hello {}
-- hello 3
hello函数不接收参数,调用:hello(),虽然hello不接收参数,但是还可以可以传入参数:hello(32)
测试结果如下

另外如果只传递一个参数可以简化成functionname arg的调用形式(注意数值不行, 从gif可以看出,去掉注释会报错)
但是arg不能为变量名,使用报错

- 例二
function f()
return 1,2,3
end
t = {f()}
print(t[1], t[2], t[3])
t = {f(), 4}
print(t[1], t[2], t[3])
t = {f(), f()}
print(t[1], t[2], t[3], t[4], t[5], t[6])
运行结果如下

结论:只有最后一项会完整的使用所有返回值(假如是函数调用)。
- 例三
print(select('#', 1,2,3))
print(select('#', 1,2, nil,3))
print(select(3, 1,2, nil,3))
print(select(2, 1,2, nil,3))
运行结果

结论:select('#', …)返回可变参数的长度,select(n,…)用于访问n到select('#',…)的参数
局部函数
local lf
lf = function(n)
if n <= 0 then
return
end
print 'hello'
n = n -1
lf(n)
end
lf(3)
运行结果

应该首先声明local lf, 在进行赋值。Lua支持一种local function(…) … end的定义形式
尾调用
--[[function f(n)
if n <= 0 then
return 0
end
a = f(n-1)
return n * a
end
f(10000000000)
--]]
function f(n, now)
if n <= 0 then
return now
end
return f(n-1, now*n)
end
f(10000000000, 1)

递归函数没有使用尾递归,而参数为大数时,堆栈溢出;优化为尾递归,运行n久也无堆栈溢出。
网友评论