Need help with looping through a table

I want to know how to loop through a data store table and check if the item passed through is equal to the item inside the table. If it is then it would return true but if not false. The problem is that it works the first time by returning true since the item i pass through should be in the table, however, the next time i pass another item through it compares the value from the previous loop in the table with the new item i want to check. I know this seems tedious but it’s kinda of hard to explain.

Here’s my code:

function CheckTool(player,item)
 
	local TableofTools = dataStore:GetAsync("User-"..player.UserId) -- table of values
	if TableofTools then
		for _,v in pairs(TableofTools) do
			if v == item then -- checks if the value inside is equal to the item i sent
				return true -- works the first time
			else
				return false -- second time this happens because it compares the last value with a  -- new item
			end
		end
	else
		return false
	end
end

I haven’t tried any fixes yet since i have no idea why this happens.

You can’t save tables, you can only save strings. You will have to use HTTPService:JSONDecode() and HTTPService:JSONEncode() to convert tables to strings and vice versa.

Edit : Also, you can’t save instances in data stores.

1 Like

How can’t you save tables when i already have? Also i save a string not an instance, it’s just named “tool”

Are you sure it really saved? Datastores really can only save strings.

1 Like

I’ve solved it. Most of the returns were redundant so i only used 1 return.


function CheckTool(player,item)
 
	local TableofTools = dataStore:GetAsync("User-"..player.UserId)
	if TableofTools then
		for _,v in pairs(TableofTools) do
			if v == item then
				return true
			end
		end
	end
end

To check if the player owns a tool i simply do if CheckTool(player,item) then and if they don’t own it then elseif not CheckTool(player,item).

1 Like

Yes I’m sure it’s saved. Thanks for the help anyways!

I know you already fixed it but I’ll explain what was the mistake (and send a better version of the code)
in the if statement where it checks if the item is equal to the value u will return true or return false, what u should do is return true if it equals or return false after the loop is done.

function _checkTool(player, item)
	local tableOfTools = dataStore:GetAsync("User-"..player.UserId) or {}

	for _, v in pairs(TableofTools) do
		if v ~= item then continue end

		return true
	end

	return false
end

I changed the function name so make sure to change the line where you call it or copy what’s inside only.

2 Likes

I appreciate your reply, I’ve never gotten an error like this using for loops before so it was quite confusing. Thank you regardless!

1 Like

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