2 ms·
Ah, yeah, the problem won't be visible with a normal loop. However if you break out of the loop without hitting the very last key, or remove a key during the it
by lifthrasiir 4y ago
Ah, yeah, the problem won't be visible with a normal loop. However if you break out of the loop without hitting the very last key, or remove a key during the iteration [1], or loop against the same table inside another loop, then the snippet will fail in unexpected ways.
The correct way to do this is as follows. First you collect all keys and sort them as usual, and then return an iterator function that contains those keys as an upvalue. Essentially you need to create a single-use `pairs` function that holds all necessary states.
[1] You can't insert a key during the iteration, but removing an existing key is guaranteed to work correctly, no matter if you've already past the deleted key or not: https://www.lua.org/manual/5.4/manual.html#pdf-next https://www.lua.org/manual/5.4/manual.html#pdf-next