Introspection Functions Lua |
|
Below is a function, originally from [Dir (objects introspection like Python's dir) - Lua - Snipplr Social Snippet Repository], modified so it can iterate through getmetatable of userdata, and recursive call itself for values printout:
------------------------------------------------------------------------ -- based on: -- "Dir (objects introspection like Python's dir) - Lua" -- http://snipplr.com/view/13085/ -- (added iteration through getmetatable of userdata, and recursive call) -- make a global function here (in case it's needed in requires) --- Returns string representation of object obj -- @return String representation of obj ------------------------------------------------------------------------ function dir(obj,level) local s,t = '', type(obj) level = level or ' ' if (t=='nil') or (t=='boolean') or (t=='number') or (t=='string') then s = tostring(obj) if t=='string' then s = '"' .. s .. '"' end elseif t=='function' then s='function' elseif t=='userdata' then s='userdata' for n,v in pairs(getmetatable(obj)) do s = s .. " (" .. n .. "," .. dir(v) .. ")" end elseif t=='thread' then s='thread' elseif t=='table' then s = '{' for k,v in pairs(obj) do local k_str = tostring(k) if type(k)=='string' then k_str = '["' .. k_str .. '"]' end s = s .. k_str .. ' = ' .. dir(v,level .. level) .. ', ' end s = string.sub(s, 1, -3) s = s .. '}' end return s end
This allows that, say, one can call this from SciTE's Lua scripting environment:
print(dir(editor, 2))
... and obtain a printout:
userdata (__newindex,function) (textrange,function) (findtext,function) (insert,function) \ (append,function) (remove,function) (__index,function) (match,function)
... whereas trying to iterate a userdata
directly (by doing for n,v in editor do print(n) end
), would fail with "attempt to call a userdata value
"; while to print
a function
you might get: "attempt to concatenate local 'v' (a function value)
".