Eduard Palade
Eduard Palade

Reputation: 1

I just started coding in lua-roblox, and I face attempt to index nil with 'Value, and can't find out why

So I just started Lua in roblox and I can't find out why am I facing this error (code below)

Workspace.Script:11: attempt to index nil with 'Value'

game.Players.PlayerAdded:Connect(function(player)
    local stats = Instance.new("Folder", player)
    stats.Name = "leaderstats"
    currency = Instance.new("IntValue", stats)
    currency.Name = "oil"
    currency.Value = 100
    return 0
end)

while true do
    currency.Value = 100+10 -- here would be the problem
    wait(5)
end

Upvotes: 0

Views: 404

Answers (3)

DennyLua
DennyLua

Reputation: 1

You are referencing a object that doesn't exist. The 'Currency' object is nil basically, to fix it basically put the while true loop in it. It shows the error if you index (go to a object using a period).

Fixed Code

game.Players.PlayerAdded:Connect(function(player)
    local stats = Instance.new("Folder", player)
    stats.Name = "leaderstats"
    currency = Instance.new("IntValue", stats)
    currency.Name = "oil"
    currency.Value = 100
    return 0

   while true do
    currency.Value = 100 + 10 -- Should be here
    wait(5)
end

end)

Upvotes: 0

d x
d x

Reputation: 112

You would want to put the while true loop inside of Players.PlayerAdded to have it work well.


Side Note: Instead of using

local stats = Instance.new("Folder", player)

you should use

local stats = Instance.new("Folder")
stats.Parent = player

as this runs much faster.

Upvotes: 1

aschepler
aschepler

Reputation: 72271

The PlayerAdded:Connect(function ... end) means you're setting up a function now to be called later when a player joins the game. It doesn't get run right away.

Immediately after that, the script goes to your while loop. But currency hasn't been set to anything yet, so its value is just nil, making currency.Value invalid.

Also, you have the currency global variable set whenever a player joins. Meaning if it is set, it will be the statistic value for the last one player to join, and any code outside the PlayerAdded callback would only be changing things for that one player.

Upvotes: 0

Related Questions