目次
Luaのデータ型
Luaには8つのデータ型があります。
| 型 | 説明 |
|---|---|
| nil(ニル) | 値なし 他の言語でのnullに相当。グローバル変数にnilを代入すると、その変数はメモリから削除されます。 |
| boolean | 真偽値(trueまたはfalse) Luaではnilとfalseのみが偽。0や空文字列は真として扱われます。 |
| number | 数値 整数・浮動小数点を区別せず1つの型(Lua5.3以降は内部的にintegerとfloatに分離)。 |
| string | 文字列 文字列は不変(イミュータブル)です。一度作成した文字列の一部だけを書き換えることはできず、変更する場合は新しい文字列を作成します。 |
| table | 配列・連想配列 配列・辞書・オブジェクトすべてをこれで表現します。 |
| function | 関数 第一級オブジェクトとして扱えます。 |
| userdata | C言語用データ ライブラリ開発などで使用。 userdataはCライブラリ経由で生成されるため、Lua単体では直接生成できません。 |
| thread | コルーチン 明示的にyield/resumeで切り替える協調的な仕組みに使用。 |
nil(ニル)
local x = nil
boolean
local flag = true
number
local n = 42
local f = 3.14
local h = 0xFF -- 16進数
string
local s = "hello"
local s2 = 'world'
local s3 = [[複数行
文字列]]
シングル・ダブルクォートどちらも使用可。
table
local arr = {10, 20, 30} -- 配列(インデックスは1始まり)
local dict = {name="Lua", ver=5} -- 辞書
function
local add = function(a, b) return a + b end
userdata
-- 例: io.open()の戻り値など
local f = io.open("test.txt", "r")
print(type(f)) -- file (userdataの一種)
thread
local co = coroutine.create(function()
coroutine.yield()
end)
データ型を調べる
type()でデータ型を確認できます。
print(type(nil)) -- nil
print(type(true)) -- boolean
print(type(42)) -- number
print(type("hello")) -- string
print(type({})) -- table
print(type(print)) -- function
type()は常に文字列を返します。
そのため、if文で=="number"のように比較できます。
※numberは、整数・小数の区別はできません(Lua 5.3以降でも基本は "number")。
print(type(1)) -- "number"
print(type(1.5)) -- "number"
math.typeで整数・小数の区別ができます。
local x = 10
if math.type(x) == "integer" then
print("integer") -- integer
end
local y = 3.333
if math.type(y) == "float" then
print("float") -- float
end
関連の記事
