Using recursive functions to return a table visualized as a string in Lua

Trying to print a table in Lua will give you something like table: 1x0324421.

So, you need a function that can turn a table into a string to be able to print it. However, you can’t just loop through all of the values of a table and print them — what if there are sub-tables? This is where recursion comes in useful.

This function takes a table and returns it as it would appear in code.

Here’s how it works:

  1. Since every table starts with a “{“, this is the start of the returned string.
  2. After this, every value is looped through. If it’s a value (string/number) it’s appended to the return string, with its index if it’s not a number (numbers are considered to be automatic indices).
  3. If it’s a table, then it needs to be displayed as one, so instead of appending the value, we need a table displayed as string. Funnily enough, we have just the function to do that — we recursively call the tableAsString function with the table that needs to be a string as the parameter. If that table contains more tables, they will be dealt with recursively.
  4. Before the string-ified table is appended to the main return string, it has its index prepended if its not a number (again, we’re considering numbers to be automatic indices).
  5. Finally, before closing the table, any trailing commas are removed.
Like what you read? Give J T a round of applause.

From a quick cheer to a standing ovation, clap to show how much you enjoyed this story.