Handling if a player leaves mid function?

how would you handle a player leaving mid function, for example:

local playerData = {}

game.Players.PlayerAdded:Connect(function(player)
  playerData[player] = {variable = "hi"}
end)

game.Players.PlayerRemoving:Connect(function(player)
  playerData[player] = nil
end)

function start(player)

print(playerData[player].variable)
task.wait(2)
print(playerData[player].variable)
task.wait(2)
--player leaves here
print(playerData[player].variable) -- errors
end

would you make it into a coroutine so it doesnt matter if it errors
or would you just check for the players existance after every task.wait

1 Like

Store playerData[player] to a variable

local playerData = {}

local function start(player)
    local data = playerData[player]
    task.wait(2)
    print(data.variable) -- shouldn't error if the player has left
end
1 Like