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: getalldata(self).
I'm currently working on a project where lua is involved. Unfortunately, there is no complete reference and i have to use precompiled stuff.
I hope you are able to understand what I am trying to say.
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
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 __index
es is a function, there is no way to get all the properties; at least not from Lua.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With