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
try
ScriptAlpha.(object Var2)(Var1)
catch
LogWarning “You have made the call with a function that does not exist.”
end try
end if
end functionAlpha
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.
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:
get ScriptAlpha.(Var2)(Var1)
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
return 2*x
end abc
to def x
return "def" & x
end def
This will either display “246” or “def123” depending on which function is randomly selected.