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 ','
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With