lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]

On Wed, Aug 17, 2016 at 7:41 PM, ThePhD <> wrote:

> I have a small question regarding the Lua C API's "lua_next" function when used on a certain subset of objects: tables that are made like arrays, with sequential integer keys. Is the order of iteration guaranteed to go from '0' to 'N' in this case, or am I still subject to jumping around in some implementation-defined order of traversal?

I am answering the very first question because I do not see a better place to jump in. I have read the entire thread, though.

Perhaps before you ask that question, you should ask yourself "why do I care"? Or, perhaps, "what do I really want to achieve"?

Lua's table is a generic structure. It can be used as an array and as an dictionary, but not at the same time. Where you need an array, use it as an array. That means contiguous integers as keys, beginning at 1, and iteration with the index and the # length thingy. Any other use of Lua's tables is their use as dictionaries,

When tables are used as dictionaries, Lua does not guarantee any particular order of iteration.

If, in this latter case, you need to feed the table's data in some particular order to something else (say, the screen), it is your responsibility to ensure that order, whatever it could be. Increasing numeric indices, if the table happens to have them, is just one case; in another case you might want the German collating rules, and so on.

That means an effort and very possibly a run-time cost, and you cannot avoid them by hoping that Lua does something that it really does not.