lua递归输出表table的内容

来源:互联网 发布:科比0506赛季详细数据 编辑:程序博客网 时间:2024/06/06 17:52
local tconcat = table.concatlocal tinsert = table.insertlocal srep = string.rep
function print_r(root)local cache = {  [root] = "." }local function _dump(t,space,name)local temp = {}for k,v in pairs(t) dolocal key = tostring(k)if cache[v] thentinsert(temp,"+" .. key .. " {" .. cache[v].."}")elseif type(v) == "table" thenlocal new_key = name .. "." .. keycache[v] = new_keytinsert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " ).. srep(" ",#key),new_key))elsetinsert(temp,"+" .. key .. " [" .. tostring(v).."]")endendreturn tconcat(temp,"\n"..space)endprint(_dump(root, "",""))end



简单一点,可以按照如下写

--打印tablefunction print_t(root)    local cache = {  [root] = "." }    local function _dump(t,space,name)        local temp = {}        for k,v in pairs(t) do            local key = tostring(k)            if cache[v] then                table.insert(temp,"+" .. key .. " {" .. cache[v].."}")            elseif type(v) == "table" then                local new_key = name .. "." .. key                cache[v] = new_key                table.insert(temp,"+" .. key .. _dump(v,space .. (next(t,k) and "|" or " " )..                     string.rep(" ",#key),new_key))            else                table.insert(temp,"+" .. key .. " [" .. tostring(v).."]")            end        end        return table.concat(temp,"\n"..space)    end    print(_dump(root, "",""))end


0 0