Check if a string isn't nil or empty in Lua

Uskiver picture Uskiver · Oct 29, 2013 · Viewed 132.1k times · Source

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?

Answer

hugomg picture hugomg · Oct 29, 2013

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