John Lardinois
John Lardinois

Reputation: 109

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.

Upvotes: 2

Views: 4729

Answers (2)

user6767685
user6767685

Reputation:

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

Upvotes: 1

John Lardinois
John Lardinois

Reputation: 109

Okay, apparently I AM a total Lua Noob / spoiled C++ Python guy.

Lua doesn't allow that. Instead, inside of the init or constructor, put:

argument = argument or defaultValue

As in,

function Animator:init(statictilesize)
    statictilesize = statictilesize or true
    self.isTileSizeStatic = statictilesize
    -- Yikes
end

Edit: I found a more stable solution, given that I require more arguments after the first.

function Animator:init(booleanstatictilesize, totalanimationstates, totalanimationframes)

    if booleanstatictilesize ~= false then
      self.isTileSizeStatic = true
    else
      self.isTileSizeStatic = false
    end

end

Sort of hacked together type casting / checking. I could be wrong, I'm a noob at all this. I never had a formal programming education. I might sound like a total idiot.

Upvotes: 3

Related Questions