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
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.