I have a situation where it would be very useful to pass in several parameters into a function, and then I want to use one of those parameters as the name of the next function to call.
functionAlpha Var1, Var2
if Var1 is a valid parameter then
LogWarning “You have made the call with a function that does not exist.”
Does anyone know of a way to actually use the string value within a variable as the name of a function for this purpose? I have found that a long series of if and else if statements works, but I have over 600 different values that could be passed into the function.
You want the do command. If Var1 is the name of a function and Var2 is the parameter, you can execute it and output the return value with :
do "put" && Var1 & "(" & Var2 & ")"
You’re building a string of valid Sensetalk code which is then passed to the interpreter by the do command.
The do command allows you to construct any code and run it, but in your case you can also do something very close to the example code you came up with. Just put the variable name in parentheses to use its value as the name of the function. So your code might look something like this:
Here’s a little test script I wrote that might be a little more clear:
set funcName to any item of "abc,def"
put (funcName)(123) -- call the function specified in funcName
to abc x
to def x
return "def" & x
This will either display “246” or “def123” depending on which function is randomly selected.
That you both. Both solutions work beautifully.
I’ve been trying to figure out how to pass a function as a parameter, and this is EXACTLY what I was looking for! Thanks to both of you!