Practical examples for tables other than datastores

Hello! It has been around 2 weeks of my journey in Lua and I am now trying to digest tables. My style of learning mostly revolves around editing preexisting scripts and experimenting them out. However, I fail to find any good practical examples of tables other than mere skeletons of tables that require heavy editing for it to work as a game mechanic or just simple tables i. e

local myTab = {"Apples", "Bananas"}
print(myTab[1])

It is also frustrating when people keep telling me to use tables to make i.e inventory systems instead of using the one I created without tables which is old-fashioned and inefficient. It is hard for me to learn tables… so does anyone have any working scripts that is practical for a game to share with me? It would be greatly helpful and much appreciated!

I use tables probably in like… every script I create. I’ll give a few examples, since I feel like the scripts that tutorials will show you (like local MyTable = {“word”,123,“cool!”} are never how tables are actually used.

Example 1: In a time-round-based game, I could have a table “CurrentPlayers” which holds all the players who are in the game at the time. Whenever a player dies, they are removed from “CurrentPlayers.” Then, once the timer runs out, every player left in the table will be a winner and I can use a for i, v in pairs() loop to grant them all some sort of prize like xp or coins.

Example 2: An in-game music player which holds a table of sound IDs. The music player will do a table[math.random(1,#table)] to select a random ID and then will play it. Once the song stops playing, the script will repeat itself and continue this cycle forever.

Example 3: A user just had me script this for her: a table which stores a list of UserIds, and any player whose UserId is in that table will receive certain items from a folder in lighting. To do this, you’d simply use for i, v in pairs(table) and then check if v == player.UserId (wrapped in player.CharacterAdded)

Example 4: A hangman game (oh, would you look at that, I have a hangman game) which stores a bunch of words in a table. Those words are randomly selected from when a player clicks “start,” and it will become the word that they are trying to guess in hangman.

Hopefully these examples give a more practical look at tables. They’re super useful.

3 Likes

Thank you for the examples and thankfully they are easy examples for me to try recreate! I hope that there are more people who are willing to give more examples especially something related to GUIs or Instances in workspace i.e bricks. Thanks anyway!

I use it for OOP, basically to organize similar functions in a table. For example,

Car = {}

function Car:Destroy(this)

bla bla

end

function Car:Start()
bla bla bla

end