Earlier quoted context omitted.
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)
What Lua is lacking here (and why the above iterator function needs 17 lines) is the ability to have “for” go through a list ( without converting the list in to values returned by an iterator function), which would let us quickly and easily sort lists that “for” can use. Something like: 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…
function vs(t)
local i = 0
return function (t)
i = i + 1
return t[i]
end, t
end
function sorted(t, cmp)
table.sort(t, cmp or function (a, b)
return tostring(a)
I.e. if “natively” means strictly “for in t” that generates values, then no, Lua can’t do that. But if “for in vs(t)” is okay, then that vs() is the solution.