Lua - Check String is Null or Empty



In Lua, we can check a String as empty or Null/Nil in multiple ways.

  • Using string.len(str) method− Using string.len() method, we can pass the string as argument and get the required length. If length is zero, then string is empty.

  • Using == operator− We can compare a string with '' to check if it is empty.

  • Using Nil Check− We can compare a string with Nil using == operator to check if it is empty.

Following examples are showing above checks.

Example - string.len() method

An example of using string.len method is shown below.

main.lua

-- text is nil

-- we can check length of string
if not text or string.len(text) == 0
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

-- text is empty
text = ''

if not text or string.len(text) == 0
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

-- text is mot empty
text = 'ABC'

if not text or string.len(text) == 0
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

Output

When we run the above program, we will get the following output−

nil	is empty.
	is empty.
ABC	is not empty.

Example - Using == operator

An example of using == operator is shown below.

main.lua

-- text is nil

-- check if string is empty
if text == ''
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

text = ''

-- empty string 
if text == ''
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

text = 'ABC'

if text == ''
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

Output

When we run the above program, we will get the following output−

nil	is empty.
	is empty.
ABC	is not empty.

Example - Nil Check

An example of using string.len method is shown below.

main.lua

-- text is nil

-- check if string is nil or empty
if text == nil or text == ''
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

text = ''

-- nil or empty string is considered as true
if not text or text == ''
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

text = 'ABC'

if not text or text == ''
then
   print(text,"is empty.")
else
   print(text,"is not empty.")
end

Output

When we run the above program, we will get the following output−

nil	is empty.
	is empty.
ABC	is not empty.
Advertisements