我刚开始用lua-roblox编码,我试图用'Value'索引nil,但找不到原因



所以我刚刚在roblox中启动了Lua,我不知道为什么我会面临这个错误(下面的代码(

工作区。脚本:11:尝试用'Value'索引nil

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

您可能希望将while true循环放入Players.PlayerAdded中,以使其正常工作。


旁注:不使用

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

你应该使用

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

因为它跑得更快。

PlayerAdded:Connect(function ... end)意味着您现在正在设置一个函数,以便稍后玩家加入游戏时调用。它不会马上逃跑。

之后,脚本立即进入while循环。但是currency还没有被设置为任何值,所以它的值只是nil,使得currency.Value无效。

此外,每当玩家加入时,都会设置currency全局变量。这意味着,如果设置了它,它将是最后一个加入的玩家的统计值,而PlayerAdded回调之外的任何代码都只会改变这一个玩家的情况。

您正在引用一个不存在的对象。Currency对象基本上是nil,为了修复它,基本上在其中放入while true循环。如果你索引(使用句点转到对象(,它会显示错误。

固定代码

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)

最新更新