內省函式 Lua

lua-users home
wiki

這裡可以將一些有用的內省函式貼出來。

Dir (修正版)

以下是一個函式,原本來自 [Dir (objects introspection like Python's dir) - Lua - Snipplr Social Snippet Repository],修正過可以迭代透過使用者資料的元表,以及遞迴呼叫函數本身來印出數值。

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

... 而嘗試直接迭代一個使用者資料例如做 for n,v in editor do print(n) end),會失敗並出現「attempt to call a userdata value」;而要列印一個函式可能會得到:「attempt to concatenate local 'v' (a function value)」。


RecentChanges · 偏好設定
編輯 · 歷程
最後編輯時間 2013 年 4 月 6 日 下午 4:52 (格林威治標準時間) (比較版本)