string 检查 Lua 中的字符串是否为 nil 或空
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19664666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Check if a string isn't nil or empty in Lua
提问by Uskiver
I've some currently some Lua code using the following syntax:
我目前有一些使用以下语法的 Lua 代码:
if (foo == nil or foo == '') then
foo = "some default value"
end
The goal of the if condition is to test foo is neither an empty string, neither a nil value.
if 条件的目标是测试 foo 既不是空字符串,也不是 nil 值。
Can this code be simplified in one if test instead two?
如果测试而不是两个,这段代码可以简化为一个吗?
回答by hugomg
One simple thing you could do is abstract the test inside a function.
您可以做的一件简单的事情是在函数中抽象测试。
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
回答by Mud
Can this code be simplified in one if test instead two?
如果测试而不是两个,这段代码可以简化为一个吗?
nil
and ''
are different values. If you need to test that s
is neither, IMO you should just compare against both, because it makes your intent the most clear.
nil
并且''
是不同的值。如果您需要测试s
两者都不是,IMO 您应该只与两者进行比较,因为它使您的意图最清楚。
That and a few alternatives, with their generated bytecode:
那和一些替代方案,以及它们生成的字节码:
if not foo or foo == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 0
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
if foo == nil or foo == '' then end
GETGLOBAL 0 -1 ; foo
EQ 1 0 -2 ; - nil
JMP 3 ; to 7
GETGLOBAL 0 -1 ; foo
EQ 0 0 -3 ; - ""
JMP 0 ; to 7
if (foo or '') == '' then end
GETGLOBAL 0 -1 ; foo
TEST 0 0 1
JMP 1 ; to 5
LOADK 0 -2 ; ""
EQ 0 0 -2 ; - ""
JMP 0 ; to 7
The second is fastest in Lua 5.1 and 5.2 (on my machine anyway), but difference is tiny. I'd go with the first for clarity's sake.
第二个在 Lua 5.1 和 5.2 中最快(无论如何在我的机器上),但差异很小。为了清楚起见,我会选择第一个。