全局var给出错误“未定义变量...”。编号-2753

时间:2018-12-20 14:22:54

标签: scope applescript

我有此代码:

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

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

为什么?我不是宣布它为全球性吗?

这有效,但不太优雅:

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

1 个答案:

答案 0 :(得分:0)

处理程序中的 local 变量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