I can iterate through an array/table (for example {'a', 'b', 'c'}
) using a regular for
loop. And then there is iteration using pairs
for _, v in pairs({'a', 'b', 'c'}) do
io.write(v..'\n')
end
but when I have a plain old array, I really don't find myself caring about the keys.
Is there a way of iterating like
for value in array do end
I do see instances of this. For example I'm using a library to create a map in my game and I see you can access objects in a map layer like this
for object in map.layer["platform"].nameIs("platform") do
Any way to iterate like this?
For arrays, the natural way is to use ipairs
, not pairs
. However, it still needs a key:
for _, v in arr do
If you really want to avoid the key item, make your own iterator. Programming in Lua provides one as an example:
function values(t)
local i = 0
return function() i = i + 1; return t[i] end
end
Then you can use it like this:
local arr = {'a', 'b', 'c', 'd'}
for e in values(arr) do
print(e)
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With