我如何检查玩家是否已经在另一个 table/room 中? - Lua

How can I check if a Player is already in another table/room? - Lua

我有一个名为:Rooms 的 table/dictionary,当客户想要加入房间时,我检查房间 UID 是否匹配:Rooms[i]["UID"] == Data,如果 UID 匹配,我检查是否玩家已经在房间里,如果不在,我会将玩家添加到他们想要加入的特定房间,但我遇到了一些问题。

local Rooms = {
    [1] = {
        ["Name"] = "test1",
        ["Players"] = {},
        ["UID"] = game:GetService("HttpService"):GenerateGUID(true)
    },
    [2] = {
        ["Name"] = "test2",
        ["Players"] = {},
        ["UID"] = game:GetService("HttpService"):GenerateGUID(true)
    }
}
RemoteEvent.OnServerEvent:Connect(function(Player, Key, Data)
    if Key == "Join" then
        for i = 1, #Rooms do
            if Rooms[i]["UID"] == Data then
                if #Rooms[i]["Players"] > 0 then
                    for a = 1, #Rooms[i]["Players"] do
                        if Rooms[a]["Players"][a] == Player then
                            print("You are already in the room")
                        else
                            RemoteEvent:FireClient(Player, "Success")
                            table.insert(Rooms[a]["Players"], Player)
                        end
                    end
                else
                    RemoteEvent:FireClient(Player, "Success")
                    table.insert(Rooms[i]["Players"], Player)
                end             
            end
        end
    end
end)

现在的问题是我的代码让玩家加入了两个房间。例如:玩家加入房间 [1] 并尝试再次加入房间 [1],它打印:You are already in the room;这是完美的工作! 但问题是,当玩家想要移动到房间 [2] 时,它不会检查玩家是否已经在另一个房间。

TL;DR:

玩家不应该加入房间[2],因为他们还没有离开房间[1],但是我如何检查玩家是否在不同的房间?

试试这个:

RemoteEvent.OnServerEvent:Connect(function(Player, Key, Data)
    if Key == "Join" then
        local targetRoomNum = nil
        for i, room in pairs(Rooms) do
            if room["UID"] == Data then
                targetRoomNum = i
            end

            for _, playerInRoom in pairs(room["Players"]) do
                if playerInRoom == Player then
                    print("You are already in a room")
                    return
                end
            end
        end
        
        if targetRoomNum then
            RemoteEvent:FireClient(Player, "Success")
            table.insert(Rooms[targetRoomNum]["Players"], Player)
        else
            print("No room found")
        end  
    end
end)