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.
Consider the example shown below, which depicts a simple if else condition in lua.
a = 3 b = 4 if a == b then print("blah") else print("nah nah") end
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.
It is possible to write the same exact logic of code in a single line. Consider the example shown below −
print("Yo: " .. (a == b and "blah" or "nah nah"))