我试图将空值传递给函数但失败了.这是我的设置; 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
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")
我用“”和“没有”试过,给出了错误:
nil是在Lua中表示空的类型和值,所以不应该传递空字符串“”或者没有,你应该像这样传递nil:unexpected symbol near ‘,’
local dog3 = dog.new(nil ,nil , "bonus", nil )
注意,可以省略最后的nil.
以第一个参数x为例,表达式
x = x or 0
相当于:
if not x then x = 0 end
也就是说,如果x既不是假也不是nil,则将x设置为默认值0.