functionparametersluadefault-valueexpected-exception

Lua, setting default function parameter values. This can't be wrong?


Eclipse is telling me that ')' is expected near '=', but surely that can't be right? This is my code:

Animator = Class{}

function Animator:init(statictilesize = true)

    self.isTileSizeStatic = statictilesize

end

I'm so confused. I've only been using Lua for a month though, I'm more of a C++ / C# / Python guy. Maybe I'm missing something.


Solution

  • Typically what seems to be done is to define your function like normal, and if the variables you want to be optional aren't set, you set them later, and redefine your function signature to look for a table:

    Animator = Class{}
    
    function Animator:init(args)
        self.isTileSizeStatic = args.statictilesize ~= false
    end
    

    Later you call this function with this form of syntax:

    Animator.init{statictilesize = false}
    

    Both nil and false are the "falsey" conditions in Lua. All other conditions in Lua are truthy, including 0 and ''. So in order to get the functionality that when statictilesize is unset, it defaults to a true condition, you must check its inequality to false, as everything else will be true (including nil since nil is not false).

    Please note that this would implicitly convert your argument into a bool

    It's quite a bit different from Python.

    See here for more details:

    https://www.lua.org/pil/5.3.html

    Additionally, if you want false to be part of the acceptable set of arguments passed to the function (or you simply don't want the argument implicitly converted to boolean) you can use the following syntax:

    function Animator:init(args)
        if args.statictilesize ~= nil then self.isTileSizeStatic = args.statictilesize else self.isTileSizeStatic = true end
    end