Skip to main content
Inspiring
February 3, 2024
Answered

How to deal with nil values in variables and concatenation them

  • February 3, 2024
  • 2 replies
  • 453 views

I have some checkboxes that represents options for executing an external program.

some pseudo code:

if box == checked

 strOption1 = aa

if box 2 == checked

  strOption2 == bb

strCommand = "software " .. strOption1 .. " " ..  strOption2

------

But if the strOption(s) are empty (nil) I get an error.
I could the write some if else but that would make it more complicated.

 

This topic has been closed for replies.
Correct answer johnrellis

Building on kimaldis' reply, in your example you'll need parentheses around the "or" expression:

strCommand = "software " .. (strOption1 or "") .. " " ..  strOption2

This will evaluate to "" if "strOption1" is nil or false, to "strOption1" otherwise.

 

More generally, the common way to approximate a conditional expression in Lua (which lacks them) is to write:

cond and x or y

which usually is "y" if "cond" is nil or false,  "x" otherwise. But you need to be very careful: if "x" is nil or false, then the value of the expression is always "y" (a different result than conditional expressions in other languages).

2 replies

Inspiring
February 3, 2024

.. StrOption1 or "" ..

johnrellis
johnrellisCorrect answer
Legend
February 3, 2024

Building on kimaldis' reply, in your example you'll need parentheses around the "or" expression:

strCommand = "software " .. (strOption1 or "") .. " " ..  strOption2

This will evaluate to "" if "strOption1" is nil or false, to "strOption1" otherwise.

 

More generally, the common way to approximate a conditional expression in Lua (which lacks them) is to write:

cond and x or y

which usually is "y" if "cond" is nil or false,  "x" otherwise. But you need to be very careful: if "x" is nil or false, then the value of the expression is always "y" (a different result than conditional expressions in other languages).

Sean McCormack
Community Expert
Community Expert
February 3, 2024

Would initialising the strings prevent this? Obviously you'd need an option for that intialising, but it could be the default choice. 

 

Sean McCormack. Author of 'Essential Development 3'. Magazine Writer. Former Official Fuji X-Photographer.