Unable to index values inside of nested tables

Hi! I have been trying to make an item saving system that saves the amount of an item that a player has. The problem is, whenever I try to load the amount of a specific item, it returns as nil.

Here is the code that I have written:

--The ModuleScript that contains the saving function
local savingItems = {}
savingItems.__index = savingItems

function savingItems.itemSave(player)
	local save = setmetatable({}, savingItems)
	local playersItems = player.plrStats.Items:GetChildren()
	--
	save.savedItems = {}
	
	for i, v in ipairs(playersItems) do
		local assignItem = {[v.Name] = {amount = v.Amount.Value}}
		table.insert(save.savedItems, assignItem) --Assigns name and amount of item the player has
	end
	return save
end

return savingItems
--End of module script

--Table that contains the data
local savedItems = saveModule.itemSave(player) --Calls ModuleScript function and returns metatable with saved data

local data = {
     items = savedItems.savedItems --Saves the saved data table
}

--Loads the data
if data.items then
	for i, v in ipairs(data.items) do
		local currentItem = table.find(items:GetChildren(), v) --items is a folder that gets cloned inside the player with the items, this is attempting to match the item in the datasave with the cloned item in the folder
		print(currentItem) --should print the current item indexed in the "items" folder, but returns `nil`
	end
end

table.find tries to find v in a table of instances.
The problem is that v is not an instance, so it can’t find it and returns nil.

PS:
Your data layout is strange, with each item being represented by a table with a single key (its name).

If you want to use the name as the index for the item itself (rather than as a key inside the item table), you should do something like this:

	for i, v in ipairs(playersItems) do
		save.savedItems[v.Name] = {amount = v.Amount.Value}
	end
1 Like

This works, the only thing I’m noticing though is that for some reason the ipairs loop won’t run in the loading script:

if data.items then
	print("items found") --Prints this
	for i, v in ipairs(data.items) do
		print("ran loop") --Does not print this
	end
end

try removing the ipairs so its just

for i, v in data.items do
	print("ran loop") --Does not print this
end

I changed ipairs to pairs and it worked, I’m going to quickly test to make sure everything works how I want it to.

This is because ipairs iterates through the numeric key-value pairs of a table, you would need to use next or pairs as you’re using non-numeric keys. Learn more about iterators here, here and here.

Though, as @Blumaimn2 stated: you are now able to omit the iterator after Luau changes back in 2022, discussed here.

2 Likes

I tested it and everything works how I want it to, thank you both for your help!

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.