之前在 Lua 代码的编写中写过一些打印表的函数用于调试,这次在看 z.lua 的实现中看到了非常完美的打印表的方法,于是在将代码改得更规范后记录一下:

使用 luacheck 检查 Lua 代码中的错误和不规范之处

local function print_table(table, level)
  local key = ""
  local func
  func = function(t, l)
    l = l or 1
    local indent = ""
    for _ = 1, l do indent = indent .. "  " end
    if key ~= "" then
      print(indent .. key .. " " .. "=" .. " " .. "{")
    else
      print(indent .. "{")
    end

    key = ""
    for k, v in pairs(t) do
      if type(v) == "table" then
        key = k
        func(v, l + 1)
      else
        local content = string.format("%s%s = %s", indent .. "  ", tostring(k),
                                      tostring(v))
        print(content)
      end
    end
    print(indent .. "}")
  end
  func(table, level)
end

print_table({{1, 2, 3}, 4, 5})

结果输出:

  {
    1 = {
      1 = 1
      2 = 2
      3 = 3
    }
    2 = 4
    3 = 5
  }