Village
Village

Reputation: 24373

How to check if a value is empty in Lua?

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.

Upvotes: 22

Views: 59354

Answers (4)

Scott
Scott

Reputation: 1119

I'm going to make an assumption that the OP means "how do you tell when a variable is unassigned".

Example:

local x

The variable x is "empty", it is initialized to "nil". (Not the text "nil", but an enumerated value that indicates that the variable is unassigned. In Lua that is defined as nil, in some other languages it is defined as NULL.)

Now assign x a value. Example:

x=""

Now x is not nil. Another example:

x=0

x is not nil.

Try running this code, it should make the situation clear to you.

local x
if x==nil then print("x is nil") end

x=0
if x==nil then print( "This line won't be written") end

x=""
if x==nil then print( "and this line won't be written") end

The first if statement will evaulate to true and the print statement will be called. The 2nd and 3rd if statements are false and the print statements will not be executed.

In conclusion, use "==nil" to check to see if a variable is "empty" (which is more properly said "nil").

Upvotes: 7

When1ConsumeMem
When1ConsumeMem

Reputation: 74

I recently ran across this problem as well. LuaSQL was returning empty strings if a database value was 'blank' (not null). A hacky approach, but here's how I solved it:

if (string.len(x) >= 1) then
    ...
end

Upvotes: 5

kikito
kikito

Reputation: 52641

You probably have spaces, newlines or other non-visible characters in your string. So you think it is "empty", but it isn't. This typically happens when you are taking input from the user, and has to type "enter" to finish - the "enter" ends up in the string.

What you need is a function that tells you whether the string is "blank" - either empty, or a list of spaces/tabs/newlines. Here's one way to do it:

function isBlank(x)
  return not not tostring(x):find("^%s*$")
end

Usage:

if isBlank(x) then
  -- ...
end

Upvotes: 1

Deco
Deco

Reputation: 5149

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.

Upvotes: 19

Related Questions