0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Luaのfor文について

Last updated at Posted at 2025-08-29

はじめに

Luaのfor文がわからなかったので僕なりにまとめてみました。
自分用につくってあるので人によってはわからないかもしれません

1. 数値for文 (決まった回数だけ繰り返す)

1から10を数える時など繰り返す回数が決まっているときなどに使える

sample.lua
for i = 1, 10 do
   print(i .. "回目のループ")
end

1.1 数値for文(指定追加)

数値for文は、第3引数で増減する数値を指定することができる。

sample.lua
-- 1, 3, 5, 7, 9
for i = 1, 10, 2 do
    print(i)
end

-- 10, 9, ... 1
for i = 10, 1, -1 do
    print(i)
end

2. 汎用for文 (リストの中身を全部取り出す)

テーブルの中身を先頭から1つずつ取り出して処理したいときに使うことができる。主にpairsipairsの2つの使い方がある

2.1 名前付きリストpairs

pairsは、{ name = "ぬる", job = "学生", age = 19 }のようにデータ名にキーが付いているテーブルに使える。取り出される順番は保証されないのが特徴

pairs.lua
local player = {
    name = "ぬる",
    job = "学生",
    age = 19
}

for key, value in pairs(player) do
    print(key .. "の中身は" .. value .. "です")
end

2.2 番号付きリストipairs

ipairsは、{ "Intel", "Ryzen" }のような番号が順番に並んだテーブル(配列)に使うことができる。

ipairs.lua
local cpu = { "Intel", "Ryzen" }

for i, manufacturer in ipairs(cpu) do
    print("主なCPUメーカーは")
    print(i .. manufacturer .. "です。")
end

ipairsは便利ではあるが、テーブルキーが1から連続していないと以下のように途中で終わってしまうので注意しなければならない

ipairs_error.lua
local table = { [1] = "A", [2] = "B", [4] = "D" }

for i, v in ipairs(table) do
    print (i, v)
end
-- 出力:
-- 1  A
-- 2  B
0
0
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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?