Inline conditions in Lua (a == b ? “yes” : “no”)

You might have noticed ternary operators in different programming languages, but since there’s no ternary operator in Lua, as per the official documentation, we can create one for ourselves with the help of the Lua operators.

Let’s first understand what a ternary operator is and why we need one.

Example

Consider the example shown below, which depicts a simple if else condition in lua.

Live Demo

a = 3
b = 4
if a == b then print("blah")
else print("nah nah")
end

Output

nah nah

In the above if else condition, we wrote multiple lines of code and also used many statements that the lua language provides, but what if we can write the exact same logic without writing multiple lines of code, and using less statements.

Example

It is possible to write the same exact logic of code in a single line. Consider the example shown below −

Live Demo

print("Yo: " .. (a == b and "blah" or "nah nah"))

Output

Yo: blah