I’m trying to make it so that I can print out a table in a way where the output is valid lua code for initializing a table with the same contents. ie:
for
foo = {
{ 6, 1, true },
{ 4, 2, { 5, 1, { 4, 3, "all" } } },
{ 3, 3, "all" },
{ 6, 4, "every2" },
{ 4, 5, "every3" },
{ 2, 6, "every4" },
{ 8, 7, "random" },
{ 9, 8, "long" }
}
running
tprint(foo, "foo")
prints (tabbing/whitespace doesn’t need to be exactly the same)
foo = {
{ 6, 1, true },
{ 4, 2,
{ 5, 1,
{ 4, 3, "all" }
}
},
{ 3, 3, "all" },
{ 6, 4, "every2" },
{ 4, 5, "every3" },
{ 2, 6, "every4" },
{ 8, 7, "random" },
{ 9, 8, "long" }
}
I have a recursive solution figured out for printing out the values based on indexing, but that only works if the table has been initialized with the same number of contents. Spent more time than I’m willing to admit trying to figure this out, but it’s stumped me. Anyone have the desire to solve this programming puzzle?
My current solution:
foo = {
{ 6, 1, true },
{ 4, 2, { 5, 1, { 4, 3, "all" } } },
{ 3, 3, "all" },
{ 6, 4, "every2" },
{ 4, 5, "every3" },
{ 2, 6, "every4" },
{ 8, 7, "random" },
{ 9, 8, "long" }
}
tprint = function(t, n, _k)
n = n ~= nil and n or 'n'
if type(t) == 'table' then
for k,v in pairs(t) do
if _k ~= nil then
k = '\t' .. _k .. '[' .. k .. ']'
if type(v) == 'table' then
-- print(k .. ' is a table')
end
else
k = n .. '[' .. k .. ']'
-- print(k .. ' is a table')
end
tprint(v, n, k)
end
else
t = type(t) == 'string' and '"' .. t .. '"' or t
print(_k .. ' = ' .. tostring(t))
end
end
tprint(foo, "foo")
-- outputs
foo[1][1] = 6
foo[1][2] = 1
foo[1][3] = true
foo[2][1] = 4
foo[2][2] = 2
foo[2][3][1] = 5
foo[2][3][2] = 1
foo[2][3][3][1] = 4
foo[2][3][3][2] = 3
foo[2][3][3][3] = "all"
foo[3][1] = 3
foo[3][2] = 3
foo[3][3] = "all"
foo[4][1] = 6
foo[4][2] = 4
foo[4][3] = "every2"
foo[5][1] = 4
foo[5][2] = 5
foo[5][3] = "every3"
foo[6][1] = 2
foo[6][2] = 6
foo[6][3] = "every4"
foo[7][1] = 8
foo[7][2] = 7
foo[7][3] = "random"
foo[8][1] = 9
foo[8][2] = 8
foo[8][3] = "long"