Looping error with tables/dictionaries

Hey, there.
I’m having this issue, where whenever I have a for loop to loop through a table/dictionary, and there is nothing stored in it yet, it will error. Is there any easy fix to this?

Optimally, I’d want it to try and loop and just skip it, as there is nothing to loop through/the table is empty.

Here’s what the loop would look like:

for _, Value in pairs(Data["Pets"]["PetsUnlocked"]) do
end

Here’s what the dictionary/table looks like:

Pets = {
	["MaxEquip"] = 4;
	["MaxStorage"] = 25;
				
	["NumberEquipped"] = 0;
				
	["CurrentPetID"] = 1;
	["TotalEggsOpened"] = 0;
				
	["PetsUnlocked"] = {
					
	};
};

And here’s the error I get:

invalid argument #1 to 'pairs' (table expected, got nil) 

If anyone has a fix, I’d greatly appreciate a post.

If nothing smart is recommended, then I’ll just go ahead and say if table ~= nil then before every loop.

Thanks :slight_smile:

Could you check if the table has at least one pet in it by doing something like this:

if Data["Pets"]["PetsUnlocked"][1] then --check if there is a pet in the table
       for _, Value in pairs(Data["Pets"]["PetsUnlocked"]) do

       end
end
1 Like

Yeah, alright.
That’s what I was going to do, just that there are a lot of loops in my game like that, and they all error, so its a lot of if statements. But I guess I’ll just go the route of doing that.

1 Like

That’s extremely odd. Data.Pets.PetsUnlocked exists and isn’t nil. pairs works just fine on empty tables. If you run across a table that would make your pairs error and you try to do

if Data["Pets"]["PetsUnlocked"][1] then

to it, then that will error as well, because you’d still be doing nil[1].
It must be that Data.Pets.PetsUnlocked just doesn’t exist and wasn’t added to the table, or there is a typo, or you are using the wrong table.

1 Like

Oh, well I’ll look into. Never had this error before aswell.