6

我试图将空值传递给函数但失败了。这是我的设置;

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

我只想传递“种类”并希望构造函数处理其余部分。像;

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

或者我只想通过“howFast”;

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

我尝试了""有无,给出了错误:

',' 附近出现意外符号

4

2 回答 2

6

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

于 2013-11-03T04:07:09.600 回答
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"}
于 2013-11-03T05:50:15.080 回答