Debugging And Testing

lua-users home
wiki


[!] VersionNotice: 下方程式碼屬於舊版的 Lua,Lua 4。在 Lua 5 下無法執行。

這些常式提供斷言、警告、錯誤和其他除錯功能,是其他程式語言中的常見功能。請參閱 UnitTesting 中關於單元測試功能的說明。

斷言、警告和除錯訊息

這些函數有些假設有一個名為 line 的全域變數,儲存正在處理的檔案中的目前行號,這可能有意義。

另請參閱 OptimisationCodingTips 中的 fast_assert

-- Give warning with, optionally, the name of program and file
--   s: warning string
function warn(s)
  if prog.name then write(_STDERR, prog.name .. ": ") end
  if file then write(_STDERR, file .. ": ") end
  writeLine(_STDERR, s)
end

-- Die with error
--   s: error string
function die(s)
  warn(s)
  error()
end

-- Die with line number
--   s: error string
function dieLine(s)
  die(s .. " at line " .. line)
end

-- Die with error if value is nil
--   v: value
--   s: error string
function affirm(v, s)
  if not v then die(s) end
end

-- Die with error and line number if value is nil
--   v: value
--   s: error string
function affirmLine(v, s)
  if not v then dieLine(s) end
end

-- Print a debugging message
--   s: debugging message
function debug(s)
  if _DEBUG then writeLine(_STDERR, s) end
end

除錯公用程式

常式擴充 tostringprint,更適合顯示表格,而且一般互動使用也常會用到。

-- Extend tostring to work better on tables
-- make it output in {a,b,c...;x1=y1,x2=y2...} format; use nexti
-- only output the LH part if there is a table.n and members 1..n
--   x: object to convert to string
-- returns
--   s: string representation
function tostring(x)
  local s
  if type(x) == "table" then
    s = "{"
    local i, v = next(x)
    while i do
      s = s .. tostring(i) .. "=" .. tostring(v)
      i, v = next(x, i)
      if i then s = s .. "," end
    end
    return s .. "}"
  else return %tostring(x)
  end
end

-- Extend print to work better on tables
--   arg: objects to print
function print(...)
  for i = 1, getn(arg) do arg[i] = tostring(arg[i]) end
  call(%print, arg)
end

這裡提供 Get/DiffGlobalNames,可用於追蹤意外的全局指派

-- GetGlobalNames - returns hash table of current
--     global names
--
function GetGlobalNames()
  local names = {}
  for i,x in globals() do
    names[i] = 1
  end
  return names
end

-- DiffGlobalNames - shows diff of current global names
--     vs previously recorded
--
function DiffGlobalNames(t)
  local gtable = globals()
  local deleted = {}

  local added = {}
  for i,x in t do
    if not gtable[i] then
      tinsert(deleted, i)
    end
  end
  for i,x in gtable do
    if not t[i] then
      tinsert(added, i)
    end
  end
  sort(deleted)
  sort(added)
  print("Changes to global names:")
  print("    Deleted")
  for i = 1, getn(deleted) do
    print("        "..deleted[i])
  end
  print("    Added")
  for i = 1, getn(added) do
    print("        "..added[i])
  end
end

RecentChanges · 偏好設定
編輯 · 歷史記錄
最後於 2019 年 1 月 26 日上午 12:39 GMT 編輯 (diff)