(Lua) Preventing a looping code.

Countbuffalo

Chieftain
Joined
Aug 16, 2013
Messages
94
Hi all, in one of my mods I wanted to add some bonuses normally only obtained from policies to a building, so I went about writing the Lua for it. Whilst the Lua itself works fine, there's an issue where players in the industrial era will see their social policies become ridiculously cheap.

I believe it is to do with how I've given the player their policy. Is it necessary to set them a free policy if I'm forcing the policy with Lua?

Code:
function WashorsehockyurnFunction(iPlayer)
        local pPlayer = Players[iPlayer]
        if pPlayer:GetCivilizationType() == iWasshi then
            for pCity in pPlayer:Cities() do
                if (pCity:GetNumBuilding(iSeto) > 0) then
                pPlayer:SetNumFreePolicies(1)
                pPlayer:SetNumFreePolicies(0)
                pPlayer:SetHasPolicy(iSciencePolicy, true)
            end
        end
    end
end
GameEvents.PlayerDoTurn.Add(WashorsehockyurnFunction)

What happens however it seems that once the player has the building the free policy keeps repeating over and over again because it's a Turn Function. How would I go about closing the code once the player has the building so the effect only happens once?

Cheers
 
You could add
Code:
GameEvents.PlayerDoTurn.Remove(WashorsehockyurnFunction)
inside your if-statement, though that will probably give problems with reloading the game. It will also cause problems where there are multiple copies of the wasshi civ, as the code will then only fire for the first copy of the civ, and not for all the others.

--

A different way would be to check if the player has the iSciencePolicy first, and only if he does not have it already you grant him the policy.
Judging from your code, I assume that only 1 building is necessary for the policy to be granted. I.e. one building grants a bonus in the whole empire. If those are your intentions, then you could compress the code to this:
Code:
function WashorsehockyurnFunction(iPlayer)
       local pPlayer = Players[iPlayer]
        if pPlayer:GetCivilizationType() == iWasshi and (not pPlayer:HasPolicy(iSciencePolicy)) then
            if pPlayer:CountNumBuildings(iSeto)>0 then --this line could as well be included in the previous line, but I left it here to show more clearly what replaced the for-loop
                pPlayer:SetNumFreePolicies(1)
                pPlayer:SetNumFreePolicies(0)
                pPlayer:SetHasPolicy(iSciencePolicy, true)
             end
         end
end
GameEvents.PlayerDoTurn.Add(WashorsehockyurnFunction)
 
Thanks, I implemented your solution. I never would have thought of simply writing out "and not player has" despite how self-explanatory it is, but that's LUA for you I guess, it all seems so straightforward when you're reading it :lol:.

Thanks again.
 
Top Bottom