~technomancy/tremendous-quest-iv

tremendous-quest-iv/metatable_monkey.lua -rw-r--r-- 1.2 KiB
a3c24536Phil Hagelberg Bump to Fennel 0.9.1; fix some bugs. 5 months ago
                                                                                
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
-- 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.
-- taken from Bussard.

local original_pairs, original_ipairs, original_maxn = pairs, ipairs, table.maxn
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 mtmaxn = function(tab)
   local mt = getmetatable(tab)
   if(mt and mt.__maxn) then
      return mt.__maxn(tab)
   else
      return original_maxn(tab)
   end
end

local patched, ipatched, mpatched, t = false, false, false, {}
setmetatable(t, {__pairs = function() return next,{1},nil end,
                 __ipairs = function() return next,{1},nil end,
                 __maxn = function() return 1 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
if(table.maxn(t) ~= 1) then table.maxn = mtmaxn end