简体   繁体   English

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

[英]How to skip optional parameters in Lua?

There is a method I have been calling: 我一直在调用一种方法:

t1, t2 = LSL:GetDiffItem(item)

where the method is declared as: 方法声明为:

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

Now I want to pass additional parameters, skipping some: 现在我想传递其他参数,跳过一些:

item , ignoreEnchant , ignoreGem , red , yellow , blue , meta , ignorePris 项目 ,ignoreEnchant,ignoreGem, ,ignorePris

I tried just skipping the parameters: 我试着跳过参数:

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

But of course that doesn't work: 但当然这不起作用:

unexpected symbol near ',' '附近的意外符号'

So, how do I skip optional parameters in Lua? 那么, 如何跳过Lua中的可选参数?


See also 也可以看看

Pass nil . 通过nil This will be identical to not ever having passed the parameter. 这将与从未通过参数相同。 However, be aware that the documentation states that you can do this, because most functions will not check each individual optional parameter, and only check each parameter if the previous one was provided. 但是,请注意文档声明可以执行此操作,因为大多数函数不会检查每个单独的可选参数,并且只检查每个参数是否提供了前一个参数。

You could use Named Arguments . 您可以使用命名参数 As said on lua.org: "This style of parameter passing is especially helpful when the function has many parameters, and most of them are optional. " 正如lua.org上所说:“当函数有许多参数时,这种参数传递方式特别有用,而且大多数参数都是可选的。”

The idea is to pass all arguments as a table: 想法是将所有参数作为表传递:

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."}

If you're writing your own functions (rather than using a preexisting API), the method I've used is to pass a table as the only parameter to the function, and fill in the appropriate values in that table. 如果您正在编写自己的函数(而不是使用预先存在的API),我使用的方法是将表作为唯一参数传递给函数,并在该表中填入适当的值。 Assigning a metatable with the defaults as the first step in your function avoids looking up defaults at each step, but make sure users know you are overwriting the metatable on their input. 在函数的第一步中分配带有默认值的元表避免在每一步查找默认值,但要确保用户知道您在输入时覆盖了元表。

Use nil . 使用nil

note that this won't work when the C code uses gettop, or relys on 'NONE' such as in a switch/case on the type, or explicity checking for none or nil instead of lua_isnoneornil . 请注意,当C代码使用gettop时,这将不起作用,或者依赖于'NONE',例如在类型上的switch / case中,或者明确检查none或nil而不是lua_isnoneornil

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM