Difference between revisions of "Lua: Iterators"
m (actually that pattern was crap) |
m |
||
Line 29: | Line 29: | ||
-- a | -- a | ||
-- b | -- b | ||
− | -- c | + | -- c e |
-- d</source> | -- d</source> |
Revision as of 04:12, 17 July 2009
Lua |
---|
Basics |
Intermediate |
Advanced |
|
XLua |
Add to this template |
Iterators are special constructs that traverse something and perform actions on the individual parts. In Lua, this is often a table or string. They are functions most often used in conjunction with a generalized for loop. The two most common iterator functions used in Lua are pairs and ipairs; the former iterates through all keys and indexes in a table, while the latter iterates only numerical indexes. Both return the key (or index) and value of the current place in the table.
t = {1, 2, 3, 4, a = "test", b = "what", c = "more", d = "hello", 5, 6}
for k, v in pairs(t) do
print(k, v)
end
print("-----")
for i, v in ipairs(t) do
print(i, v)
end
You'll notice that ipairs block is effectively equivalent to this for loop:
for i = 1, #t do
print(i, t[i])
end
However, there are some small differences in how each of those handle nil values, but for most purposes they are interchangeable.
One thing you may notice is that the printout of pairs is not necessarily in the same order the table was defined. You can't rely on it to give you information in a predictable order; according to the Lua manual, not even numerical indices are guaranteed to be returned in order (as they are with ipairs). Obviously, you'll want to be careful when using pairs (or next, which is the function pairs actually uses to get the values).
Another useful iterator is found in the string library: gmatch. gmatch allows you to apply a pattern over a string repeatedly until the pattern no longer matches anything. Of course, it returns the match if there is one. The following usage will separate a list of comma-separated values:
s = "a, b, c e, d"
for p in s:gmatch("%s*([^%,]+)%s*") do
print(p)
end
-- prints:
-- a
-- b
-- c e
-- d