Nmap Development mailing list archives

[Lua] printing a table


From: Ron <ron () skullsecurity net>
Date: Sat, 22 Nov 2008 18:51:25 -0600

Hi all,

The newer methods I'm writing are modelled after the interface that
Microsoft uses for the RPC calls. Unfortunately, this often means that
the important data is 3 or 4 structs down. I was giving myself a
headache trying to remember where everything goes, so I threw together a
quick function to print out everything in a table:

--
---Converts an arbitrary data type into a string. Will recursively convert
-- tables.
--
--@param data   The data to convert.
--@param indent (optional) The number of times to indent the line. Default
--              is 0.
--@return A string representation of a data, will be one or more full
lines.
function to_string(data, indent)
    local str = ""

    if(indent == nil) then
        indent = 0
    end

    -- Check the type
    if(type(data) == "string") then
        str = str .. (" "):rep(indent) .. data .. "\n"
    elseif(type(data) == "number") then
        str = str .. (" "):rep(indent) .. data .. "\n"
    elseif(type(data) == "boolean") then
        if(data == true) then
            str = str .. "true"
        else
            str = str .. "false"
        end
    elseif(type(data) == "table") then
        local i, v
        for i, v in pairs(data) do
            -- Check for a table in a table
            if(type(v) == "table") then
                str = str .. (" "):rep(indent) .. i .. ":\n"
                str = str .. to_string(v, indent + 2)
            else
                str = str .. (" "):rep(indent) .. i .. ": " ..
to_string(v, 0)
            end
        end
    else
        print_debug(1, "Error: unknown data type: %s", type(data))
    end

    return str
end
--
Does anybody know if there's an easier (or built-in) way to do this?

I put this code in stdnse for now, on my branch at least.
-- 
Ron Bowes
http://www.skullsecurity.org/

_______________________________________________
Sent through the nmap-dev mailing list
http://cgi.insecure.org/mailman/listinfo/nmap-dev
Archived at http://SecLists.Org


Current thread: