為了讓游戲前端數據輸出更加條理,做了一個簡單樹狀結構來打印數據。
ccmlog.lua
~~~
local function __tostring(value, indent, vmap)
local str = ''
indent = indent or ''
vmap = vmap or {}
--遞歸結束條件
if (type(value) ~= 'table') then
if (type(value) == 'string') then
--字符串
str = string.format("[[%s]]", value)
else
--整數
str = tostring(value)
end
else
if type(vmap) == 'table' then
if vmap[value] then return '('..tostring(value)..')' end
vmap[value] = true
end
local auxTable = {} --保存元表KEY(非整數)
local iauxTable = {} --保存元表value
local iiauxTable = {} --保存數組(key為0)
table.foreach(value, function(i, v)
if type(i) == 'number' then
if i == 0 then
table.insert(iiauxTable, i)
else
table.insert(iauxTable, i)
end
elseif type(i) ~= 'table' then
table.insert(auxTable, i)
end
end)
table.sort(iauxTable)
str = str..'{\n'
local separator = ""
local entry = "\n"
local barray = true
local kk,vv
table.foreachi (iauxTable, function (i, k)
if i == k and barray then
entry = __tostring(value[k], indent..' \t', vmap)
str = str..separator..indent..' \t'..entry
separator = ", \n"
else
barray = false
table.insert(iiauxTable, k)
end
end)
table.sort(iiauxTable)
table.foreachi (iiauxTable, function (i, fieldName)
kk = tostring(fieldName)
if type(fieldName) == "number" then
kk = '['..kk.."]"
end
entry = kk .. " = " .. __tostring(value[fieldName],indent..' \t',vmap)
str = str..separator..indent..' \t'..entry
separator = ", \n"
end)
table.sort(auxTable)
table.foreachi (auxTable, function (i, fieldName)
kk = tostring(fieldName)
if type(fieldName) == "number" then
kk = '['..kk.."]"
end
vv = value[fieldName]
entry = kk .. " = " .. __tostring(value[fieldName],indent..' \t',vmap)
str = str..separator..indent..' \t'..entry
separator = ", \n"
end)
str = str..'\n'..indent..'}'
end
return str
end
ccmlog = function(m,fmt,...)
local args = {...}
for k,arg in ipairs(args) do
if type(arg) == 'table'
or type(arg) == 'boolean'
or type(arg) == 'function'
or type(arg) == 'userdata' then
args[k] = __tostring(arg)
end
end
args[#args+1] = "nil"
args[#args+1] = "nil"
args[#args+1] = "nil"
local str = string.format("[%s]:"..fmt.." %s", m, unpack(args))
print(str)
local off = 1
local p = CCLOGWARN
if m == 'error' then
p = CCLOGERROR
elseif m == 'warn' then
p = CCLOGWARN
end
while off <= #str do
local subStr = string.sub(str, off, off+1024)
off = off + #subStr
--p(subStr)
end
end
--打印測試
reserved = { [100] = { 300, 400}, 200, { 300, 500}, abc = "abc",[0] = {1,2,3,"abc"}}
ccmlog("d","d",reserved)
~~~
打印效果如下:

為了讓程序模塊調用該打印接口,打印函數前加上module("ccmlog", package.seeall),并將此文件保存在類似lualibs的庫目錄,然后在程序中用require "ccmlog"來調用該函數了.
- 前言
- lua學習筆記之一(C/C++程序員的Lua快速入門[初階話題])
- lua學習筆記之二(C/C++程序員的Lua快速入門[進階話題])
- lua學習筆記之三(C/C++程序員的Lua快速入門[高階話題])
- lua學習筆記之四(Lua中的基本函數庫)
- lua學習筆記之五(Lua中的數學庫)
- Lua中的table函數庫
- Lua中的常用操作系統庫
- LUA string庫
- LUA IO庫
- VS2010編譯Lua程序(lua-5.2.3)
- Lua中調用C函數(lua-5.2.3)
- Lua 常用數據結構
- lua 如何輸出樹狀結構的table?
- Lua中的元表與元方法
- lua 函數回調技巧
- Cocos2d-x使用Luajit實現加密
- Lua中的模塊與module函數
- 我所理解lua 語言中的點、冒號與self
- Lua代碼編寫規范