自省函数 Lua

lua-users home
wiki

这里可以发布一些有用的自省函数。

Dir(修改版)

下面是一个函数,最初来自 [Dir (objects introspection like Python's dir) - Lua - Snipplr Social Snippet Repository],经过修改,可以遍历 userdata 的 getmetatable,并递归调用自身以打印值

------------------------------------------------------------------------
-- 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

这允许,例如,可以在 SciTE 的 Lua 脚本环境中调用它

print(dir(editor, 2))

... 并获得打印输出

userdata (__newindex,function) (textrange,function) (findtext,function) (insert,function) \
(append,function) (remove,function) (__index,function) (match,function)

... 而尝试直接迭代 userdata通过执行 for n,v in editor do print(n) end),将导致 "attempt to call a userdata value" 错误;而尝试 print 一个 function,你可能会得到 "attempt to concatenate local 'v' (a function value)" 错误。


最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2013 年 4 月 6 日下午 4:52 GMT (差异)