Lua笔记--function

Lua笔记--Function

函数定义

function foo(v1, v2)
    //do something
end

函数调用

省略括号

Lua函数调用其中有一个比较特别的地方:当函数只有一个参数时(或者说此次调用只传递一个一个参数给该函数),并且这个参数是literal string(字符串字面量)或者是一个table constructor,此时函数调用时可以不用圆括号(),举例如下

s = 'hello'
print s --error: s is not a literal string
print 'hello' --right
function showtable(a)
    for i = 1, #a do
        print(a[i])
    end
end
showtable{'I', 'am', 'learning', 'lua.'}

例中第二行为错误用法,因为s是一个string变量而不是一个string literal ,可以认为用引号引起来的就是literal

第九行直接使用了table constructor,省略了圆括号,至于何为constructor,翻翻书吧

参数个数

定义函数时的参数个数和调用时候的参数个数可以不一样,可以多,可以少,Lua会自动匹配

function add( a, b )
    local a = a or 0
    local b = b or 0
    local ans = a + b
    return ans
end

print(add(2,3,4,5,'kidding me')) --absolutely right!

注意当调用时的参数比定义时的参数少时,函数可以会出错。比如把上面的第2&3行去掉,然后调用add(1) 程序出错。这是因为如果参数只有一个,那么b的值就是nil ,而nil变量和number变量a是不可以相加的。

为了防止这种情况,我们可以给参数附上缺省值,像上面的例子一样。

返回值

Lua里面的函数可以返回多个值,神奇吧哈哈。

function max( a )
    local m = 0
    local mindex = 0
    for i = 1, #a do
        if m < a[i] then
            m = a[i]
            mindex = i
        end
    end
    return m, mindex
end
a = {1,2,0,-4}
m = max(a)
print(m)
t,mi = max(a)
print(mi)
print(max(a))
print(max(a), 'lua')

类似调用和定义函数时的参数数目差别,lua会根据接收返回值的变量数量来决定返回几个值

Lua always adjusts the number of results from a function to the circumstances of the call. When we call a function as a statement, Lua discards all results from the function. When we use a call as an expression, Lua keeps only the first result. We get all results only when the call is the last (or the only) expression in a list of expressions. These lists appear in four constructions in Lua: multiple assignments, arguments to function calls, table constructors, and return statements.

只有我们把多返回值函数当成表达式来用时,并且函数是在表达式列表的最后,我们才可能得到全部的返回值。

在以下四种表达式列表中,可以得到所有的返回值,否则的话,只返回第一个返回值

  • 多变量赋值
  • 当成函数参数
  • table constructor
  • return语句

你可能感兴趣的:(Lua笔记--function)