lua-users home
lua-l archive

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


Hi all,

I have been using the following iterator for some time but it just occurred to me that it may work by lucky accident.

I have tested it with Lua v5.1, v5.2, and v5.3 and it always gives correct results for any table that contains any combination of key-value pairs and/or lists (indexed 1..n) provided there are no gaps in the 1..n numeric sequence:

------------------
function kpairs(t)
 local key = #t
 if key == 0 then key = nil end
 return next,t,key
end
------------------

"for k,v in kpairs(t) do print(k,v) end" will iterate over and print all non-list (1..n) elements of the given table. (Again, assuming there are no gaps in the sequence.) But this behavior does not seem to be guaranteed by the 'next' documentation (unless I missed something) which says: "The order in which the indices are enumerated is not specified, even for numeric indices."

(BTW: In LuaJIT, it fails just for index 0 -- and possibly other cases I didn't test as I rarely use LuaJIT)

So, my question is:
Can I rely on this behavior for standard Lua, or is this an implementation accident that could stop working any time a new version comes out? (Or, is it even the case that even the current implementation won't work for all cases, and I simply was lucky enough not to hit those? Examples where it wouldn't work?)

TIA