调试和测试

lua-users home
wiki


[!] 版本说明: 以下代码适用于旧版本的 Lua,Lua 4。它在 Lua 5 下无法运行。

这些例程提供了断言、警告、错误和其他调试功能,这些功能在其他语言中很常见。有关单元测试功能的讨论,请参见 单元测试

断言、警告和调试消息

其中一些函数假设存在一个全局变量 line,它提供正在处理的文件的当前行号,如果这有意义的话。

另请参见 优化编码技巧 中的 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

调试工具

对于一般的交互式使用也很有用:tostring 的扩展,因此 print 可以更好地显示表格。

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

最近更改 · 偏好设置
编辑 · 历史记录
最后编辑于 2019 年 1 月 26 日凌晨 12:39 GMT (差异)