Here is one way to do it. Functions that allow for a variable number of parameters can be problematic. That is because the function will GPF if you attempt to access an argument greater than the number of arguments in the list. For this reason, the programmer normally has to specify the number of items in the list. You will notice that FB has some built in functions that allow you pass a variable number of arguments (eg. CHR() ). To prevent a crash, the compiler passes to the runtime library function a hidden parameter to the CHR() function telling it how many arguments the programmer supplied in his code when calling the function.
I have shown two versions of the function. The first will crash if you specify a position more than number of of strings in the list (but the calling syntax is the same as the VB Choose function), whereas the second version is safer because there is an additional parameter whereby the programmer specifically specifies the number of strings in the list.
''
'' This function does not check that nPosition is within the
'' valid range of choices (there is no built in way to know
'' how many variable arguments exist until they are processed
'' at runtime).
''
function strChoose cdecl ( byval nPosition as long, ... ) as string
dim as zstring ptr pzs
dim as string st
dim as cva_list args
cva_start( args, nPosition )
for i as long = 1 to nPosition
pzs = cva_arg( args, zstring ptr)
if i = nPosition then
st = *pzs
exit for
end if
next
cva_end( args )
function = st
end function
''
'' This version prevents crashes when nPosition exceeds the variable
'' list of choices by comparing against the programmer supplied numArgs.
''
function strChoose2 cdecl ( byval nPosition as long, byval numArgs as long, ... ) as string
dim as zstring ptr pzs
dim as string st
dim as cva_list args
cva_start( args, numArgs )
for i as long = 1 to nPosition
if i > numArgs then exit for
pzs = cva_arg( args, zstring ptr)
if i = nPosition then
st = *pzs
exit for
end if
next
cva_end( args )
function = st
end function
dim as long n = 2 ' will GPF is n > list of choices
dim as string a = strChoose( n,"Blue","Green","Aqua","Yellow","Gold")
? "a = "; a
n = 2 ' will not GPF because programmer has specified the list size
dim as string b = strChoose2( n, 5, "Blue","Green","Aqua","Yellow","Gold")
? "b = "; b
sleep