Skip to content

Instantly share code, notes, and snippets.

@nefftd
Last active August 29, 2015 14:05
Show Gist options
  • Save nefftd/030934ca8a350baf2c1e to your computer and use it in GitHub Desktop.
Save nefftd/030934ca8a350baf2c1e to your computer and use it in GitHub Desktop.
local grandparent = { a = 1, b = 2, c = 3 }
local parent = { a = 4, b = 5 }
setmetatable(parent, { __index = grandparent })
local child = { a = 7 }
setmetatable(child, { __index = parent })
local function mpairs(t)
local returned = {}
local function next_family(_,k)
local v
repeat
k,v = next(t,k)
if not k then break end
until not returned[k]
if k then
returned[k] = true
return k,v
end
local mt = getmetatable(t)
if mt and type(mt.__index) == 'table' then
t = mt.__index
return next_family(nil,nil)
end
return nil
end
return next_family
end
for k,v in mpairs(child) do print(k,v) end
@nefftd
Copy link
Author

nefftd commented Aug 27, 2014

Somebody required an iterator with the properties that: it will traverse a table, including all inherited properties as well. So I built this: it traverse a table, then when finished, ascends to the next parent up and traverses it too. On the way, it skips any keys which were present somewhere up the line (so they're not getting inherited).

I can't imagine why he really needs this, but here you have it. An ugly-ass iterator.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment