Help with pcall

Hi. I am having troubles with the pcall function.

I am making a minigame style game and I am trying to make it so in the case of an error, the whole game doesn’t break.

This is my original game loop which works fine:

while true do
	wait(LobbyTime)
	
	local ChosenGameMode = ChooseGame()
	
	ServerMessage(ChosenGameMode.Title)
	
	local GameData = ChosenGameMode.F()
	
	ServerMessage("Winners:")
	
	for _,Player in pairs(GameData.Winners) do
		ServerMessage(Player.Name)
	end
	
	ServerMessage("Coins Awarded:")
	
	for PlayerName,Coins in pairs(GameData.CoinsAwarded) do
		ServerMessage(PlayerName .. " - " .. Coins)
	end
	
	ClearBin()
end

To clarify, everything above works fine ^ ^ ^

Now my solution to not make errors stop my entire game is:

while true do
	wait(LobbyTime)

	local ChosenGameMode = ChooseGame()

	ServerMessage(ChosenGameMode.Title)

	local Success, Data = pcall(ChosenGameMode.F())

	if Success then
		ServerMessage("Winners:")

		for _,Player in pairs(Data.Winners) do
			ServerMessage(Player.Name)
		end

		ServerMessage("Coins Awarded:")

		for PlayerName,Coins in pairs(Data.CoinsAwarded) do
			ServerMessage(PlayerName .. " - " .. Coins)
		end

		ClearBin()
	else
		OnServerError(Data)
	end
end

and for some reason every time a gamemode finishes, OnServerError() gets called with the string ‘attempt to call a table value’

I have no idea why this is happening. I think I might just have a lack of understanding of pcall.

Anyone know why this is happening?

Change

local Success, Data = pcall(ChosenGameMode.F())

to

local Success, Data = pcall(ChosenGameMode.F)
1 Like

Thank you man. That makes a lot of sense now.