I've some currently some Lua code using the following syntax:
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.
Can this code be simplified in one if test instead two?
In Lua - '' == true , nil == false .
To check wether a value is a string use type(value) == "string" . To check wether a value can be convertet do a number use tonumber(value) . It will either return a number or nil.
The following example shows the different meaning of nil and NULL in the context of Lua when reading a resultset: NULL means that the Value read from the database is NULL. nil means that the referenced column doesn't exist.
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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With