for in loop
A "for in" loop is a construct that allows you to iterate over elements in a table or array without specifying the loop control variables or indices. In Lua, the "for each" loop is achieved using the for
keyword in combination with an iterator function (pairs(), ipairs(), os.fs.glob()
).
The specific form of a "for each" loop in Lua uses the for k, v in pairs(table) do
syntax, where:
k
is a variable that represents the key of the current element.v
is a variable that represents the value associated with the key.
Here's a simple example using a Lua table:
-- Example table
local myTable = {key1 = "value1", key2 = "value2", key3 = "value3"}
-- Iterate over key-value pairs using pairs()
for k, v in pairs(myTable) do
trace(k, v)
end
In this example, for each iteration the pairs
function returns an iterator function that produces key-value pairs from myTable
.
k
takes on the key, and v
takes on the corresponding value. The loop body (the print(k, v)
statement in this case) is executed for each pair.
The output of this example would be:
key1 value1
key2 value2
key3 value3
This type of loop is convenient when you want to iterate over the elements of a collection without explicitly dealing with indices. It's often used with tables in Lua, but it can be applied to other iterable data structures as well.