2013-11-03 58 views
5

我試圖將空值傳遞給函數,但失敗。這是我的設置;如何將空變量傳遞給函數Lua

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 

我只想傳遞「kind」並希望構造函數處理其餘部分。喜歡;

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

或者我只想通過「howFast」;

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

我都與""並沒有嘗試過,給人的錯誤:

unexpected symbol near ','

回答

5

nil是類型和值在Lua代表空的,所以不是傳遞一個空字符串""或沒有,你應該通過nil這樣的:

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

注意最後nil可以省略。

取第一參數x作爲一個例子,所述表達

x = x or 0 

相當於:

if not x then x = 0 end 

也就是說,如果x既不false也不nil,設置x與默認值0

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"}