Цикл while в Lua: примеры и фрагменты кода

Вот несколько примеров использования цикла while в Lua вместе с примером кода:

Метод 1: базовый цикл while

local i = 1
while i <= 5 do
  print("Iteration: " .. i)
  i = i + 1
end

Выход:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5

Метод 2. Цикл с проверкой условий внутри

local input = ""
while input ~= "quit" do
  print("Enter 'quit' to exit:")
  input = io.read()
end

Выход:

Enter 'quit' to exit:
hello
Enter 'quit' to exit:
world
Enter 'quit' to exit:
quit

Метод 3. Цикл с оператором разрыва

local i = 1
while true do
  print("Iteration: " .. i)
  i = i + 1
  if i > 5 then
    break
  end
end

Выход:

Iteration: 1
Iteration: 2
Iteration: 3
Iteration: 4
Iteration: 5