59
votes

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?

2
So, what are You testing exactly foo, bar or foo.bar? If You'd have foo.bar, You could have some function like local function test(foo, bar) { if (foo.bar == nil or foo.bar == '') then foo.bar = "some default value" end end which would do the trick. - Kamiccolo
foo = foo or "some default value" - doog abides
Assuming you don't want foo of 'false' to count either you could use if (not foo) or (foo == '') then ... but otherwise that's as short as it gets. - Etan Reisner
@doog abides, won't work. In Lua - '' == true, nil == false. - Kamiccolo
foo = (foo or '')=='' and 'default value' or foo - Egor Skriptunoff

2 Answers

77
votes

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
17
votes

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.