全局变量给出错误 "The variable ... is not defined." 编号 -2753

global var gives error "The variable ... is not defined." number -2753

我有这个代码:

global logFilePath

Job("/Volumes/Work/test.log")

on Job(logFilePath)
  -- more code
  vlog("text")
  -- more code
end Job

on vlog(x)
   do shell script "echo \"" & (do shell script "date +' %H:%M:%S '") & x & "\" >> " & quoted form of logFilePath
end vlog

我不断从 on vlog 块中获取 error "The variable logFilePath is not defined." number -2753 from "logFilePath"

为什么?我不是声明它是全局的吗?

这有效但不够优雅:

global logFilePath, logFilePath2

Job("/Volumes/Work/test.log")

on Job(logFilePath)
  set logFilePath2 to logFilePath
  -- more code
  vlog("text")
  -- more code
end Job

on vlog(x)
   do shell script "echo \"" & (do shell script "date +' %H:%M:%S '") & x & "\" >> " & quoted form of logFilePath2
end vlog

处理程序中的本地变量logFilePath

 on Job(logFilePath)

与同名的 global 变量不是同一个对象,因此确实没有定义。


为了清楚起见,请使用不同的名称

global logFilePath

Job("/Volumes/Work/test.log")

on Job(localPath)
    set logFilePath to localPath
    -- more code
    vlog("text")
    -- more code
end Job

on vlog(x)
    do shell script "echo \"" & (do shell script "date +' %H:%M:%S '") & x & "\" >> " & quoted form of logFilePath
end vlog

或仅使用局部变量

Job("/Volumes/Work/test.log")

on Job(localPath)
    -- more code
    vlog("text", localPath)
    -- more code
end Job

on vlog(x, logFilePath)
    do shell script "echo \"" & (do shell script "date +' %H:%M:%S '") & x & "\" >> " & quoted form of logFilePath
end vlog