1. loadfile、loadstring: The environment of the returned function is the global environment.
i = 32 local i = 0 f = load("i = i + 1; print(i)") g = function () i = i + 1; print(i) end f() --> 33 g() --> 1
2. 适当缓存预编译好的chunk,在某些时候能提高不少效率。
local a_file = loadfile("a.lua"); -- or local a_string = loadstring("i=i+1"); a_file();
3. Lua会调整实参个数以与形参个数一致:多余的实参丢弃,实参不足补nil。(multiple assignment也是如此)
4. 函数返回多个值时,只有当函数调用位于表达式最后或是唯一的表达式时,才会尽可能多的保留返回值,其它情况都只保留第1个返回值。
function foo () return "a", "b" end x,y,z = foo(),1 -- x="a", y=1, z=nil x,z = 1,foo(),2 -- x=1, y="a", z=2 x,foo() -- x=1, z="b" x,z = foo() -- x="a", y="b", z=nil
x,z = (foo()) -- x="a", y=nil, z=nil
5. closure:
function newCounter () local i = 0 return function () -- anonymous function i = i + 1 return i end end c1 = newCounter() print(c1()) --> 1 print(c1()) --> 2 c2 = newCounter() print(c2()) --> 1 print(c1()) --> 3 print(c2()) --> 2
6. Proper Tail Calls: tail call不占用额外的栈空间,尾调用的嵌套层数是无限的(不受栈空间影响)。
function foo (n) if n > 0 then return foo(n - 1) end end
In Lua,only a call with the form "return func(args)" is a tail call.