Handling self referencing tables

I have a deep copy function that copies a table as well as its metatable. The problem is when tables like this show up:

MT.__index = MT

When I run DeepCopy on MT, it searches all the stored values; it finds that the key __index stores the table MT, so it runs DeepCopy on that. But MT also has an __index which refers back to MT! This self-reference causes a stack overflow. A simple fix is to just not use this, and replace it with:

MT.__index = function(self, Index) return MT[Index] end

However, I want DeepCopy to work for standard OOP (which uses Object.__index = Object), so the above solution isn’t helpful. Is there a way to successfully copy MT?

Nope, there isn’t with recursive tables. They never work well with deep copying. I know object.__index = object is a common pattern but you should use a separate table anyways.

local Class = { }
local mt = { __index = Class }

You should also separarte the metatable so you can separate constructors and methods

1 Like