how to find out all properties of an object in lua?

前端 未结 3 1004
别那么骄傲
别那么骄傲 2021-02-20 07:15

Is there any way of getting all the non-nil parameters / properties of an object? I found this: getmetadata(self.xxxx) and i am looking for something like: ge

相关标签:
3条回答
  • 2021-02-20 07:26

    I wrote my own printObject code.. here it is

    function printObj(obj, hierarchyLevel) 
      if (hierarchyLevel == nil) then
        hierarchyLevel = 0
      elseif (hierarchyLevel == 4) then
        return 0
      end
    
      local whitespace = ""
      for i=0,hierarchyLevel,1 do
        whitespace = whitespace .. "-"
      end
      io.write(whitespace)
    
      print(obj)
      if (type(obj) == "table") then
        for k,v in pairs(obj) do
          io.write(whitespace .. "-")
          if (type(v) == "table") then
            printObj(v, hierarchyLevel+1)
          else
            print(v)
          end           
        end
      else
        print(obj)
      end
    end
    

    This is the opposite approach then the post before used. Go through all key value pairs in the table. If the value of one index is a table, go through this table. This solution will not get the upwards metatables like the other post did

    0 讨论(0)
  • 2021-02-20 07:35

    I believe objects are just a table, so you should be able to iterate over the properties as any other table:

    for i,v in ipairs(your_object) do body end
    
    0 讨论(0)
  • 2021-02-20 07:36

    I'm going to assume that when you are referring to "objects" you are meaning "lua tables with an __index metatable pointing to other tables". If that is not the case, this answer will not help you.

    If your object structure is made with tables (this is, all __indexes are tables) then you can "parse them up" to obtain all the properties and inherited properties.

    If you have any function as __index then what you ask is impossible; there's no way to get the "list of values for which a function returns a non-nil value".

    In the first case, the code would look like this:

    function getAllData(t, prevData)
      -- if prevData == nil, start empty, otherwise start with prevData
      local data = prevData or {}
    
      -- copy all the attributes from t
      for k,v in pairs(t) do
        data[k] = data[k] or v
      end
    
      -- get t's metatable, or exit if not existing
      local mt = getmetatable(t)
      if type(mt)~='table' then return data end
    
      -- get the __index from mt, or exit if not table
      local index = mt.__index
      if type(index)~='table' then return data end
    
      -- include the data from index into data, recursively, and return
      return getAllData(index, data)
    end
    

    But remember, if any of your __indexes is a function, there is no way to get all the properties; at least not from Lua.

    0 讨论(0)
提交回复
热议问题