我在 Roblox Studio 中收到数据存储错误,导致我的数据存储失败。我已启用工作室对 API 服务的访问权限

问题描述 投票:0回答:1

我制作了这个简单的数据存储脚本,该脚本应该加载数据存储并将值添加到您的 Leaderstats 中。它在第 29 行失败,该行已在脚本中标记。我做错了什么?

local dts = game:GetService("DataStoreService")
local money = dts:GetDataStore("Currency-0")



--Currency is set up like this:

--{CASH, GEMS}

--It is a table storing both values.


game.Players.PlayerAdded:Connect(function(plr)
local model = Instance.new("Model") -- lets set up our leaderstats!
    model.Name = "leaderstats"
    model.Parent = plr
local moneyValue = Instance.new("IntValue")
    moneyValue.Name = "Cash"
local gemValue = Instance.new("IntValue")
    gemValue.Name = "Gems"
    
local key = "USER_" .. plr.Name .. "_" .. plr.UserId -- advanced player key

local storedCash -- setting up a variable
local success, err = pcall(function()
    storedCash = money:GetAsync(key)
end)
if success then
    moneyValue.Value = storedCash[1] -- this is the line that messes up
    gemValue.Value = storedCash[2]
    -- we've set that, now we must make it show
    moneyValue.Parent = model
else
    moneyValue.Value = 0
    gemValue.Value = 0
    money:SetAsync(key, {0, 0}) 
end
end)

我的错误::29:尝试索引本地“storedCash”(零值)

我制作了一个简单的数据存储脚本,它应该将值添加到leaderstats中。但是第29行显示错误,我做错了什么?

lua syntax-error game-development roblox-studio
1个回答
1
投票

这不是使用until 语句的方式。您的 wait 语句是在说“如果

wait(5)
不返回任何内容”,这与使用 while 条件一样,都是对 Until 语句的严重滥用。这也不利于可读性。

这就是我会做的:

local success, result do
    repeat
        success, result = pcall(money.GetAsync, money, key)
        if not success then
            wait(5)
        end
    until success or MAX_RETRIES

关于

MAX_RETRIES:
的注释是一个占位符,说明您应该添加重试上限。重复调用这个函数是对
DataStores
的不好使用。它将创建一个永远运行的循环,直到
DataStores
返回 true,如果
DataStores
关闭或调用不成功,这可能会导致问题。我不确定为什么你要使用带有数据的循环语句。

这里的简单响应就是进行错误处理。如果键中没有数据(然后

GetAsync
返回 nil),您将处理这种情况而不是进行循环。

local success, result = pcall(money.GetAsync, money, key)
if success then
    if result then
        -- Data non-nil
    else
        -- Data nil
    end
else
    -- Success false, do something about it
end
© www.soinside.com 2019 - 2024. All rights reserved.