Skip to content

Instantly share code, notes, and snippets.

@HallexCosta
Created October 9, 2021 21:05
Show Gist options
  • Save HallexCosta/03dfc7ed6a8baaae7eaa50fb1e1f0587 to your computer and use it in GitHub Desktop.
Save HallexCosta/03dfc7ed6a8baaae7eaa50fb1e1f0587 to your computer and use it in GitHub Desktop.
Debug Dictornary for Lua
function count(table)
local size = 0
for k, v in pairs(table) do
size = size + 1
end
return size
end
function get_last_key(table)
local last_key
for k, v in pairs(table) do
last_key = k
end
return last_key
end
function verify_have_table(tbl)
for k, v in pairs(tbl) do
if type(v) == 'table' then
return true
end
end
return false
end
function debug(table, plain_table, amount_spaces, close_internal_tbl)
local amount_spaces = amount_spaces or 2
local first_element = 1
local last_element = count(table)
local last_key = get_last_key(table)
local have_table = verify_have_table(table)
local text = '{\n'
if plain_table then
text = plain_table
end
--print('PLAIN TABLE', plain_table)
for k, v in pairs(table) do
local spaces = string.rep(' ', amount_spaces)
if type(v) == 'table' then
have_table = true
local start_new_tbl = string.format('%s\n%s%s = {\n', text, spaces, k)
--text .. '\n' .. k .. ' = {\n'
print(start_new_tbl )
debug(v, start_new_tbl, amount_spaces + 2, true)
--text = string.format('%s = %s', k, text)
--print(string.format('%s%s = %s', spaces, k, v))
else
have_table = false
last_element = get_last_key(table)
if first_element == 1 then
first_element = 0
text = text .. string.format('%s%s = %s,', spaces, k, v)
else
local indent_close_tag = string.rep(' ', amount_spaces - 2)
if last_element == count(table) then
local close_tbl = '}'
last_element = 0
text = text .. string.format('\n%s%s = %s\n%s%s', spaces, k, v, indent_close_tag, close_tbl)
else
local close_tag = ','
print(have_table)
print(get_last_key(table), verify_have_table(table))
if close_internal_tbl then
close_internal_tbl = false
text = string.format('%s\n%s%s = %s,', text, spaces, k, v)
else
text = string.format('%s\n%s%s = %s\n%s}', text, spaces, k, v, indent_close_tag)
end
end
end
end
end
if have_table == false then
text = string.format('%s', text)
--print(text)
end
return true
end
local UserAddress = { street = "Tokyo Kyoko", number = 461, country = 'Brazil' }
local User = { name = 'Hállex', age = 19, address = { teste = 1}}
debug(User)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment