[JASS] [Solved] Is nulling local variables necessary even if you only announced it?

Level 3
Joined
Feb 11, 2024
Messages
22
I'm trying to make a dummy unit (to make it use thunder clap) when dash skill is finished.
So i announced local unit u in the timer-looping function, but it is only used when the loop is finished. (set u = CreateUnit~)

In this case, should I put "set u = null" inside the [if then] before calling "destroy()"?

Or should I put it where it is now (at the end, nulling it everytime timer loops before dash is not finished)?

Thanks in advance.

JASS:
private function FWalk_Act takes nothing returns nothing
   local unit u
   local data d = GetTimerStructA(GetExpiredTimer())
   set d.z = d.z - d.speed
   set d.x = d.x + d.speed * Cos(d.angle * bj_DEGTORAD)
   set d.y = d.y + d.speed * Sin(d.angle * bj_DEGTORAD)
   if  d.z <= -15.00 then
        set u = CreateUnit(GetOwningPlayer(d.c), 'h000', d.x, d.y, 0.00)
        call UnitApplyTimedLifeBJ( 2.00, 'BTLF', u )
        call d.destroy()
    else
        set Index = d
        call SetUnitX(d.c,d.x)
        call SetUnitY(d.c,d.y)
    endif
    set u = null
endfunction
 
Either way is fine. I usually just put it at the end, in case you end up making changes and using "u" elsewhere. You just need to make sure it is nulled out before the local variable "goes out of scope". In JASS, this only happens when you encounter an "endfunction" or a "return" (because local variables are "local" to the function they are defined in!).

For example:
JASS:
// Example 1: this is fine
function Test takes nothing returns nothing
    local unit u = GetTriggerUnit()
    call KillUnit(u)
    set u = null
endfunction

// Example 2: this is not fine, as the scope ends without "u" being nulled
// so you'll have a reference leak
function TestTwo takes nothing returns nothing
    local unit u = GetTriggerUnit()
    if UnitAlive(u) then
        return // should add "set u = null" before this to fix the problem
    endif

    call KillUnit(u)
    set u = null
endfunction

As long as you follow those rules you'll be fine. But to answer your specific question, you don't need to assign it to null if the variable has only been declared but not assigned yet (so if you wanted to, you could move the null inside the if/then without issues). You only need to assign it to null if the local variable is an agent-type that currently points to some object.
 
Top