LoginSignup
2
1

More than 5 years have passed since last update.

Luaをサクッと

Posted at

Luaという拡張プログラミング言語を知ったので、とりあえずどんな書き方するのかなと思い
まずサクッとLuaを動く環境を作成。
※本当にただ動かすだけですww

Luaとは

オブジェクト指向プログラミング、関数型プログラミング、データ駆動型プログラミングもサポートしている。
拡張言語であるため、Luaは「メイン」プログラムを持たない。 ホストクライアント (エンベッディングプログラム、あるいは単にホスト とも呼ぶ) に 組み込まれて 動くだけである。

ふむふむ。軽量で高速でC言語のホストプログラムに組み込まれる目的なわけか〜。
文法的で面白いのは、関数を変数として扱えるのか〜、ふむふむ。

まあとりあえずで、

環境: macOS

Luaをインストール&ヴァージョン確認

$ brew install lua
$ lua -v
Lua 5.3.4  Copyright (C) 1994-2017 Lua.org, PUC-Rio

LuaRocksをインストール

LuaRocksは、パッケージマネージャの1つ。
インストールした後、ホームディレクトリにモジュール等がインストールされるディレクトリを作成。

$ brew install luarocks
$ mkdir ~/.luarocks

ライブラリをインストール

CJSON: JSONを扱うライブラリである
LuaFileSystem: ファイルシステムを扱う

$ luarocks install --local lua-cjson
$ luarocks install --local luafilesystem

test.luaを作成

local json = require 'cjson'
local lfs = require 'lfs'
local doc_path = "./"
local result
local file
local text
local val
for filename in lfs.dir(doc_path) do
    result =  string.find(filename,"^.*json$")
    if result ~= nill then
        file = io.open(filename,"r");
        io.input(file);
        text = io.read()
        val = json.decode(text)
        io.close(file)
    end
end

print("from JSON File...." ..val.sample)

helloworld.jsonを作成

{ "sample":"Hello World!!!!"}

実行

$ lua ./test.lua

構成はこんなかんじになった(当たり前だけどw)

├── bin
│   ├── json2lua
│   └── lua2json
├── helloworld.json
├── lib
│   ├── lua
│   │   └── 5.3
│   └── luarocks
│       └── rocks-5.3
├── share
│   └── lua
│       └── 5.3
└── test.lua

出力

from JSON File....Hello World!!!!

参考:
http://milkpot.sakura.ne.jp/lua/lua51_manual_ja.html#1
https://dev.classmethod.jp/server-side/language/installation_of_lua/

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