Lua 命名参数怎么用?

文章导读
Previous Quiz Next Lua 函数通过位置机制接收参数。每当调用函数时,其参数会根据位置进行匹配。第一个参数对应第一个形参,第二个对应第二个,以此类推。请看下面的示例——
📋 目录
  1. 使用位置参数
  2. 位置参数的完整示例
A A

Lua - 带命名参数的函数



Previous
Quiz
Next

Lua 函数通过位置机制接收参数。每当调用函数时,其参数会根据位置进行匹配。第一个参数对应第一个形参,第二个对应第二个,以此类推。请看下面的示例——

main.lua

-- function to calculate area of a shape passed
function calculateArea(type, l, b)
   local length = l
   local breadth = b

   if type == 'Rect' then
      return length * breadth
   end
end

-- calculate area of rectangle with length as 2, width as 4
print('Area of Rectangle', calculateArea('Rect', 2, 4))

输出

运行上述代码时,将得到以下输出——

Area of Rectangle	8

现在如果想使用像下面的命名参数——

function calculateArea(type, length, breadth)

并以如下方式调用函数——

print('Area of Rectangle', calculateArea(type='Rect', length=2, width=4))

那么 Lua 中没有直接支持这种方式。但是使用 table 可以实现相同的效果。请看下面的示例:

使用位置参数

我们可以定义一个 table,其中包含所有位置参数。

arguments = { type='Rect', length=2, width=4 }

然后将这个 table 作为参数传递给函数。

function calculateArea(arguments)
   local length = arguments.length
   local breadth = arguments.breadth

   if arguments.type == 'Rect' then
      return length * breadth
   end
end

位置参数的完整示例

main.lua

-- function to calculate area of a shape passed
function calculateArea(arguments)
   local length = arguments.length
   local breadth = arguments.breadth

   if arguments.type == 'Rect' then
      return length * breadth
   end
end

-- calculate area of rectangle with length as 2, width as 4
print('Area of Rectangle', calculateArea({type='Rect', length=2, breadth=4}))

输出

运行上述代码时,将得到以下输出——

Area of Rectangle	8