How to check if a value is empty in Lua?

conditional-statements, lua

Solution

Lua is a dynamically type-based language. Any variable can hold one of the following types: nil, boolean, number, string, table, function, thread, or userdata. Any variable in a table (including `_G`, the table where globals reside) without a value gives a value of `nil` when indexed. When you set a table variable to `nil`, it essentially "undeclares" it (removing the entry from memory entirely). When a `local` variable is declared, if it is not assigned immediately it is given a value of `nil`. Unlike table variable, when you set a `local` variable to `nil`, it does not "undeclare" it (it just has a value of `nil`).

In Lua, an empty string (`""`) is still a "value" - it's simply a string of size zero.

Problem

What is the proper way to make a conditional which checks of something is or is not empty in Lua? `if x == ""` and `f x ~= ""` does not seem to work.

Original source