Avatar

分类

最新留言

链接

lua中可变数量参数的函数

lua中定义函数

posted @ 2008年5月23日 08:05 in Lua , 7795 阅读

在lua中可以这样定义函数

  -- add all elements of array `a'
    function add (a)
      local sum = 0
      for i,v in ipairs(a) do
        sum = sum + v
      end
      return sum
    end

调用是也需要带括号,即使没有参数也要带括号。特例是如果只有一个字符常量参数或者是一个table constructor,可以省略括号。如print "Hello World"

 print [[a multi-line    <-->     print([[a multi-line
     message]]                        message]])

f{x=10, y=20} 

lua为面向对象的函数调用提供了一个特殊语法,o:f(x)和o.f(o,x)意思相同。lua不检验实参的个数是否和形参匹配,多了被丢弃,少了就会设置为nil

假设一个如下定义的函数:

 function f(a, b) return a or b end

we will have the following mapping from arguments to parameters:
    CALL             PARAMETERS
      
    f(3)             a=3, b=nil
    f(3, 4)          a=3, b=4
    f(3, 4, 5)       a=3, b=4   (5 is discarded)

 


登录 *


loading captcha image...
(输入验证码)
or Ctrl+Enter