如何跳过Lua中的可选参数?

时间:2011-08-20 12:37:15

标签: lua optional-parameters

我一直在调用一种方法:

t1, t2 = LSL:GetDiffItem(item)

将方法声明为:

GetDiffID(item, ignoreEnchant, ignoreGem, red, yellow, blue, meta, ignorePris)

现在我想传递其他参数,跳过一些:

项目 ignoreEnchant ignoreGem 红色黄色 blue meta ignorePris

我尝试跳过参数:

t1, t2 = LSL:GetDiffItem(item, ignore, ignore, , , , , ignore)

但当然这不起作用:

  

','附近的意外符号

那么,如何跳过Lua中的可选参数?


另见

4 个答案:

答案 0 :(得分:6)

通过nil。这将与从未通过参数相同。但是,请注意文档声明可以执行此操作,因为大多数函数不会检查每个可选参数,只检查每个参数是否提供了上一个参数。

答案 1 :(得分:0)

如果您正在编写自己的函数(而不是使用预先存在的API),我使用的方法是将表作为唯一参数传递给函数,并在该表中填入适当的值。在函数的第一步中分配带有默认值的元表避免在每一步查找默认值,但要确保用户知道您在输入时覆盖了元表。

答案 2 :(得分:0)

使用nil

请注意,当C代码使用gettop时,这不起作用,或者依赖于'NONE',例如在类型上的switch / case中,或者明确检查none或nil而不是lua_isnoneornil。< / p>

答案 3 :(得分:0)

您可以使用Named Arguments。 正如在lua.org上所说:&#34;当函数有许多参数时,这种参数传递方式特别有用,而且大多数都是可选的。 &#34;

我们的想法是将所有参数作为表传递:

function InfoItem(item)
  if item.name then
    print("Name: ",item.name)
  end
  if item.color then
    print("Color: ",item.color)
  end
  if item.enchant then
    print("Enchant: ",item.enchant)
  end
  if item.specialInfo then
    print(item.specialInfo)
  end
end

InfoItem{name = "Internet Troll's Bane", color = "silver"}
InfoItem{name = "Death's Toenail Clipper", enchant = "unbreakable", specialInfo = "Little effort required to cut through the thickest nails."}