开发者

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

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?


See also

  • lua.org - 5.3 - Named Arguments "arguments are positional"


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

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

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜