Thread Tools Display Modes
07-11-14, 06:49 PM   #1
ArithEU
A Kobold Labourer
 
ArithEU's Avatar
Join Date: Mar 2012
Posts: 1
Lua: null coalescing ??

Hey there

I'm very inexperienced with Lua (I'm a C# developer) and I was wondering if there's a null coalescing operator I could use to handle any null/empty strings?

for example in C# I would do
Code:
string a = b ?? c;
which would give a the value of c if b was null.

Last edited by ArithEU : 07-11-14 at 07:00 PM. Reason: un-capitalising "Lua"
  Reply With Quote
07-11-14, 06:59 PM   #2
TOM_RUS
A Warpwood Thunder Caller
AddOn Author - Click to view addons
Join Date: Sep 2008
Posts: 95
Something like this:
Lua Code:
  1. local a = nil
  2. local b = "123"
  3. local c = a or b
  4. print(c)
should assign "123" to c.

But if a is "", then it won't work.
  Reply With Quote
07-11-14, 07:29 PM   #3
semlar
A Pyroguard Emberseer
 
semlar's Avatar
AddOn Author - Click to view addons
Join Date: Sep 2007
Posts: 1,060
If you want to check that the variable both exists and is not an empty string, you could do something like this
Lua Code:
  1. local a = (b and b ~= '') and b or c
This is called short-circuiting and it stops when the condition evaluates to true.

The above is equivalent to writing
Lua Code:
  1. local a
  2. if b and b ~= '' then
  3.   a = b
  4. else
  5.   a = c
  6. end
  Reply With Quote
07-11-14, 08:15 PM   #4
Phanx
Cat.
 
Phanx's Avatar
AddOn Author - Click to view addons
Join Date: Mar 2006
Posts: 5,617
Also, for the purposes of simple "if x then" checks in Lua, a value of false is the same as "not existing" or having a value of nil.

Code:
a = b or c
... is the same as:

Code:
a = (b ~= nil and b ~= false) and b or c
... which is the same as :

Code:
if b ~= nil and b ~= false then
    a = b
else
    a = c
end
... so if you need to distinguish between a boolean false and an actual nil value, you'll have to explicitly check.
__________________
Retired author of too many addons.
Message me if you're interested in taking over one of my addons.
Don’t message me about addon bugs or programming questions.
  Reply With Quote

WoWInterface » Developer Discussions » Lua/XML Help » LUA: null coalescing ??


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off