lua树型打印table

来源:互联网 发布:网络安全设备 编辑:程序博客网 时间:2024/06/05 12:08

Lua,是当今手游客户端脚本开发的宠儿,鼎鼎大名的魔兽争霸”就是采用Lua作为其脚本开发语言。

Lua的设计理念跟Scheme如出一辙,遵循极简主义哲学。但是麻雀虽小,五脏俱全。

想当初开始接触手游开发,找了一本《Lua程序设计》作为教材,其基础知识一天内就可以掌握了。

Lua唯一的数据结构是table,不管是数组还是hashmap,皆为table。还有一点值得说明的是,作为一门脚本语言,Lua的调试方法基本靠打印。(虽然也有VisivalStudio可以调试,但大部分开发人员没用,习惯使然。)

因此,需要一种工具能够对table进行递归格式化输出。下面的代码可以实现

TablePlus = {}local function checkTable( t )-- bodyif type(t) ~= "table" then error("t is not table")end endlocal function checkType(_type)if _type ~= "array" and _type ~= "hashmap" and _type ~= nil then error("invalid type .." .. tostring(_type))endend --[[设置元表属性__type,取值自["array","hashmap"]]]local function genmetatable(_type)checkType(_type)local __type = _type or "hashmap"local mt = {__index = function(t,k)if k == "__type" then return __typeelse return rawget(t,k)endend,__newindex = function(t,k,v)if k == "__type" then checkType(v)__type = velse rawset(t,k,v)endend}return mtendfunction TablePlus.new(_type)local t = {}setmetatable(t,genmetatable(_type))return t end function TablePlus:foreach(f)if self.__type == "array" then for k,v in ipairs(self) do if f(k,v) then break end --拓展可中断endelse for k,v in pairs(self) do if f(k,v) then break end --拓展可中断end end end --[[递归打印table]]function TablePlus.toString(t,isRecur)if (type(t) ~= "table") then return tostring(t) elselocal result = "{"TablePlus.foreach(t,function(k,v)result = result .. "['" .. tostring(k) .. "']=" if type(v) == "table" and isRecur == true then result = result .. TablePlus.tostring(v,true) .. "',"elseif type(v) == "string" thenresult = result .. "'" .. tostring(v) .. "',"elseresult = result  .. tostring(v) .. ","end end )return result .. "}"endend local function wordsIndentBy(xn)local result = ""    for i=1,xn do          result = result .."\t"      end return resultend  local function _toTreeString(t,deep)if (type(t) ~= "table") then return tostring(t) elselocal indent = wordsIndentBy(deep)local result = indent .. "table{\n" TablePlus.foreach(t,function(k,v)result = result ..  wordsIndentBy(deep+1)result = result .. "['" .. tostring(k) .. "']=" if type(v) == "table" then local subT = _toTreeString(v,deep+2) result = result .. "\n" ..  subT.. "'," .. "\n"elseresult = result  .. tostring(v) .. ",".. "\n"end end )return result .. indent ..  "}"endend --[[将table打印为树形结构]]function TablePlus.toTreeString(t)return _toTreeString(t,0)end

其中,设置元表的部分,是为了标记table的类型是数组(array)还是映射(hashmap)

下边为测试代码(无格式+树形table打印输出)

t={school = {name = "scau",location = "gz"},age = 13,name = "Lily",}print("print table directly " )print("" )print(TablePlus.toString(t,true))print("" )print("print table in tree pattern " )print("" )print(TablePlus.toTreeString(t))
输出如下

0 0