lua loop through table
-- Define a sample table
myTable = {10, 20, 30, 40, 50}
-- Iterate through the elements of the table using a numeric for loop
for i = 1, #myTable do
-- Access the current element using the index 'i'
local currentValue = myTable[i]
-- Print the index and value of the current element
print("Index:", i, "Value:", currentValue)
end
Explanation:
1. A table named myTable
is defined with numeric elements {10, 20, 30, 40, 50}
.
2. The for
loop is set up to iterate from index 1
to the length of the table (#myTable
).
3. Inside the loop, the variable i
represents the current index in each iteration.
4. local currentValue = myTable[i]
retrieves the value of the element at the current index (i
) and stores it in the variable currentValue
.
5. The print
statement outputs the index and value of the current element during each iteration.