I'm just learning lua, this is my first script with it. How can I check to see if a variable is empty or has something like a line feed in it?
Asked
Active
Viewed 7.8k times
19
-
An "empty" variable in Lua is a variable with the value `nil`. Maybe you are referring to an "empty string", i.e. a string with a length of 0? – Michal Kottman Feb 04 '12 at 16:58
1 Answers
31
You can check whether the value is nil:
if emptyVar == nil then
-- Some code
end
Since nil is interpreted as false, you can also write the following:
if not emptyVar then
-- Some code
end
(that is, unless you want to check boolean values ;) )
As for the linebreak: You can use the string.match function for this:
local var1, var2 = "some string", "some\nstring with linebreaks"
if string.match(var1, "\n") then print("var1 has linebreaks!") end
if string.match(var2, "\n") then print("var2 has linebreaks!") end

Henrik Ilgen
- 1,879
- 1
- 17
- 35
-
The first 2 didn't work, but last one did. Thanks. `if string.match(variable, "\n") then print("found") else print("not found")` – Anthony Kernan Feb 04 '12 at 16:32
-
3You need to understand that a variable with a line feed in it is not empty. An empty variable has nothing in it. So that is why the first two failed as I assume you tested with a variable with a line feed in. – Jane T Feb 04 '12 at 21:38