luastack-overflowlua-tablemetatablemeta-method

Why does this cause a C stack overflow?


I'm aware that I can fix this problem by using rawset, but I'm just wondering why the following code causes a C stack overflow.

local mt = {
    __newindex = function(self, key, value) 
        self[key] = value 
    end
}

local x = setmetatable({}, mt)

x.y = 5

Solution

  • Deep Recursion.

    Inside the call to the metamethod __newindex, self[key] = value calls the metamethod __newindex again, recursively, until stack overflow.