Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Way to get all "supertables" (opposite of metatables)?

edited March 2015 in Questions Posts: 12

In my program it would be very helpful to have a function that would do the following:

--the function I want is wantedFunction()
mt={}
t=setmetatable({},mt)
t2=setmetatable({},mt)
wantedFunction(mt) --should return {t,t2}

In other words, if i have a table which is a metatable, is there any way to write a function to find all of the tables it is a metatable for?

Also, I'm new to this forum, so any info as to how to make my posts better is appreciated.

Comments

  • @Jmv38 Thanks, that helped a lot! I was able to make my question much clearer.

  • IgnatzIgnatz Mod
    Posts: 5,396

    @time4coding - try this, it's a bit of a kludge because it loops through every object in memory to get the list - but it is fast. The variable _G is worth exploring, it is a table holding absolutely everything.

    function setup()
        mt={}
        t=setmetatable({},mt)
        t2=setmetatable({},mt)
        list=GetTableList(mt)
        print(t==list[1],t2==list[2]) --check it worked
    end
    
    function GetTableList(m)
        local list={}
        for n,v in pairs(_G) do --look at everything
            if type(v)=="table" then
                local mt=getmetatable(v)
                if mt==m then table.insert(list,v) end
            end
        end
        return list
    end
    
  • Jmv38Jmv38 Mod
    edited March 2015 Posts: 3,295

    Precision: _G holds everything that is *top level* : it doesnt see local variables, or objects recorded inside tables only. (@Ignatz: i know you know).

  • Jmv38Jmv38 Mod
    edited March 2015 Posts: 3,295

    You probably want to access only some special metatables, corresponding to some class you've created? If so you can simply record each object when it is created:


    --# example example = class() example.list = {} function example:init(name) self.name = name table.insert(example.list,self) end --# Main -- class list function setup() ex1 = example("name 1") ex2 = example("name 2") for k,v in pairs(example.list) do print(v.name) end end

    here example variable is the metatable of every object you create with example("xx"), so it looks pretty much like what you wanted (a list of all objects with this metatable).

  • Both of these methods work great! Thanks for introducing me to _G too.

  • IgnatzIgnatz Mod
    Posts: 5,396

    @time4coding - welcome to the forum, by the way. :-h

  • Posts: 547

    @Jmv38 thanks for that, I was able to use it for resetting all my buttons when a popup occured :)

    @time4coding welcome to the forum indeed :)

Sign In or Register to comment.