wurstscript / WurstScript

Programming language and toolkit to create Warcraft III Maps
https://wurstlang.org
Apache License 2.0
226 stars 28 forks source link

How to modify external variables in closures? #988

Closed isaced closed 3 years ago

isaced commented 3 years ago
int leavingsMonstorCount = 0
forUnitsInRect(gg_rct_C) (unit u) ->
    if u.getOwner() == Player(PLAYER_NEUTRAL_AGGRESSIVE)
        u.kill()
        leavingsMonstorCount++    // VSCode warning: The assignment to local variable leavingsMonstorCount is never read.
        print("leavingsMonstorCount++")

print("leavingsMonstorCount :" + leavingsMonstorCount.toString())

The above code will output as follows, leavingsMonstorCount is always 0, can I modify external variables in a closure?

leavingsMonstorCount++
leavingsMonstorCount++
leavingsMonstorCount :0
GetLocalPlayer commented 3 years ago

No, you can't. Local variables are passed by value just like if you were passing them to a normal function. You can use a class-wrapper from the standard library

let leavingsMonstorCount = new Reference<int>(0)
forUnitsInRect(gg_rct_C) (unit u) ->
    if u.getOwner() == Player(PLAYER_NEUTRAL_AGGRESSIVE)
        u.kill()
        leavingsMonstorCount.val++ 
        print("leavingsMonstorCount++")

print("leavingsMonstorCount :" + leavingsMonstorCount.val.toString())

So you're passing a reference for a class instance that contains your value in an integer field.