Easy Tutorial
❮ Java Transformation Problem Home ❯

Ternary Operator in Lua

Category Programming Techniques

Ternary Operation

Veterans familiar with C/C++ know the ternary operation a ? b : c, which can replace simple conditional statements without increasing reading difficulty, keeping the code concise.

int a, b, ret;
//if-else
if (a > b)
    ret = a;
else
    ret = b;

//Ternary operator
ret = a > b ? a : b;

Ternary Operator in Lua

Lua's native semantics do not implement the ternary operator; it is usually simulated using logical operators and and or.

Both and and or in Lua use "short-circuit evaluation," meaning they only evaluate the second operand when necessary. (“Programming in Lua”)

local a, b, ret;
ret = a > b and a or b

Enumerating all possibilities:

When a > b:

a > b and a –> true 
a or b –> a

When a <= b:

a > b and a –> false 
a or b –> b

Perfect!

Pitfalls of the Ternary Operator in Lua

Following the principle from special to general:

It can be seen that when b = false, the Lua simulation of a and b or c always returns c and cannot restore the original form of the ternary operator.

“Programming in Lua” also suggests using if-else to avoid this situation.

Generalized a and b or c

Is there a way to solve the problem of b = false failing?

This made me think of a common exam question in C: Please use a macro to write a method that returns the smaller of two values.

When I first saw this question at school, my first reaction was:

#define MIN(A,B) A < B ? A : B

However, this writing often does not return the correct result in many nested usage environments. For example: 2 * MIN(3, 4) expands to 2 * 3 < 4 ? 3 : 4 = 6 < 4 ? 3 : 4, result is 4.

#define MIN(A,B) ((A) < (B) ? (A) : (B))

Curious students can refer to Macro Definition: Correct Writing of Macro Definition, Macro Definition of Ternary Operation

From this example, I wondered how to ensure that b in a and b or c is true or b does not create ambiguity?

Conclusion

Indeed, to know the form of the ternary operation in Lua, one can simply search to find the desired answer. The above reasoning process may seem a bit like knowing the answer and deliberately leaning towards it. However, I firmly believe that when proving a problem, the conclusion is not the most important; what matters is the process of argumentation. This article merely attempts to restore the derivation process of a generalized Lua ternary operation based on my superficial understanding of Lua. If there are better reasoning processes, we can exchange ideas.

Source: https://blog.csdn.net/u010832643/article/details/77546887

❮ Java Transformation Problem Home ❯