I am trying to iterate through a table but start from a position in the table using a key.
list = {
"one",
"two",
"four",
"five",
"six"
}
for k = 3, v in pairs(list) do
print("Key:" .. k .. " " .. "Value:" .. v)
end
Compilation error on line 10: ...\ZeroBraneStudio\myprograms\untitled.lua:10: 'do' expected near 'in'
For an array-like table (one with a sequence), you can use a numeric
for, with the upper bound being the length of the table.Note that starting with a certain key (index) usually only makes sense given an array-like table - which your
listis. The key-value pairs in a table have no stable order as far asnext/pairsis concerned (note thatipairsis for operating on a sequence).If the arbitrary keys in an associative array-like table follow a particular generation order (i.e., they are deterministic), it is possible to iterate through them in a stable way, but that is a specific use-case.
You can also write a function similar in form to
ipairs- one that returns an iterator function (alongside the initial state and control) used by the genericfor, but starts from a given index.Here is a cursory example where the iterator returns index, value to be assigned to the loop variables.
There are many ways to write such an iterator and the function that creates it. For example, returning value, index might be preferred since the value is often more interesting, and allows us to omit the second variable (as opposed to using
for _, value in).