1. ホーム
  2. スクリプト・コラム
  3. ルア

Luaの3種類のループの使い方を解説

2022-01-05 06:13:51

Luaのループは、C言語のループと似たような構文なので、理解しやすく、実装も簡単です。

以下はその例です。

test1.lua

-- 1. while loop
--[[
 Understand it as a C language, in fact, it is almost the same
 Syntax format.
 while(true)
 do
 Execute the statement
 end
]]
-- Define a global variable a=0
a=0
--
while(true)
do 
 a=a+1
 print("a:",a)
 if(a == 5)
 then
 break
 end
end
-- 2. for loop
--[[
 Understand the C language for on the line, in fact, almost the same
 Syntax format.
 for var=exp1,exp2,exp3 do 
 The statement you want to execute
 end 
end]]
-- numeric for loop
-- How to understand? i = 0 , i <=5 ; i+=1 
--if the third parameter 1 is negative, it means to do the operation of subtracting one
--parameter 2 as a condition, of course, you can also pass the function, using the function as a return value for the condition to achieve the loop
for i = 0 , 5 , 1 do
 print("i:",i)
end
--generic for loop
--java-like iteration
--[[
 Format.
 for i,v in ipairs(a) 
 do 
 print(v) 
 end  
]]
--i is the index of the array, v is the value of the array element corresponding to the index, ipairs is an iterative function of lua, which is used to iterate through the array
num = {1,2,3,4,5}
for i,v in ipairs(num) do
 print("num:",num[i])
end
--3. repeat... .util loop
--[[
 Understand as a shell script until on the line, in fact, almost the same, as long as the condition does not hold the execution, the condition is established to end
 Syntax format.
 repeat
  The statement you want to execute
 until( judge condition )
]]
num1 = 1
repeat 
 print("num1:",num1)
 num1 = num1 + 1 
until(num1 > 5)

ランを説明する。

lua test2.lua

実行結果。

a: 1
a: 2
a: 3
a: 4
a: 5
i: 0
i: 1
i: 2
i: 3
i: 4
i: 5
num: 1
num: 2
num: 3
num: 4
num: 5
num1: 1
num1: 2
num1: 3
num1: 4
num1: 5

概要

この記事の内容が、あなたの勉強や仕事の参考になれば幸いです。また、スクリプトハウスを応援していただきありがとうございます。もっと詳しく知りたい方は、以下のリンク先をご覧ください。