Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How can i check if a datastore key doesn't exist already?

Asked by 3 years ago

So I am trying to make a datastore and I am trying to figure out if a datastore key exists or not. When i read about it online it says if i use GetAsync and enter a key that doesnt exist then it will return nil but when i try this code

local datastoreservice = game:GetService("DataStoreService")
local inventory = datastoreservice:GetDataStore('inventory')

print(inventory:GetAsync("aewjrje")) -- Key that doesnt exist

it prints out

  14:08:04.817 - Server - data:4

I am not sure what this means

When I hover over the data it says workspace:data I just want to know if a key exists or not

1 answer

Log in to vote
2
Answered by
imKirda 4491 Moderation Voter Community Moderator
3 years ago
Edited 3 years ago

GetAsync returns void if no result exists. As far as i know that is not intentional and is a bug, however, since in Lua void variables do NOT exist, you can count that as nil and following code will print out true:

print(inventory:GetAsync("arwjrje") == nil)
-- true

If you declare a variable pointing to void then it will be set to nil automatically so this example will print out nil as you expected:

local result = inventory:GetAsync("aewjrje")
print(result)
-- nil

The reason why it printed blank text is because putting void into parameters is like not putting anything in them so your code is basically calling print()

Note when using data stores, it is crucial to use pcall since if the servers are down, your thread is going to break and you won't be able to do anything with that. This function runs given function and stops it if it throws an error without affecting thread that called it.

It returns boolean representing if the function ran without errors and a string as an error message if it errored. If the function did NOT error, it will return boolean as the first value as usual and all next values it will return will be the values that function you passed in returns, in practice you would use it like this:

local success, response = pcall(inventory.GetAsync, inventory)

if success then
    if response then
        -- key exists, response is the retrieved data
    else
        -- key is nil
    end
else
    -- code did not run successfully and threw an error
    warn("Failed to get data: " .. response)
end
Ad

Answer this question