ForGroup

From WarCraft3

Jump to: navigation, search

Template:common.j article series


common.j

native ForGroup                 takes group whichGroup, code callback returns nothing
Confused? Jass help forum!

Picks every unit in whichGroup and calls callback for each one. The unit the callback function is being called for is accessible inside the callback function by using GetEnumUnit.

Detailed example

This example creates a group, adds a couple of units to it, and displays the name of each unit in the group.

function CallbackFunc takes nothing returns nothing
    call BJDebugMsg(GetUnitName(GetEnumUnit()))
endfunction

function Foo takes nothing returns nothing
    local group g = CreateGroup()
    local unit u = CreateUnit(Player(1), 'hfoo', 0, 0, 0)
    call GroupAddUnit(g, u)
    
    set u = CreateUnit(Player(0), 'hfoo', 0, 0, 0)
    call GroupAddUnit(g, u)
    
    set u = CreateUnit(Player(0), 'hpea', 0, 0, 0)
    call GroupAddUnit(g, u)
    
    // The group now contains the following units:
    //    Footman owned by Player(1)
    //    Footman owned by Player(0)
    //    Peasant owned by Player(0)
    
    call ForGroup(g, function CallbackFunc)
    
    call DestroyGroup(g)
    set g = null
    set u = null
endfunction

When ForGroup is called in that code, about the following will happen:

  1. The footman owned by Player(1) is set as the unit GetEnumUnit returns.
  2. CallbackFunc is called. The GetEnumUnit() call inside it returns the footman, so it displays the message 'Footman'.
  3. The footman owned by Player(0) is set as the unit GetEnumUnit returns.
  4. CallbackFunc is called. GetEnumUnits returns the footman, so 'Footman' is displayed.
  5. The peasant is set as the return value of GetEnumUnit.
  6. CallbackFunc is called, it displays 'Peasant'.

See also

Personal tools