Improve table formatting

Current implementation of table formatting uses `string.gsub` on the result to fix formatting (collapse empty tables, etc). That can corrupt it if the table contains certain strings. It also sometimes did not collapse empty tables as last values of other tables, and could format a table with `false` key as empty. There were some code repetitions there as well which I removed.