如何将空变量传递给Lua中的函数

时间:2013-11-03 04:02:28

标签: variables lua function-parameter

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

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

我尝试使用""并且没有,给出错误:

  

','

附近的意外符号

2 个答案:

答案 0 :(得分:5)

nil是在Lua中表示空的类型和值,因此您应该传递"",而不是传递空字符串nil,而不是:{/ p>}

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 :(得分: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"}