[英]In Lua, how to set a nil parameter to some default value correctly?
For Lua code below:对于下面的 Lua 代码:
local function foo(x, y, z)
local x = x or true
local y = y or 1234
z = z or "default"
end
I always thought the meaning of these three lines inside the function is:一直以为函数里面这三行的意思是:
If x/y/z is nil, x/y/z is set to true/1234/"default".如果 x/y/z 为零,则 x/y/z 设置为 true/1234/“默认”。 Otherwise, it remains whatever it is.
否则,它保持原样。 Therefore, I have such a line in many places to set a parameter to some default value in case it might be passed into a function as nil.
因此,我在很多地方都有这样的一行来将参数设置为某个默认值,以防它可能作为 nil 传递到函数中。
However, it seems not totally correct in my experiments.但是,在我的实验中似乎并不完全正确。 I am not sure where I learnt this Lua coding concept.
我不确定我从哪里学到了这个 Lua 编码概念。 How to do it correctly?
如何正确地做到这一点?
The method will work as long as your boolean(?) variable x
was not initialised as false
.只要您的 boolean(?) 变量
x
未初始化为false
该方法就会起作用。 If you only want to use defaults against nil
values, the a or b
method is correct.如果您只想对
nil
值使用默认值,则a or b
方法是正确的。
If your variable can be false
, you'd have to use a strict if-then block:如果您的变量可以为
false
,则必须使用严格的 if-then 块:
if x == nil then x = true end
You can see a few more methods/examples about ternary operators on lua wiki .您可以在lua wiki上看到更多关于三元运算符的方法/示例。
There exists one more strict method if you want to be able pass nil
as argument(eg you want distinguish foo(1,2,nil)
and foo(1,2)
)如果您希望能够将
nil
作为参数传递,则存在一种更严格的方法(例如,您想区分foo(1,2,nil)
和foo(1,2)
)
function foo(...)
local n,x,y,z = select('#', ...), ...
if n < 3 then z = default end
if n < 2 then y = default end
if n < 1 then x = default end
-- here x,y or z can be nil
...
end
But you have to be shure you know what you doing because it may be not expected behavior for users of your function.但是您必须确保您知道自己在做什么,因为对于您的函数的用户来说,这可能不是预期的行为。
This should work as expected:这应该按预期工作:
function foo(x, y, z)
x = (x == nil) or x
y = (y == nil and 1234) or y
z = (z == nil and "default") or z
print(x, y, z)
end
> foo()
true 1234 default
> foo(false, false, "me")
false false me
> foo(nil, 50, "me")
true 50 me
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.