How to make a table within a table?

I’m trying to make it so that I have information stored within the item of a table, something like this:

local parts = {
	["Part1"] = {
		["ID"] = 1;
	};
	
	["Part2"] = {
		["ID"] = 2;
	};
}

This is my current script, but I do not know what the problem is, I keep getting the error “attempt to index nil with ‘ID’”. This is the solution I found on the devforum instead of using table.insert, but it does not seem to help.

local parts = {}

for i, v in pairs(game.Workspace.Parts:GetChildren()) do
	table.insert(parts, i, v.Name)
	parts[v.Name]["ID"] = v.PartID.Value

	print(parts)
end 

u doing
parts[v.Name][“partID”]
but in the table its not partID it’s just ID

Yeah I know, forgot to change that on my post.

the problem is that parts[v.Name] does not exist yet when you try to set partID. Insert uses numerical indexing I think so that’s why your attempt didn’t work

The fix is something like this:

local parts = {}

for i, v in pairs(game.Workspace.Parts:GetChildren()) do
	if parts[v.Name] == nil then -- check if there is no entry for the part already
		parts[v.Name] = {} -- make an empty portion of the dictionary
	end
	--fill the dictionary:
	parts[v.Name]["ID"] = v.PartID.Value

	print(parts)
end
2 Likes

Thanks! Do you know how I would save and load this with a datastore?

Well that’s a big question but DataStoreService:GetAsync(key) and :SetAsync(key) both can store tables/dictionaries directly so it wouldn’t be difficult. Can’t really go in to too much detail without a little bit more info

2 Likes

Could I just do something like

local httpService = game:GetService("HttpService")

local data
local success, errormessage = pcall(function()
	data = partsDS:GetAsync(plr.UserId..httpService:JSONDecode(idkwhattoputherelol))
end)

if success then
	for i, v in pairs(#idkthetablelol) do
		game.ServerStorage.Parts:FindFirstChild(v.ID):Clone()
	end
else
	warn(errormessage)
end

Not too sure about some things. I would most likely use a JSON encode and decode for the table.

2 Likes