Nested tables and metatables - how to find index called in a nested table?

I am looking to determine every index called, on any of the tables within one large nested table. For instance:

local myTable = {}
myTable[1] = 'blue'
myTable[2] = 'orange'
myTable[3] = {[3938] = 'green', [56879] = 'yellow'}
myTable[3][1234] = {'purple'}

print(myTable[3][3938])
--prints green

Sorry for the crazy table layout, just trying to make it readable.

So if I were to call print on that index, I would like to be able to return the index (in this case 3938). Is there a nifty way to do this with a metatable so that I can return any of the index’s, regardless of the inner table? Would I need to nest metatables also?

I tried searching online for a solution and attempted a few things that were more based on retrieving keys on newindex and I couldn’t quite modify that to work for this scenario.

Thanks!

You could probably try something like this:

local t = setmetatable({
   NestedTable = { -- the nested table within the table
      Index = "value" -- key and value
   }
}, {
    __index = function(self, key)
        local value = rawget(self, key) -- gets the raw value (doesn't index __index)

        if type(value) == "table" then -- checks the value's type
           return setmetatable(value, getmetatable(self)) -- returns the table with the __index metatable
        end

        return value
    end
})

Yes

Thanks, is NestedTable in this case actually myTable[3] ?