0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

20分でまとめる備忘録 Luaで三項演算子的なものの使い方

Posted at

はじめに

if文にするほどでもない処理で何気なく三項演算子を使おうとしたところ、Luaに三項演算子はないことを知った。ただし、ほぼ三項演算子と同じ使い方のできる書き方があったのでメモしておく

書き方

c#などだと、
条件 ? "trueのときに返る値" : "falseのときに返る値";
の書き方がluaだと
条件 and "trueのときに返る値" or "falseのときに返る値"
になる

コード

local a = 10
local b = 5

local ret = a > b and a or b
print(ret)
> 10    

仕様として、以下の表のように値が決まる

論理演算子 記述例 意味
and a and b aがfalseかnilならaを返し、そうでなければbを返す
or a or b aがfalseかnil以外ならaを返し、そうでなければbを返す

はじめに a > b and a a > bはtrueなので、
true and a or ba or b aは数値でfalseではないので、 aが入る。となる

おわりに

Luaはswitch文すらないのだから、三項演算子も当然用意していない感じはある意味好感が持てる気がする。何にしろ一貫した態度は、何というか、許せる気がする。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?