How do I loop through a players units?

Craig_Sutter

Deity
Joined
Aug 13, 2002
Messages
2,773
Location
Calgary, Canada
I am using the following code in my mod. I want to select a group of units randomly based upon their combat type and assign them to an operation. However, I run into trouble when I try to loop through the units. I get a nil value for "unit". I've never looped through a player's units before, and can't seem to find a good example in the scenarios or in this forum.

Code:
function HladirAttackOnBamborough()
	
if Game.GetGameTurn() == 0 then

	--set Hladir as player
	local pHladir
	
	for iPlayer=0, GameDefines.MAX_MAJOR_CIVS-1 do 

		local pHladir = Players[iPlayer]
	
		if (pHladir:IsAlive() and not pHladir:IsHuman()) then
			if (GameInfo.Civilizations.CIVILIZATION_SONGHAI.ID == pHladir:GetCivilizationType()) then
			
			-- loop through Hladir units and find units with certain combat types

			local unit = unit:GetID()

			for unit in pHladir:Units() do				
			
			if (unit:UnitCombatType() == GameInfoTypes["UNITCOMBAT_MELEE"]) then
			elseif (unit:UnitCombatType() == GameInfoTypes["UNITCOMBAT_NAVALMELEE"]) then
			elseif (unit:UnitCombatType() == GameInfoTypes["UNITCOMBAT_ARCHER"]) then
			elseif (unit:UnitCombatType() == GameInfoTypes["UNITCOMBAT_SIEGE"]) then

			-- select half of those untis			
			
			if (Game.Rand(100, "Selecting attack unit") < 50) then

			-- add that unit to operation
						
				unit:SetDeployFromOperationTurn(1);
							
			Players[iPlayer]:AddTemporaryDominanceZone (53, 48);

			end
			end
			end			
		end
		end
	end
end
end

Events.ActivePlayerTurnEnd.Add(HladirAttackOnBamborough)

I run into an error when I try to loop through the units. I'm doing something wrong, but I'm not good at lua and without a template, am having difficulties.

Any advice would be appreciated.

Thank-you.
 
Remove this line:
local unit = unit:GetID()

unit is being defined as a part of the for loop and thus you do not require it to be defined as a local.

EDIT: Also the above line is out of whack as you are defining unit to be unit:GetID()
 
Also, a tip I learn from other member's mods:

Instead of doing this:
GameInfo.Civilizations.CIVILIZATION_SONGHAI.ID == pHladir:GetCivilizationType()

Try defining GameInfo.Civilizations.CIVILIZATION_SONGHAI.ID as a global so that you can call it across any code. Same goes for all other civs.

SONGHAI = GameInfo.Civilizations.CIVILIZATION_SONGHAI.ID
....
....
if pHladir:GetCivilizationType() == SONGHAI then
......
end

Its quicker and easier to remember.
 
Back
Top Bottom