7

I've tried to pass empty values to a function but failed. Here is my setup;

function gameBonus.new( x, y, kind, howFast )   -- constructor
    local newgameBonus = {
        x = x or 0,
        y = y or 0,
        kind = kind or "no kind",
        howFast = howFast or "no speed"
    }
    return setmetatable( newgameBonus, gameBonus_mt )
end

I want only to pass "kind" and want the constructor to handle the rest. Like;

 local dog3 = dog.new("" ,"" , "bonus","" )

Or I want only to pass "howFast";

 local dog3 = dog.new( , , , "faster")

I tried both with "" and without, gives error:

unexpected symbol near ','

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
cbt
  • 1,271
  • 1
  • 11
  • 20

2 Answers2

6

nil is the type and value to represent empty in Lua, so instead of passing an empty string "" or nothing, you should pass nil like this:

local dog3 = dog.new(nil ,nil , "bonus", nil )

Note that the last nil can be omitted.

Take the first parameter x as an example, the expression

x = x or 0

is equivalent to:

if not x then x = 0 end

That is, if x is neither false nor nil, sets x with the default value 0.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
1
function gameBonus.new( x, y, kind, howFast )   -- constructor
  local newgameBonus = type(x) ~= 'table' and 
    {x=x, y=y, kind=kind, howFast=howFast} or x
  newgameBonus.x = newgameBonus.x or 0
  newgameBonus.y = newgameBonus.y or 0
  newgameBonus.kind = newgameBonus.kind or "no kind"
  newgameBonus.howFast = newgameBonus.howFast or "no speed"
  return setmetatable( newgameBonus, gameBonus_mt )
end

-- Usage examples
local dog1 = dog.new(nil, nil, "bonus", nil)
local dog2 = dog.new{kind = "bonus"}
local dog3 = dog.new{howFast = "faster"}
Egor Skriptunoff
  • 23,359
  • 2
  • 34
  • 64