When making RPG games, most if not all of them include an inventory system that works like this:
Let's say there are 3 items. each labeled Item1
,Item2
and Item3
.
Now, if I were to remove Item2
, then Item3
would slide into the position of Item2
and Item2
would be equipped.
By observing other scripters and developers, I found that I would have to use a table to conduct such things. I have no experience in making tables, all I do know is that a table contains values that can be summoned with TableName.value
. I also do know that you have to summon a table with curly brackets ({,}).
Sorry if it's hard to read, but I'm really desperate. Can anyone show me examples of a table and how I would use it to create an inventory system?
Regards, Your pal Sensei_Developer.
Hey Sensei_Developer
This is a really interesting question you've asked.
What I would do is, have a server script;
1 | local data = { } -- create a table, and name it 'data' |
2 |
3 | game.Players.PlayerAdded:Connect( function () -- player added event. |
4 | data [ plr.Name ] = { "Starting Weapon" , "Another Weapon" } -- create a new table inside of the 'data' table, name it after the player's name, and give them a weapon. |
5 | print (data [ plr.Name ] [ 1 ] ) -- Would print > 'Starting Weapon' |
6 | print (data [ plr.Name ] [ 2 ] ) -- Would print > 'Another Weapon' |
7 | end ) |
So with this code, there are multiple things you can do, I'll list a few!
Use Datastore service, to load and save. (Check for data else give them starting weapon) Fire the client, to update their inventory. Using remove events.
To add a weapon:
1 | table.insert(data [ plr.Name ] , #data [ plr.Name ] + 1 , "Hello" ) -- will insert hello, to position two in the players table. |
2 | print (data [ plr.Name ] [ 3 ] ) -- Would print > 'Hello' |
To remove a weapon:
1 | function getIndex(tbl, weaponName) -- new function named, getIndex. |
2 | for i,v in pairs (tbl) do -- for loop, to iterate though the table |
3 | if v = = weaponName then -- if the weaponName = the current iteration value |
4 | return i -- return the index of 'weaponName' |
5 | end |
6 | end |
7 | end |
8 |
9 | table.remove(data [ plr.Name ] , getIndex(data [ plr.Name ] , "Starting Weapon" )) -- Would remove the starting Weapon. |
I hope this has helped you a little.
I am fairly new to tables myself, but I hope this helped
Please feel free to comment back, alternatively contact me on discord, and let me know who you are. Invoke_Client#0100