Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass empty variables to a function in Lua

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 ','

like image 503
cbt Avatar asked Nov 03 '13 04:11

cbt


1 Answers

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.

like image 72
Yu Hao Avatar answered Oct 13 '22 11:10

Yu Hao