LoginSignup
16
18

More than 5 years have passed since last update.

MoonScriptしようや...

Posted at

MoonScript!?

image
AltJSよろしく、AltLuaな
Luaへの言語トランスレータです。

環境構築

luarocksでの環境構築が必須です。
Mac OSであり、homebrewの環境構築が済んでいるなら
以下のコマンドでインストール可能ですm(_ _)m

> brew install luarocks

moonscriptインストール

luarocksをインストールした状態で、
moonscriptをインストールしましょう。

必要そうなやつ全部入れてしまう。(luarocksよくわからんな...)

> luarocks install luasocket
> luarocks install lapis
> luarocks install lpeg
> luarocks install moonscript

これでmoonコマンドが使えるようになりました。

moonscriptをお試し

リスト内包表記

リスト内包表記(List Comprehensions)が使えます

コード例

odd.moon
data = {1,2,3,4,5,6,7,8,9,10}
odd = [v for i, v in ipairs(data) when i % 2 != 0]

for i, v in ipairs(odd)
  print(v)

実行結果

> moon odd.moon
1
3
5
7
9

switch構文

Switch構文を使うことができます。
(評価結果がSwitchのブロックから戻ってくるようになる)

コード例

switch.moon
type = "Hello world"

message = switch type
  when "Hello world"
    "Welcome!"
  when "Welcome to underground"
    "Go to hell..."
  else
    "????"

print message

実行結果

> moon switch.moon
Welcome!

class表現

Luaそのものだと擬似クラス表現になりますが、
MoonScriptではclass構文を使えます。

コード例

class.moon
class Bucket
  new: =>
    @box = {}

  inc: (item) =>
    if @box[item]
      @box[item] += 1
    else
      @box[item] = 1

  count: (item) =>
    @box[item]

bucket = Bucket!
bucket\inc "hoge"
bucket\inc "hoge"
bucket\inc "fuga"

print bucket\count "hoge"
print bucket\count "fuga"

実行結果

> moon class.moon
2
1

なお、
@がインスタンス自身(self)で
@@がクラス(self.class)に当たる。

全体的に

endが省略可能だったり、forのdoが省略できたりする。
組み込み向けスクリプティング用途ではなく、
Webアプリケーションを書くための用途、つまるところ
Lua単体でアプリを提供する場合に使うと良いのではと思う。

参考

MoonScript - Language Guide

16
18
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
16
18