Printing Contents of a Table in Lua

In other programming languages, you can use functions like print_r() in php to display the information stored in a table (known as an array in php). Lua doesn’t have a function like print_r() and you have to get a bit creative to print out the contents of a table.

For example, let’s say you have a table that stores the different suits in a deck of cards: local cards = {“heart”,”spades”,”clubs”,”diamonds”}. You can use a for loop to print out the contents of the table, or you can use table.concat(). Here’s how:

local cards = {"heart","spades","clubs","diamonds"}
print("Print contents: ",table.concat(cards))

This will print out the contents of the table cards and the output will look like this: Print contents: heartspadesclubsdiamonds. Unforunately, this isn’t very helpful as the contents are one long word.

To address this, you can pass in a parameter that will separate the contents. Here’s how to use the parameter:

local cards = {"heart","spades","clubs","diamonds"}
print("Print contents that are readable: ",table.concat(cards,", "))

The output for this print statement is Print contents that are readable: heart, spades, clubs, diamonds. This is easier to read and you can use the pipe character, dash, or something else to display the contents. You can also pass the index numbers if you’d like to see a few of the elements.

This approach is perfect for smaller tables that have a limited amount of content. If you’re like me, you like to see the code in one bunch. For those of you that do, here’s the full set of code:

local cards = {"heart","spades","clubs","diamonds"}

-- This will print the contents of the cards table
print("Print contents: ",table.concat(cards))
-- Output: Print contents: heartspadesclubsdiamonds

-- Separate the contents with a comma
print("Print contents that are readable: ",table.concat(cards,", "))
-- Output: Print contents that are readable: heart, spades, clubs, diamonds

-- Print out index 2 and 3
print("Print index 2 and 3: ",table.concat(cards,", ", 2,3))
-- Print index 2 and 3: spades, clubs

Thanks for reading!

Daniel Williams

Leave a Reply

Your email address will not be published. Required fields are marked *