Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as parameter in AutoIT

I have a few functions with the same structure (simplified):

func moveFiles()  
    local $error = 1  
        For $i = 1 to 100
            updateProgress($i)  
            updateStatus("Processing " & $i & "/100 files")  
            $error *= moveFile($i)  
        Next  
    Return $error  
endFunc  

I would like to make this a generic function like this:

func doSomething($function)  
    local $error = 1  
        For $i = 1 to 100
            updateProgress($i)  
            updateStatus("Processing " & $i & "/100 files")  

            $error *= $function($i)   ;execute the function that was passed

        Next  
    Return $error  
endFunc

So i can do like this:

doSomething($moveFiles)  
doSomething($compareFiles)
doSomething($removeFiles)
...

Is this possible in AutoIt v3 and how can i do it ?

like image 778
Aerus Avatar asked Jul 25 '12 07:07

Aerus


1 Answers

A challenger appears! Interesting question. You can call a function by their name as a string with the built-in Call. For example you have a function called moveFiles with a parameter, you can call that function with:

Call("moveFiles", $i)

I've written an example that demonstrates this. It's a convenient simple way of doing delegates, events or callbacks as you may be used to from other strict languages. In the example I've intentionally left out error handling because there are two ways to do it. You can return a true / false (or 1 / 0) value or you can use the SetError function with the @error macro.

Here is the full and working example:

func doSomething($function)  
    local $error = 0
    For $i = 1 to 5
        updateProgress($i)  
        updateStatus("Processing " & $i & "/100 files")  

        Call($function, $i)
    Next  
    Return $error  
endFunc

doSomething("moveFiles")
doSomething("compareFiles")
;doSomething("removeFiles")

Func moveFiles($i)
    ConsoleWrite("Moving file " & $i & @CRLF)
EndFunc

Func compareFiles($i)
    ConsoleWrite("Copying file " & $i & @CRLF)
EndFunc

Func updateProgress($i)
    ConsoleWrite("Stage processing at #" & $i & @CRLF)
EndFunc

Func updateStatus($msg)
    ConsoleWrite($msg & @CRLF)
EndFunc

Output:

Stage processing at #1
Processing 1/5 files
Moving file 1
Stage processing at #2
Processing 2/5 files
Moving file 2
Stage processing at #3
Processing 3/5 files
Moving file 3
Stage processing at #4
Processing 4/5 files
Moving file 4
Stage processing at #5
Processing 5/5 files
Moving file 5
Stage processing at #1
Processing 1/5 files
Copying file 1
Stage processing at #2
Processing 2/5 files
Copying file 2
Stage processing at #3
Processing 3/5 files
Copying file 3
Stage processing at #4
Processing 4/5 files
Copying file 4
Stage processing at #5
Processing 5/5 files
Copying file 5
like image 114
Jos van Egmond Avatar answered Sep 29 '22 10:09

Jos van Egmond