What is the method for iterating through an array in Lua?

In Lua, loops can be used to iterate over arrays. Common methods include for loops and while loops.

  1. Traverse the array using a for loop.
local array = {"apple", "banana", "orange"}

-- 使用数字索引遍历数组
for i = 1, #array do
    print(array[i])
end

-- 使用泛型遍历数组
for index, value in ipairs(array) do
    print(index, value)
end
  1. Iterate through the array using a while loop.
local array = {"apple", "banana", "orange"}
local i = 1

while array[i] do
    print(array[i])
    i = i + 1
end

You can access array elements and manipulate or print them using either for loops or while loops by using array indexes.

bannerAds