Optional arguments

Is there any ways to make an optional arguments in Lua?

Just like in other languages:

In Python,

def func(arg="hello"):
    print(arg)

If there is no provided argument, the “hello” is automatically the default value of ‘arg’.

-- Can also specify which argument is which, I believe it's like this:
func(arg="nice")

Is that possible in Lua?

yes

function amogus(optional)
optional = optional or "default argument"
return optional
end

The “optional” would be the arg.

8 Likes

Is this possible? Or it’s not allowed in Lua?

Yes it would do that if the argument isn’t specified. I tested it.

amogus() -- "default argument"
amogus("yes") -- "yes"

You also don’t have to assign the value to a new variable, and can instead reuse the older one:

local function DoSomething(arg)
   arg = arg or "default"
   return arg
end
1 Like

Oh, I totally forgot about that, thx