I'm learning Lua for about a week now and I've built (I hope) a function to print any type in Lua. As I'm new to Lua I don't quite understand:
- if there is a more succinct way to achieve this
- if there is a standard way to print nested tables
- if there are any cases the function doesn't cover
function printAnyLuaType(AnyLuaType, identationSpaces, identationLevel)
function printTable(tableToPrint)
--recursively print a table indenting
for index, value in pairs(tableToPrint) do
depperIdentation = currentIdentation .. identationToAppend
if type(value) == 'table' then
print(currentIdentation .. index)
currentIdentation = depperIdentation
printTable(value) --call to function
else
print(currentIdentation .. index)
print(depperIdentation .. value)
end
end
shallowerIdentation = string.sub(currentIdentation, 1, #currentIdentation - identationSpaces)
currentIdentation = shallowerIdentation
end
--globals for printTable
AnyLuaType = AnyLuaType or ''
identationSpaces = identationSpaces or 4
identationLevel = identationLevel or 0
identationToAppend = string.rep(' ', identationSpaces)
currentIdentation = string.rep(identationToAppend, identationLevel)
--recursively printTable or normal print
if type(AnyLuaType) == 'table' then
printTable(AnyLuaType)
else
print(AnyLuaType)
end
end
tableToPrint = {1234, {'a','b','c'}, 5678, ['complains'] = {'ugly', 'fragile'}, {['name'] = 'smith', ['age'] = 10}}
printAnyLuaType(tableToPrint)
--[[
expected output:
1
1234
2
1
a
2
b
3
c
3
5678
4
age
10
name
smith
complains
1
ugly
2
fragile
--]]
```
tconstructed by the following script:t={}; t[1]=t; printAnyLuaType(t). There is an explanation in the "PiL" book on how to process tables with cycles. \$\endgroup\$