lua53_polyfill.lua (660B)
1 local upvaluejoin, getmetatable = debug.upvaluejoin, debug.getmetatable 2 3 -- test whether __ipairs works 4 local function myipairs(x) 5 return function(x, i) return i == 0 and 1 or nil end, x, 0 6 end 7 local t = setmetatable({}, {__ipairs=myipairs}) 8 local n = 0 9 for i in ipairs(t) do n = n+1 end 10 11 if n ~= 1 then 12 local orig_ipairs = ipairs 13 function ipairs(t) 14 local mt = getmetatable(t) 15 if mt.__ipairs then 16 local a,b,c = mt.__ipairs(t) 17 return a,b,c 18 end 19 return orig_ipairs(t) 20 end 21 end 22 23 -- set an unpvalue in a function without affecting other functions 24 return function(fn, i, env) 25 upvaluejoin(fn, i, function() return env end, 1) 26 end