首页 > 解决方案 > For循环不工作?罗布洛克斯工作室

问题描述

代码:

local DataStoreService = game:GetService("DataStoreService")
local InvDataStore = DataStoreService:GetDataStore("InvDataStore")

game.Players.PlayerAdded:Connect(function(player)
    local Id = player.UserId
    
    local Inventory = Instance.new("Folder")
    Inventory.Name = "Inventory"
    Inventory.Parent = player
    
    local Inv = InvDataStore:GetAsync(Id)
    print(Inv)
    print(table.concat(Inv, " "))
end)

game.Players.PlayerRemoving:Connect(function(player)
    local Id = player.UserId
    local InvTable = {}
    
    for i, v in pairs(game.Players:FindFirstChild(player.Name).Inventory:GetChildren()) do
        print("Repear")
        if v:IsA("NumberValue") then
            table.insert(InvTable, v)
            print(v)
        end

    end
    
    print(InvTable)
    print(table.concat(InvTable, " "))
    InvDataStore:SetAsync(Id, InvTable)
end)

输出:

13:25:35.288 - 创建了无标题游戏自动恢复文件 Realism Mod 当前正在运行 v2.09!(x2) 表:0x08cb53598b2d3aa1

表:0xd8ce847b521d4091 1 13:26:26.703 - 从 ::ffff:127.0.0.1|60556 断开

探险家:

它似乎正在跳过这个循环:

for i, v in pairs(game.Players:FindFirstChild(player.Name).Inventory:GetChildren()) do
        print("Repear")
        if v:IsA("NumberValue") then
            table.insert(InvTable, v)
            print(v)
        end

    end

因为它似乎不打印 repear (repeat) OR v (Value) 有谁知道怎么回事?

注意:我不明白的是,它在保存之后和保存之前不打印值,并且忘记了 for 循环。我可以提供额外的东西。

标签: for-loopdebuggingluaroblox

解决方案


它忽略了循环,因为当它到达game.Players:FindFirstChild(player.Name)返回时将为零,因为该玩家刚刚离开服务器。您可以尝试做的是直接从您拥有的播放器对象进行迭代,如果您已经拥有它,则无需查找对象播放器。尝试:

for i, v in pairs(player.Inventory:GetChildren()) do
    print("Repear")
    if v:IsA("NumberValue") then
        table.insert(InvTable, v)
        print(v)
    end
end

在游戏期间而不是在离开时存储数据也是一个好习惯,当玩家离开时所有这些对象也会被删除,最好在游戏期间处理表格并且在玩家移除期间只更新数据存储。另外一个好的做法是每 5 分钟更新一次播放器的数据存储


推荐阅读