Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

lua overload: possibilities?

My group is currently working with Lua,creating an android game. One thing we've run into is the appearant inability to create overload constructors.

I'm used to having an object set up with default values, that then get overloaded if need be.

ex:

apples()
{
    taste="yum";
    amount = 0;

}

apples(string taste, int num)
{
    taste=taste;
    amount=num;

}

However, with the inability to do that, we have these lare if/else sections for initialization that look like this

if velX ~= nil then
    self.velX = velX
else
    self.velX = 0
end

if velY ~= nil then
    self.velY = velY
else
    self.velY = 0
end

Is there a better way to set this up in Lua?

like image 742
Drew L. Facchiano Avatar asked Dec 12 '22 13:12

Drew L. Facchiano


1 Answers

Instead of using if/else statements, you can initialize your variables with a condition providing the default value.

function apples(taste, num)
  taste = taste or "yum"
  amount = num or 0
  -- ...
end

Lua's or operator evaluates and returns its first operand unless it is nil or false, otherwise it evaluates and returns its second operand. That leads to the above idiom for default values.

like image 80
WuTangTan Avatar answered Jan 25 '23 19:01

WuTangTan