6 ms·
You can convert a list first and then feed it to a simple iterator. I don’t fully understand what your exact real-code issues can be, but hope this snippet may
by wruza 7y ago
You can convert a list first and then feed it to a simple iterator. I don’t fully understand what your exact real-code issues can be, but hope this snippet may help:
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) < tostring(b)
end)
return t
end
function keys(t)
local keys = { }
for key in pairs(t) do
table.insert(keys, key)
end
return keys
end
t = {a=10, c=20, d=30, b=40, 50}
for k in vs(sorted(keys(t))) do
print(k, t[k])
end
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.
- strenholme 7y agoThat looks good, and I think putting these in a prominent place of the Lua documentation (along with a notice that the code is public domain) would help us who are used to the AWK/Perl/Python/PHP way of having “for” natively traverse a list without needing a complicated list-to-iterator function that uses function closure (i.e. the iterator function remembers the value “i” -- I’m writing this for the lurkers because code like this can be difficult to follow). One honest question: Is there any reason why the function factory (i.e. a function which returns a function) which converts a list (Actually, table with ascending integer indexes) in to an iterator Lua can use with “for” returns both the element and the entire table here? Here is the code I am asking about: return function (t) i = i + 1 return t[i] end, t I’m curious why we’re returning both the table element for the iterator and the entire table.