[JASS] Do Local Variables Leak?

Level 21
Joined
Mar 16, 2008
Messages
955
I can only find out-of-date sources on this topic. Do we need to null all local variables at the end of the function to prevent leaks?

Also, do you notice anything wrong in general with this function in general aside from potential local variable leaks? A player wanted to help with a few triggers but he doesn't know a lot about JASS and doesn't like GUI. It seems ok to me but I mostly only use GUI.

It's still a rough draft so some things might not be 100% working.

JASS:
//===========================================================================
// The actions performed when a king provides gold to a knight.
function Trig_AI_Give_Gold_Actions takes nothing returns nothing

    local trigger t = GetTriggeringTrigger()
    local integer i = LoadInteger(gg_TriggerToKingIndex, GetHandleId(t), 0)
    local integer goldAmount = GetRandomInt(999, 3001)
    local force kingsKnights = CreateForce()
    local player knight = null
    local integer knightId = 0
    local player p = null
    

    call DisplayTextToForce(GetPlayersAll(), "Trig_AI_Give_Gold_Actions :: Calculated id: " + I2S(i))

    if i < 0 or i > 3 then
        return
    endif

    // Build a temporary force of knight players in the same force as this king
    loop
        exitwhen knightId > 23
        set p = Player(knightId)
        if IsPlayerInForce(p, udg_Knights_Group_Var) and IsPlayerInForce(p, udg_Groups[i + 1]) then
            call ForceAddPlayer(kingsKnights, p)
        endif
        set knightId = knightId + 1
    endloop

    set knight = ForcePickRandomPlayer(kingsKnights)

    if (Trig_AI_Knight_CanReceiveGold(knight)) then
        call QuestMessageBJ(udg_Groups[i + 1], bj_QUESTMESSAGE_UPDATED, "The |cffff0000King|r has given gold to " + GetPlayerName(knight) + ".")
        call AdjustPlayerStateBJ(goldAmount, knight, PLAYER_STATE_RESOURCE_GOLD)
        call AdjustPlayerStateBJ(-goldAmount, Player(i), PLAYER_STATE_RESOURCE_GOLD)
    endif

    call DestroyForce(kingsKnights)
    set kingsKnights = null
    set knight = null
    set p = null
    set t = null

endfunction
 
Last edited:
Level 29
Joined
Sep 26, 2009
Messages
2,594
Yes, local variables leak references unless nulled. You still need to call relevant destructor to prevent an object leak (like you do in GUI with global variables), but on top of that you need to null local variables.
JASS:
local location loc = GetUnitLoc(some_unit)
//do stuff with loc
call DestroyLocation(loc) //destroys the object itself to prevent object leak
set loc = null // prevents reference leak

You should also null variables even when you don't destroy the object:
JASS:
local group g = CreateGroup()
//do something with the group
set udg_Groups[udg_index] = g //we assign group "g" to global variable array
set g = null //still need to null local variable to prevent reference leak

Your code seems ok
 
Top