I found a bug in __pairs metamethod

  • From: 云风 <cloudwu@xxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Wed, 12 Sep 2012 20:24:24 +0800

I enable "Lua 5.2 __pairs and __ipairs metamethods", and found a bug.

This is the sample code.
-------------------------
local tbl = {}

local a = { values=  { foo = 1 } }

local iter = function(value)
        local function loop(t,k)
                return next(t,k)
        end
    return loop, value
end

local mt = {
        __pairs = function(self)
                local values = rawget(self, "values")
                return iter(values)
        end
}

setmetatable(a,mt)

tbl.a = a

local function trav(k,t)
        if type(t) == "table" then
                print(k, t)
                for k,v in pairs(t) do
                        trav(k,v)
                end
        end
end

trav("",tbl)
---------------------

Run these codes above, and "a" print twice :(

        table: 0x00326f48
a       table: 0x00326fe0
a       table: 0x00326fe0

If I change function iter to :

local iter = function(value)
    return next, value
end

It will be correct. ( Only once "a" )

        table: 0x002b1c38
a       table: 0x002b1c60

--------

-- 
http://blog.codingnow.com

Other related posts: