我有一些具有相同结构的功能(简化):
func moveFiles()
local $error = 1
For $i = 1 to 100
updateProgress($i)
updateStatus("Processing " & $i & "/100 files")
$error *= moveFile($i)
Next
Return $error
endFunc
我想把它变成这样的通用函数:
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
所以我可以这样做:
doSomething($moveFiles)
doSomething($compareFiles)
doSomething($removeFiles)
...
这是否可以在AutoIt v3中使用,我该怎么办?
答案 0 :(得分:12)
挑战者出现了!有趣的问题。您可以通过内置Call调用函数名称作为字符串。例如,您有一个带有参数的名为moveFiles的函数,您可以使用以下函数调用该函数:
致电(“moveFiles”,$ i)
我写了一个例子来证明这一点。这是一种方便的简单方式来执行委托,事件或回调,因为您可能习惯使用其他严格的语言。在示例中,我故意省略错误处理,因为有两种方法可以做到这一点。您可以返回true / false(或1/0)值,也可以将SetError函数与@error宏一起使用。
以下是完整且有效的例子:
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
输出:
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