2013-11-03 25 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"}