What is wrong with this code?

In PlayerInitialSpawn:


if team.NumPlayers(0) == team.NumPlayers(1) then
			ply:SetTeam(math.random(0,1));
		else
			ply:SetTeam(team.BestAutoJoinTeam());
		end

That code seems fine, no errors, yet, every single time they get put onto team 1. Every. Single. Time. No. Matter. What.
And it’s the only 2 cases of “SetTeam” in init.lua too so it can’t be overridden anywhere else.

Are you sure the team numbers are correct?

100% sure.
[lua]team.SetUp(0, “Resistance”, Color(255,32,32), true);
team.SetUp(1, “Combine”, Color(32,32,255), true);[/lua]

Try using 1 and 2, instead of 0.
Failing that, add some debug prints to see what’s happening.

I’m just going to answer your thread title (“What is wrong with this code?”):

You shouldn’t use magic numbers in your code. Instead, before you create the team assign some enumerations wand use those to setup the teams.

For example:
[lua]-- Define team indexes
TEAM_EXAMPLE = 0;
TEAM_OTHER_TEAM = 1;
TEAM_ANOTHER_TEAM = 3;

– Setup the teams
team.SetUp(TEAM_EXAMPLE, “Example Team”, Color(255, 255, 255));
team.SetUp(TEAM_OTHER_TEAM, “Other Team”, Color(0, 0, 0));
– etc…[/lua]

This would ensure you’re using the right team indexes.

Also I have no idea how math.random works in GLua these days, but you might have to re-seed the function with something like the current time in seconds to ensure it gives a more “random” number.

Additionally iirc Lua starts counting from 1 rather than 0 in table indexes, maybe because you set the first team to index 0 it’s failing somehow? Though I wouldn’t be suprised if GLua is inconsistent in this and it doesn’t matter.

I hope any of this information will get you to your answer, if it doesn’t please provide more relevant code like: How you are hooking into PlayerInitialSpawn, what other parts of the gamemode hook into PlayerInitialSpawn and the part where you setup the teams.

[editline]3rd May 2015[/editline]

  • partially ninja’d -

printing math.random(0,1) many times serverside works fine.