Hello, I need a minute of Lua help. What is the syntax for optional parameters or default values. I want something equivalent to this:
function(--[[required]]var1, --[[optional]]var2, --[[optional]]var3)
if not var2 then
var2 = 6--default value
end
if not var3 then
var3 = 0 --default value
end
--Do something with the inputs
end
Is there anything more succinct than what I have there? Optional arguments or multiple function definitions seem to be a built-in feature with most of the languages I have worked with in the past, but I canât seem to find an equivalent for Lua. Maybe I am just looking in the wrong places! Thanks!
As far as I know, there is no syntax for it, but there might very well be conventions (maybe the ones you are using?) in either naming or luadoc or similar to denote this (@britzl?). To check for optionals, I think âorâ is commonly used:
function(--[[required]]var1, --[[optional]]var2, --[[optional]]var3)
var2 = var2 or 6 --default value
var3 = var3 or 0 --default value
--Do something with the inputs
end
Like @Ragnar_Svensson writes there is no mechanism in the language itself to indicate that a function parameter is optional, but there are plenty of examples in the Lua standard API where optional parameters exist and where the behaviour of a function depends on the number of arguments provided:
In your code you can assign default values using the or logical operator like in Ragnarâs example. A lot of Lua libraries use LDoc to write and automatically generate documentation, and optional arguments are documented like this:
--- Three dashes indicate the beginning of a function or field documented
-- using the LDoc format
-- @param var1 The first argument
-- @param[opt=6] var2 The second argument
-- @param[opt=0] var3 The third argument
-- @return Max The maximum value of var1 and var2
-- @return Min The minimum value of var2 and var3
function foobar(var1, var2, var3)
var2 = var2 or 6
var3 = var3 or 0
return math.max(var1, var2), math.min(var2, var3)
end
Wow, thanks for the clarification! LuaDoc is intriguing, too. I donât know if I have a use for it now, but thanks for the overview - Iâll keep it in mind! I might use the commenting conventions LDoc uses for my own modules; They remind me of pythonâs conventions, which I am familiar with. Do you guys on the Defold team adhere to a specific style-guide, or is there a proprietary one? Asking out of curiosity, as I personally have never been in industry and donât know what the norm is.
And when we design out APIs we try to follow the simple rule of âDo what Lua doesâ meaning that we try to follow the conventions set by the Lua standard libraries in terms of naming conventions, return values etc