Lua は、アプリケーション拡張のために設計された、強力で高速、軽量かつ組み込み可能なスクリプト言語です。
基本構文
コメント
-- 1行コメント
--[[
複数行コメント
--]]
関数呼び出しの括弧省略
関数が単一の文字列リテラルまたはテーブルコンストラクタのみを引数に取る場合、括弧を省略できます:
print("Hello World") <==> print "Hello World"
dofile('app.lua') <==> dofile 'app.lua'
config({ x = 1 }) <==> config{ x = 1 }
テーブルと配列
テーブルは Lua における唯一のデータ構造です。配列は 1 から始まるインデックス (1-based) を使用します:
-- 空のテーブル
local t = {}
-- キー・バリュー形式のテーブル (辞書)
local user = { name = "Alice", age = 30 }
user.role = "admin"
user["email"] = "[email protected]"
-- 配列 (1始まりのインデックス)
local fruits = { "apple", "banana", "cherry" }
print(fruits[1]) -- "apple" を出力
print(#fruits) -- 長さ取得演算子 (3)
制御構文とループ
条件分岐
Lua で偽 (falsy) とみなされるのは false と nil のみです。0 や "" は 真 (truthy) として扱われます:
if score >= 90 then
grade = "A"
elseif score >= 80 then
grade = "B"
else
grade = "C"
end
ループ
-- While ループ
local count = 1
while count <= 5 do
count = count + 1
end
-- Repeat...until ループ (最低1回は実行される)
repeat
count = count - 1
until count == 0
-- 数値 for ループ: for var = start, stop [, step]
for i = 1, 10, 2 do
print(i) -- 1, 3, 5, 7, 9
end
-- 汎用 for ループ: ipairs (配列順) と pairs (辞書順)
for index, value in ipairs(fruits) do
print(index, value)
end
for key, value in pairs(user) do
print(key, value)
end
関数
関数定義と多値返却
-- 複数の値を返す
local function min_max(a, b)
if a < b then
return a, b
else
return b, a
end
end
local minimum, maximum = min_max(10, 5)
-- 可変長引数 (varargs)
local function sum(...)
local s = 0
for _, v in ipairs({...}) do
s = s + v
end
return s
end
メタテーブルとオブジェクト指向
メタテーブルとメタメソッド
local Vector = {}
Vector.__index = Vector
function Vector.new(x, y)
local instance = setmetatable({}, Vector)
instance.x = x
instance.y = y
return instance
end
-- ベクトル加算用メタメソッド
function Vector.__add(a, b)
return Vector.new(a.x + b.x, a.y + b.y)
end
function Vector:__tostring()
return string.format("(%d, %d)", self.x, self.y)
end
local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
local v3 = v1 + v2
print(v3) -- "(4, 6)"
メタメソッド一覧
| メタメソッド | 呼び出しトリガー |
|---|---|
__index |
存在しないキーの読み込み (t[k]) |
__newindex |
存在しないキーへの代入 (t[k] = v) |
__tostring |
文字列への変換 (tostring(t)) |
__call |
テーブルを関数として実行 (t()) |
__add, __sub |
加算 (+)、減算 (-) |
__mul, __div |
乗算 (*)、除算 (/) |
__eq, __lt, __le |
比較演算 (==, <, <=) |
__concat |
文字列結合 (..) |
標準ライブラリ API
文字列関数
string.len("hello") -- 5 (#"hello" also works)
string.lower("HELLO") -- "hello"
string.upper("hello") -- "HELLO"
string.sub("hello", 2, 4) -- "ell"
string.format("%s = %d", "x", 5)-- "x = 5"
string.gsub("banana", "a", "o") -- "bonono"
string.find("hello world", "wor") -- 7, 9
テーブル関数
table.insert(fruits, "orange") -- 末尾に追加
table.insert(fruits, 1, "grape") -- インデックス 1 に挿入
table.remove(fruits, 1) -- 最初の要素を削除
table.concat(fruits, ", ") -- 文字列連結: "apple, banana"
table.sort(fruits) -- 配列をインプレースソート
数学関数
math.abs(-10) -- 10
math.floor(3.7) -- 3
math.ceil(3.2) -- 4
math.max(1, 9, 4) -- 9
math.random(1, 100) -- 1から100までの乱数整数