Recursively print table (print_r equivalent)



Published: 2018-09-20 22:39:40 +0000
Categories: LUA,

Language

LUA

Description

PHP's print_r can be very useful when testing and debugging, but LUA doesn't have a native equivalent

This function implements similar functionality, though for convenience rather than force printing the generated result, it returns it as a string (so you can write it to a log if that's preferred

Similar to

Snippet

function dumpvar(data)
    -- cache of tables already printed, to avoid infinite recursive loops
    local tablecache = {}
    local buffer = ""
    local padder = "    "

    local function _dumpvar(d, depth)
        local t = type(d)
        local str = tostring(d)
        if (t == "table") then
            if (tablecache[str]) then
                -- table already dumped before, so we dont
                -- dump it again, just mention it
                buffer = buffer.."<"..str..">\n"
            else
                tablecache[str] = (tablecache[str] or 0) + 1
                buffer = buffer.."("..str..") {\n"
                for k, v in pairs(d) do
                    buffer = buffer..string.rep(padder, depth+1).."["..k.."] => "
                    _dumpvar(v, depth+1)
                end
                buffer = buffer..string.rep(padder, depth).."}\n"
            end
        elseif (t == "number") then
            buffer = buffer.."("..t..") "..str.."\n"
        else
            buffer = buffer.."("..t..") \""..str.."\"\n"
        end
    end
    _dumpvar(data, 0)
    return buffer
end

Usage Example

dumpvar(foo)

Keywords

print_r, dump, print, variable,

Latest Posts

Setting Git author details for a single repo (Git)
Checking Virtual Machine Resource Allocations with Libvirt (BASH)
Rsync over SSH with a custom port (BASH)
Remotely backing up PFsense Configuration (BASH)
FFMPEG: Converting RMVB to X264 MP4 (BASH)
Recursively print table (print_r equivalent) (LUA)
Bulk Delete Comments from (Self-Hosted) JIRA Issues (Misc)
Add a static entry to the ARP table (BASH)
SSL Cipher Hex codes to Human Readable Names (Misc)
Convert Ascii to Binary (BASH)

Copyright © 2019 Ben Tasker | Sitemap | Privacy Policy
Available at snippets.bentasker.co.uk and snippets.6zdgh5a5e6zpchdz.onion