Created
September 8, 2012 12:39
-
-
Save reefwing/3674519 to your computer and use it in GitHub Desktop.
Tutorial 16 - Table to String & String to Table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--# ToString | |
-- | |
-- 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 from www.seclists.org/nmap-dev/2008/q4/550 | |
function ToString(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("Error: unknown data type: %s", type(data)) | |
end | |
return str | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment