data = datastore:GetAsync(userId) if data == nil or data == {} then newkey(userId) print("Added user "..userId.." to the index.") loginfo("Added "..userId.." to KEY_INDEX at "..os.time()) --More stuff else for key, value in pairs(data) do print(key, "=", value) --It doesn't print anything, so it must be an empty table. end datastore:SetAsync(userId, data) print(userId.." logged on.") --This happens loginfo(userId.." logged on at "..os.time()) end
I'm using Crazyman32's DataStore Editor to watch my data. I keep clearing it before I test. It's supposedly just an empty table. It looks like this. However, for whatever reason, it says that I logged on. That means that the table is not empty. What am I doing wrong here?
Well, a few things here.
1: You're comparing an empty table, to another empty table. However, you're actually comparing 2 different tables so that will always return false
print({} == {}) -- > false (2 different tables created)
And our empty table isn't nil, so your if statement returns false for both logical operations, which brings us to the the "else" statement. What you wanna do, is check if there's a table, and then check that table and see if anything's inside of it. We can do this easily with the "next" function:
local t = {} print(next(t)) -- > "nil" t[1] = "test" print(next(t)) -- > 1 test
So this would be our revised code:
data = datastore:GetAsync(userId) -- Making it so if the data is nil, or if it's not nil but it's an empty table, then... if data == nil or (type(data) == "table" and not next(data)) then newkey(userId) print("Added user "..userId.." to the index.") loginfo("Added "..userId.." to KEY_INDEX at "..os.time()) --More stuff else for key, value in pairs(data) do print(key, "=", value) --It doesn't print anything, so it must be an empty table. end datastore:SetAsync(userId, data) print(userId.." logged on.") --This happens loginfo(userId.." logged on at "..os.time()) end
Let me know if you have any questions, hope it helped.