一、函数
在Lua中,函数是作为"第一类值"(First-Class Value),这表示函数可以存储在变量中,可以通过参数传递给其他函数,或者作为函数的返回值(类比C/C++中的函数指针),这种特性使Lua具有极大的灵活性。
Lua对函数式编程提供了良好的支持,可以支持嵌套函数。
另外,Lua既可以调用Lua编写的函数,还可以调用C语言编写的函数(Lua所有的标准库都是C语言写的)。
定义一个函数
function hello()
print('hello')
end
</div>
hello函数不接收参数,调用:hello(),虽然hello不接收参数,但是还可以可以传入参数:hello(32)
另外如果只传递一个参数可以简化成functionname arg的调用形式(注意数值不行)
> hello '3'
hello
> hello {}
hello
> hello 3
stdin:1: syntax error near '3'
</div>
另外对变量名也不适用
> a = 21
> print a
stdin:1: syntax error near 'a'
</div>
另外,Lua函数不支持参数默认值,可以使用or非常方便的解决(类似Javascript)
> function f(n)
>> n = n or 0
>> print(n)
>> end
> f()
0
> f(1)
1
</div>
Lua支持返回多个值,形式上非常类似Python:
> function f()
>> return 1,2,3
>> end
> a,b,c = f()
> print(a .. b .. c)
123
</div>
函数调用的返回值可以用于table:
> t = {f()}
> print(t[1], t[2], t[3])
1 2 3
</div>
可见,f()返回的三个值分别称为table的3个元素,但是情况并不总是如此:
> t = {f(), 4}
> print(t[1], t[2], t[3])
1 4 nil
</div>
这次,f()返回的1,2,3只有1称为table的元素;
> t = {f(), f()}
> print(t[1], t[2], t[3], t[4], t[5])
1 1 2 3 nil
</div>
总之:只有最后一项会完整的使用所有返回值(假如是函数调用)。
对于无返回值的函数,可以使用(f())的形式强行返回一个值(nil)
> function g()
>> end
> print(g())
> print((g()))
nil
</div>
实际上,(f())形式的调用返回一个且只返回一个值
> print((f()))
1
> print(f())
1 2 3
</div>
二、变长参数
Lua支持编程参数,使用简单(借助于table、多重赋值)
> function f(...)
for k,v in ipairs({...}) do
print(k,v)
end
end
> f(2,3,3)
1 2
2 3
3 3
</div>
使用多重赋值的方式
> function sum3(...)
>> a,b,c = ...
>> a = a or 0
>> b = b or 0
>> c = c or 0
>> return a + b +c
>> end
> =sum3(1,2,3,4)
6
> return sum3(1,2)
3
</div>
通常在遍历变长参数的时候只需要使用{…},然而变长参数可能会包含一些nil;那么就可以用select函数来访问变长参数了:select('#', …)或者 select(n, …)
select('#', …)返回可变参数的长度,select(n,…)用于访问n到select('#',…)的参数
> =select('#', 1,2,3)
3
> return select('#', 1,2, nil,3)
4
> =select(3, 1,2, nil,3)
nil 3
> =select(2, 1,2, nil,3)
2 nil 3
</div>
注意:Lua5.0中没有提供…表达式,而是通过一个隐含的局部table变量arg来接收所有的变长参数,arg.n表示参数的个数;
三、函数式编程
函数做一个First-Class Value可以赋值给变量,用后者进行调用
> a = function() print 'hello' end
> a()
hello
> b = a
> b()
hello
</div>
匿名函数
> g = function() return function() print 'hello' end end
> g()()
hello
</div>
函数

