Skip to content

Instantly share code, notes, and snippets.

@Krishna
Created April 22, 2009 14:42
Show Gist options
  • Save Krishna/99829 to your computer and use it in GitHub Desktop.
Save Krishna/99829 to your computer and use it in GitHub Desktop.
vardump for Lua (modified from Lua Gems)
--
-- vardump
-- original verstion by Tobias Sulzenbruck and Christoph Beckmann
-- source: Lua Gems, page 29
-- modifications: Krishna Kotecha
--
--[[
value - the value to dump
key - checked for adding a prefix. Used for printing tables
and for printing out the index of the table cell.
depth - used for indentation
options - a table used to pass in additional information to this function:
options.metatable - a boolean flag used to indicate whether
the current table passed in value is a metatable.
--]]
function vardump(value, depth, key, options)
options = options or {}
local linePrefix = ""
local spaces = ""
-- add a line prefix if necessary...
if key ~= nil then
linePrefix = "["..key.."] = "
end
-- depending on the table depth, add spaces to
-- the front of each line for readability
if depth == nil then
depth = 0
else
depth = depth + 1
for i = 1, depth do
spaces = spaces .. " "
end
end
if type(value) == 'table' then
tableDescription = '(table) '
if options.metatable ~= nil then
tableDescription = '(- metatable) '
end
print(spaces .. linePrefix .. tableDescription)
-- deal with the current table's metatable...
mTable = getmetatable(value)
if mTable ~= nil then
vardump(mTable, depth + 1, nil, {metatable = true})
end
-- now print out the table...
for tableKey, tableValue in pairs(value) do
vardump(tableValue, depth, tableKey)
end
elseif type(value) == 'function'
or type(value) == 'thread'
or type(value) == 'userdata'
or type(value) == 'nil'
then
-- print(spaces .. tostring(value))
print(spaces .. linePrefix .. tostring(value))
else
print(spaces .. linePrefix .. "(" .. type(value) .. ") " .. tostring(value))
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment