0
1

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 5 years have passed since last update.

Luaでも a==1 and a==2 and a==3 をtrueにしてみたい

0
Posted at

なんか流行ってますね……。

ん?

いや……

できますよ!

コード

aa = 0
setmetatable(_G, {
  __index = function(t, n)
    if n == 'a' then
      aa = (aa == 3) and 1 or (aa + 1)
      return aa
    end
  end
})

if a == 1 and a == 2 and a == 3 then
  print "True!"
end

※Lua5.1/5.2/5.3で動作確認。

解説

要するに、次のJavaScriptのコード1と同じ原理。

let aa = 0;
// 'global'はグローバルオブジェクト
Object.defineProperty(global, 'a', {
  get: function() {
    aa = (aa == 3) ? 1 : (aa + 1);
    return aa;
  }
});

if (a == 1 && a == 2 && a == 3) {
  console.log("True!");
}

Luaは次のような「JavaScriptと似た性質」を持っています。

  • Luaでは、グローバル変数とは「グローバルテーブルのキー」のことである。
  • テーブルのインデクス操作(キーに対する値を返す)はカスタマイズ可能。

これを利用して、「読み出す度に値が異なるグローバル変数a」を実現しました。

おしまい。

  1. 元ネタのStack Overflowの回答の一つにあるコードを改変したもの。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?