Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

string

lua

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?

like image 742
Uskiver Avatar asked Oct 29 '13 17:10

Uskiver


People also ask

How do you check nil in Lua?

In Lua - '' == true , nil == false .

How do you check if a value is a string Lua?

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.

Is null in Lua?

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.


2 Answers

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
like image 132
hugomg Avatar answered Oct 04 '22 14:10

hugomg


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.

like image 30
Mud Avatar answered Oct 04 '22 15:10

Mud