DavidT
DavidT

Reputation: 767

AppleScript pass expression into function to be re-evaluated repeatedly? (or: AppleScript handler with callback?)

I think the correct description for what I'm trying to do is be able to pass an expression or function/handler into another handler as a parameter/argument. Some code to be evaluated inside the receiving handler. Similar to Javascript callbacks, I think.

For example, something like this:

on waitFor(theConditionExpression)
    timeout_start(5) -- start a 5 second timer
    repeat until (theConditionExpression or timeout_isExpired())
        delay 0.1
    end repeat
    return theConditionExpression
end waitFor

Of course, typically if I pass in some boolean expression, it will evaluate that expression once, at the time I pass it in. But I want it to evaluate it every time it's referenced in the code inside the handler.

Some languages (not sure about AS) have some kind of eval() function that you can pass it some code as a string and it will execute that string as code. Theoretically that could solve this, but: (a) I don't know if AS has anything like that, but even if it does, (b) it's not desired for various reasons (performance, injection risks, etc.)

So I'm thinking something more like eg. JavaScript's ability to pass in a function (named or anonymous) as function parameter/argument that can be re-evaluated every iteration in a loop, etc. (eg. like the compareFn argument in JS's Array.sort(compareFn)).

Can AS do anything like this, and if so how?

Thanks!

Upvotes: 0

Views: 289

Answers (1)

Ted Wrigley
Ted Wrigley

Reputation: 3194

I'm going to suggest (pro forma) that an AppleScript application with an on idle handler is generally a better solution for wait conditions than a repeat/delay loop. It's more efficient for the system, and doesn't freeze up the script. But that would involve reconceptualizing your script, and I'm not certain it would work in this case, given the way you formed the problem.

There's an old but good site called AppleScript Power Handlers that shows a bunch of nifty-neato tricks for sophisticated use of AppleScript handlers: passing handlers as values or parameters; creating Script Objects within handlers; making closures and constructors. I'm pretty sure the answer to your request is in there. aLikely you'll want to set up a bunch of handlers that serve as condition expressions, then pass them as parameters to the evaluating handler. Or maybe you'll want to set up a script object containing the condition handlers and call it as needed?

At any rate, see what you can do with it, and ask more specific questions if you run into problems.

Upvotes: 1

Related Questions