Best way to index for a possible "nil" value?

What’s the best way to index a return from a datastore, that could return nil.
Here’s my code.

	local Currency_Cash = Instance.new("IntValue")
	Currency_Cash.Name = Currency
	Currency_Cash.Parent = LeaderStatsFolder
	Currency_Cash.Value = BankData:GetAsync(Player.UserId):WaitForChild("Cash",1) or 0

Tried using :WaitForChild() of course this dident work.
So’ whats the best way to index for this value and if it does not exit then set it to 0 (like in the script).

local Data = BankData:GetAsync(Player.UserId) -- Value or nil

Currency_Cash.Value = Data or 0 -- Data or 0 (if nil, it will pick 0)

if not Data then -- if there is no Data (Alternate: if Data == nil then)
    -- code
end

This wont work, as BankData:GetAsync(Player.UserId) returns a table {Cash=0,Bank=0,BankRep="BloxBank"}
That’s the reason im having this problem to start with.
Because BankData:GetAsync(Player.UserId)['Cash'] could return nil.

You didnt mention your table.

Also:

if Data[index] == nil then
    -- code
end

not that hard.
It should not return nil if The DataStore gave you Data, unless you arent handling your Data properly.

1 Like
	if BankData["Cash"] == nil then
		Currency_Cash.Value = 0 
	else
		Currency_Cash.Value = Currency_Cash.Value
	end
  00:03:44.296  ServerScriptService.RF_Framework.LeaderStatsSystem:25: attempt to index nil with 'Cash'  -  Server - LeaderStatsSystem:25

Because you are indexing the DataStore instead of your Data.

1 Like

:skull::skull::skull:
ohh… yeah…

Time to go to bed…

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