Help with tables and how to add keys?

Hello, developers!

I am currently trying to learn tables. But I need a little bit of help.

As you see, there is a sample table here:

_G.playerTable[player.Name] = {
		TableID = tostring(_G.playerTable),
		Hunger = 0,
		Health = 100,
		Stamina = 100,
		Inventory = {
			Items = {
				["Apple"] = {
					["Amount"] = 1,
					["InventoryDetails"] = {
						["Length"] = 1,
						["Width"] = 1,
						["Rotation"] = 90
					},
					["DecalID"] = "rbxassetid://9797089440"
				},
				["Banana"] = {
					["Amount"] = 3,
					["InventoryDetails"] = {
						["Length"] = 2,
						["Width"] = 1,
						["Rotation"] = 0
					},
					["DecalID"] = "rbxassetid://14334702049"
				},
				["M16A1"] = {
					["Amount"] = 1,
					["InventoryDetails"] = {
						["Length"] = 6,
						["Width"] = 2,
						["Rotation"] = 90
					},
					["DecalID"] = "rbxassetid://5788786001"
				}
			}
		}
	}

I was thinking, that if i needed to add a key to that table with a value, using functions, how could one do that? Eg. if i want to add a key called “Orange” to a path like “[Inventory][Items]” with the value of 1?

So, it should look like [“Player”][“Inventory”][“Items”][“Orange”] = 1! But i really don’t know how to do it.

Thanks for reading, hope you understand because this is my first post :grinning:

Either of these work

playerTable.Player.Inventory.Items["Orange"] = 1
playerTable["Player"]["Inventory"]["Items"]["Pineapple"] = 2
1 Like

Yeah, you’re on the right path, but how could one do it with functions? :thinking:

If i wanted to add an item called “Orange” to a custom path in the table, like [“Player”][“Inventory”][“Items”] with a value of 3? Not that it has a hardcoded path, but something that could add it to a custom path with a function?

Thanks!

local function UpdateTable(place, item, value)
    place[item] = value --place can be Inventory, or items, or player... Item is the new item made, and value is the value of it
end

print(UpdateTable(playerTable["Player"]["Inventory"]["Items"], "Watermelon", 10))
1 Like

Dude, spot on! Thanks!

30charrrrrrrrrr

1 Like

I’m glad I’ve solved your problem! Any more helps, contact Devforum!

1 Like