Ryan B. Jawad
Ryan B. Jawad

Reputation: 61

passing a variable to a handler(function) in applescript

test_two() and test_three work(), but test_one() does not. Why is that? How do I pass the argument into the handler and use it as a local variable?

set the_application to "Safari"
test_one(the_application)
on test_one(the_application)
    tell application the_application
        make new document with properties {URL:"http://www.stackoverflow.com"}
    end tell
end test_one
# ----

test_two()
on test_two()
    tell application "Safari"
        make new document with properties {URL:"http://www.stackoverflow.com"}
    end tell
end test_two
# ----

set the_application to "Safari"
test_three(the_application)
on test_three(the_application)
    tell application the_application
        activate
    end tell
end test_three

Upvotes: 0

Views: 564

Answers (2)

Robert Kniazidis
Robert Kniazidis

Reputation: 1878

Here is my other working solution, maybe, better than my first one:

set the_application to "Safari"
test_one(the_application)

on test_one(the_application)
    set theScript to "tell application \"" & the_application & "\"
make new document with properties {URL:\"http://www.stackoverflow.com\"}
    end tell"
    run script theScript
end test_one

Upvotes: 1

Robert Kniazidis
Robert Kniazidis

Reputation: 1878

When you want use some terms common to multiple applications, you can do it using terms from one of them. This terms will work for other applications as well. You can indicate in the code's first line the name of any application, which has command make new document with properties and property URL,

set the_application to "some Safari like application"
test_one(the_application)

on test_one(the_application)
    using terms from application "Safari"
        tell application the_application
            make new document with properties {URL:"http://www.stackoverflow.com"}
        end tell
    end using terms from
end test_one

Other example (creates new folder on the desktop):

set the_application to "Finder"
test_one(the_application)

on test_one(the_application)
    using terms from application "System Events"
        tell application the_application
            make new folder with properties {name:"TestFolder"}
        end tell
    end using terms from
end test_one

Upvotes: 0

Related Questions