문제

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.

다른 팁

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"}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top