lua-users home
lua-l archive

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


steve donovan wrote:

> On Mon, May 24, 2010 at 3:29 PM, Juri Munkki <jm_list@cameraid.com> wrote:
> > Ipairs allows you to add items to the list. If you evaluate the length of
> > the list in a numeric loop, you can't add new items to the list within the
> > loop and expect them to be looped through. Similarly, deleting items from
> > a table within the loop will behave differently with ipairs and a numeric
> > loop using #table.
> 
> Very good point; the obvious & naive implementations of ipairs lack
> this very important property.


What would be the closest compatible pure-Lua implementation of ipairs()
for Lua 5.2?

This is what I've got in my "utilities.lua" file which I use with all
my own projects:


-- ipairs() depreciated (with an error) in Lua 5.2
if not pcall(ipairs, {}) then
    local function ipairs_helper(a, i)
        i = i + 1
        local v = a[i]  -- use rawget?
        if v ~= nil then
            return i, v
        end
    end

    function ipairs(a)
        --   iterator function, context, start value
        local mt = getmetatable(a)
        if mt and mt.__ipairs then
            return mt.__ipairs(a)
	else 
	    return ipairs_helper, a, 0
        end
    end
end


Questions:

Should I be using rawget(a, i) instead of a[i]?  

Since I want ipairs() to be universally accessible, is there any
practical difference to declaring the function as it is now, versus
inserting it explicitly in the _G table?

------------------------------------------------------------

I use ipairs() all the time in my code.  I like that it iterates over
only the integer keys.  Sometimes I use tables where the 'main'
information is in the integer keys, and other details (like options) are
in string keys.  

I'm not worried if it is a little slower or less efficient than a
numeric for loop.


James Graves