在__index元方法中产生了无限递归。

据我理解,Lua 只有在表中找不到键时才会调用 __index 函数,因此我有一个代码,在 __index 部分遇到了无限递归的问题,但我无法理解,因为在 __index 函数中使用的两个值已经存在于表中!?

这基本上是一个测试脚本,用于尝试在保存表的大小以供在调用 # 时检索时,将其保存在内存中。

    do
local lenKey,originalKey = {},{}
fastKey = {}
fastKey.__len = function(t) return t[lenKey] end
fastKey.__index = function (t,k)
                        t[lenKey] = t[lenKey] +1
                        return t[oroginalKey][k]
                end
fastKey.__newindex = function(t,k,v) t[originalKey][k] = v end
fastKey.__pairs = function ()
                    return  function (t, k)
                                return next(t[oroginalKey], k)
                            end
                end

function fastLen(t)
    local proxy = {}
    local c = 0
    for _ in pairs(t) do
        c=c+1
    end
    proxy[lenKey] = c
    proxy[originalKey] = t
    setmetatable(proxy,fastKey)
    return proxy
end
end

n = fastLen{1,2,3,x=5}
--n:insert(1) -- here the __index is called and gets stackoverflow
print(#n)
点赞
用户1633117
用户1633117

你的其中两个拼写错误:__index__pairs 函数中都包含了 oroginalKey 而非 originalKey

2013-06-28 15:46:43