honeylisp/lib/metatable_monkey.lua
Jeremy Penner 12481e9257 non-working attempt to lazily expand macros using lua proxy objects
Unfortunately there is no way to override # in luajit, so I can't make
a truly transparent proxy. Unclear if I could get away with a weird
half-object, but it doesn't seem to be working.
2021-10-22 20:44:24 -04:00

34 lines
966 B
Lua

-- source: https://gitlab.com/technomancy/bussard/-/blob/master/metatable_monkey.lua
-- Versions of Lua prior to 5.1 could not properly support iterating over proxy
-- tables with their built-in iterators. This module fixes that problem.
local original_pairs, original_ipairs = pairs, ipairs
local mtpairs = function(tab)
local mt = getmetatable(tab)
if(mt and mt.__pairs) then
return mt.__pairs(tab)
else
return original_pairs(tab)
end
end
local mtipairs = function(tab)
local mt = getmetatable(tab)
if(mt and mt.__ipairs) then
return mt.__ipairs(tab)
else
return original_ipairs(tab)
end
end
local patched, ipatched, t = false, false, {}
setmetatable(t, {__pairs = function() return next,{1},nil end})
for _ in pairs(t) do patched = true end
if(not patched) then pairs = mtpairs end
for _ in ipairs(t) do ipatched = true end
if(not ipatched) then ipairs = mtipairs end
return {original_pairs, original_ipairs}