Why does my pcall return nil when i get the number of players in both teams?

Hello i am trying to get the number of players on both teams but my pcall function returns nil could somebody tell me what is wrong with my variables here??

local players = game:GetService("Players"):GetPlayers()
local teamplayersinfected = #game.Teams['Infected']:GetPlayers()
local teamplayerssurvivors = #game.Teams['Survivors']:GetPlayers()
local maxplayers = #game.Players:GetPlayers()
local module = require(workspace.modules.ModuleScript)
local ok = module.setvalues(teamplayersinfected,teamplayerssurvivors,maxplayers)


local e,s = module:SetPercentage()
print(e,s)


2 Likes

Might need to see the pcall in order to help figure out what’s going on in the pcall

1 Like
local module = {}


function module:setvalues(infected,survivors,maxplayers)
	local self = setmetatable({},module)
	
	self.Infected = infected
	self.Survivors = survivors
	self.Maxplrs = maxplayers
	
	return self
end

function module:SetPercentage()
	
	local success,response 
	local infected,survivors,max = self.Infected,self.Survivors,self.Maxplrs
	
	success,response = pcall(function()
		if success then return (infected/max)*100, (survivors/max)*100
	end
		if not success then return warn(response)end
		end)
end

return module

You’re using pcall incorrectly. pcall can be used to catch any run-time errors that occur within the body of the function it is provided. The first returned value from a pcall is always a boolean. It is true if the function provided as argument to pcall ran without any errors, false otherwise. Additionally, if the function provided to pcall did error, then the second returned value from pcall is the error message. Here’s an example of how you might use it:

function doError()
	local value = Vector3.new()
	value = value + "you can't add a string to a Vector3"
	return value --This line will not be reached because an error occurred on the previous line
end

function doNotError()
	local value = Vector3.new()
	value = value + Vector3.new(3,4,5) --No error here
	return value --This value will be returned as an additional return value from the pcall which called it
end

local suc1, msg1 = pcall(doError)
print(suc1, msg1)
-- false [location_of_script]: invalid argument #2 (Vector3 expected, got string)
local suc2, msg2 = pcall(doNotError)
print(suc2, msg2)
-- true 20

You shouldn’t be referencing the success and response variables within the body of the function you provide to pcall. There is no need to set them manually. If you wish to print out a custom error message when a pcall catches an error, you can do something like the following:

local suc, msg = pcall(function()
	local var = Vector3.new() + "still can't add a string to a Vector3"
	return var
end)

if not suc then
	warn("Oops I did something wrong!")
	warn("Got error message:", msg)
end
4 Likes