I’m trying to set the value of a object value to either the data in a datastore or a regular value if that data isn’t found. The issue is that the script seems to break when the data isn’t present. What I mean by this, is that if I have
Object.Value = MyData.money or 100
The script will break if “MyData” is a nil, as far as I know, if MyData is a nil, and there’s an “or” statement next to it the script should set the value to 100.
My code:
local id = Player.UserId
local key = id
local data = DataStore:GetAsync(key)
local PlayerStats = script.Stats:Clone()
PlayerStats.Parent = Player
PlayerStats.Health.Value = data.Health or 100
PlayerStats.HealthRegen.Value = data.HealthRegen or 0.7
PlayerStats.Money.Value = data.Money or 50
PlayerStats.WalkSpeed.Value = data.WalkSpeed or 13
Would really appreciate it if anyone is able to clear up this situation.
You are indexing a value that doesn’t exist, or nil. You had the second part of the code handled right, but Lua and many other languages will error if you try to index anything other than a table.
Add or {} next to the data variable definition.
local id = Player.UserId
local key = id
local data = DataStore:GetAsync(key) or {} -- This is where the "or {}" would go to.
local PlayerStats = script.Stats:Clone()
PlayerStats.Parent = Player
PlayerStats.Health.Value = data.Health or 100
PlayerStats.HealthRegen.Value = data.HealthRegen or 0.7
PlayerStats.Money.Value = data.Money or 50
PlayerStats.WalkSpeed.Value = data.WalkSpeed or 13
local id = Player.UserId
local key = id
local data = DataStore:GetAsync(key)
local PlayerStats = script.Stats:Clone()
PlayerStats.Parent = Player
PlayerStats.Health.Value = data and data.Health or 100
PlayerStats.HealthRegen.Value = data and data.HealthRegen or 0.7
PlayerStats.Money.Value = data and data.Money or 50
PlayerStats.WalkSpeed.Value = data and data.WalkSpeed or 13