2016年4月14日木曜日

三項演算子です


C++では、三項演算子(ternary operator)が使えます。次のようなものです。

x = a ? b : c;

解り難いとかの批判もあるみたいですが、それは条件等が複雑な場合だけで、そうでない場合は逆に if 文よりも解りやすいと思うのですがいかがでしょう。
果たして Lua でこれを実現できるのでしょうか?
Lua のリファレンスマニュアルには次のように書かれています。

論理積演算子 and は最初の引数が falsenil であればその値を返し、そうでなければ2番目の引数を返します。 論理和演算子 or は最初の引数が nil でも false でもなければその値を返し、そうでなければ2番目の引数を返します。 andor は両方とも短絡評価を行います。 つまり2番目の引数は必要な場合にだけ評価されます。
 ~ Lua 5.3 リファレンスマニュアル - 論理演算子
The conjunction operator and returns its first argument if this value is false or nil; otherwise, and returns its second argument. The disjunction operator or returns its first argument if this value is different from nil and false; otherwise, or returns its second argument. Both and and or use short-circuit evaluation; that is, the second operand is evaluated only if necessary.
 ~ Lua 5.3 Reference Manual – Logical Operators
よって、

x = a and b or c

これで三項演算子が実現できます。ただ、慣れないうちは三項演算であることが分かり難いかもですね。
なお、C++ では数値の 0 は false と判定されますが、Lua では true と判定される点には注意してください。


0 件のコメント:

コメントを投稿