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