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

前端 未结 3 993
别那么骄傲
别那么骄傲 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: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.

提交回复
热议问题