varargs best practice?

Jan Schenkel janschenkel at yahoo.com
Tue Dec 7 03:00:42 EST 2010


--- On Mon, 12/6/10, Mark Wieder <mwieder at ahsoftware.net> wrote:
> All-
> 
> Does anyone have ideas on a best practice for handling
> variable
> numbers of parameters (as in C varargs)? I have two
> functions and I'd
> like to pass a variable number of parameters (probably no
> more than
> six) to the first function and have it hand them off to the
> second:
> 
> function getString pVerb, pArgs -- pArgs may be many
> parameters
>   return doCommand(pVerb, pArgs)
> end getString
> 
> function doCommand pVerb, pArgs
>   -- do something with parameters
>   -- return something
> end doCommand
> 
> The problem is that only the first argument gets passed to
> the
> doCommand function. If I iterate through the parameters to
> getString
> using paramCount and param(x) then the result gets packaged
> up in
> quotes when it gets handed to doCommand and it becomes one
> parameter.
> 
> I'm about to do something really ugly with the code and
> hoping that
> someone has been through this already and has a nifty way
> of dealing
> with this situation.
> 
> -- 
> -Mark Wieder
>  mwieder at ahsoftware.net
> 

Why not repackage the additional params as an array, and pass that on to the 'doCommand' handler? The 'doCommand' handler can then check if the second parameter is an array, and if not, check the paramCount for those cases where it is called directly, rather than through the 'getString' function.

Of course, you can always collect the parameters and build a 'do' instruction; I just dropped a button onto a stack and gave it this script:
##
on mouseUp
   answer getString("alpha","beta","gamma")
end mouseUp

function getString pVerb
   local tToDo, tParamIndex
   put "return doCommand(pVerb" into tToDo
   repeat with tParamIndex = 2 to the paramCount
      put ",param(" & tParamIndex & ")" after tToDo
   end repeat
   put ")" after tToDo
   do tToDo
end getString

function doCommand pVerb
   local tOutput, tParamIndex
   put "Hello from doCommand" & return & \
          "Verb: " & pVerb & return & \
          "Params: "into tOutput
   repeat with tParamIndex = 2 to the paramCount
      put param(tParamIndex) & "," after tOutput
   end repeat
   delete char -1 of tOutput
   return tOutput
end doCommand
##

Clicking the button produced an answer box with the text:
##
Hello from doCommand
Verb: alpha
Params: beta,gamma
##
So I guess it works :-)

HTH,

Jan Schenkel.
=====
Quartam Reports & PDF Library for LiveCode
www.quartam.com

=====
"As we grow older, we grow both wiser and more foolish at the same time."  (La Rochefoucauld)



      




More information about the Use-livecode mailing list