Lua: Iterators

From Mario Fan Games Galaxy Wiki
Revision as of 22:40, 16 July 2009 by Xgoff (talk | contribs) (Created page with '{{Lua}} '''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 [[functi…')
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Lua
Lua.gif
Basics
Intermediate
Advanced
XLua
Add to this template
 Standardwikimessagebox.png This article assumes the use of Lua 5.1.

Information may not be accurate or may need revision if you are using a different version.

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, d"

for p in s:gmatch("[^%,%s]") do
   print(p)
end
-- prints:
-- a
-- b
-- c
-- d