This is a refreshing update for those of us that like having code which will always act in the same way across multiple invocations. Now, if only Lua could follow the same path with their “tables” (“tables” is what Lua programmers call their form of Python’s “dictionaries” and Perl’s “hashes”). I just spent eight hours earlier this week debugging Lua code which would run differently on different invocations of the sa…
You can write an iterator yourself, no need to leave ?pairs idiom: function sortpairs(t) local keys = { } for key in pairs(t) do table.insert(keys, key) end table.sort(keys, function (a, b) return tostring(a)
d = {"foo": 2, "bar": 1, "zoo": 4}
for k in sorted(d.keys()):
print k
(I’m not advocating Python here, since Perl has a similar way of using “for” to go through lists which can also be easily sorted)However, with Lua, “for” only accepts a numeric range, or an iterator function, so customizing “for” requires understanding function closures: Understanding how a function, when called multiple times, stores variables altered in previous invocations of the function, and understanding how to give those variables initial values (usually in the “function factory” function which creates the function we use).
In other words, “for”, in most modern high-level languages, can be one of:
1. for variable in [something that specifies a numeric range]
2. for variable in [iterator function]
3. for variable in [list]
But Lua only has “something that specifies a numeric range” and “iterator function”; it can not natively go through a list.