1
[subsection {Handling A Variable Number Of Arguments}]
3
In [sectref {A Simple Procedure}] we demonstrated how easy a
4
translation to C can be. Is it still as easy when we introduce
5
something moderately complex like handling a variable number of
6
arguments ? A feature which is needed to handle commands with options
7
and optional arguments ? Unfortunately not.
9
We can use [cmd critcl::cproc] only if the number of arguments is
10
known beforehand, i.e. at the time of declaration. This of course also
11
means that they do not support default arguments either.
15
Thus, to handle something like the example below
20
foreach y { set sum [expr {$sum + $y}] }
25
we have to use [cmd critcl::ccommand] instead.
27
[para] Its advantage: Access to the low-level C arguments representing
28
the Tcl arguments of the command.
30
That allows things like variable number of arguments, optional
31
arguments, options, etc.
33
[para] Its disadvantage: Access to the low-level C arguments
34
representing the Tcl arguments of the command.
36
Where [cmd critcl::cproc] handles the task of converting from Tcl to C
37
values (for arguments) and back (for the result), with
38
[cmd critcl::command]s we have to do this on our own.
40
[para] Here is the translation of the example:
43
package require critcl
45
critcl::ccommand math {cd ip oc ov} {
50
if (Tcl_GetDoubleFromObj (ip, ov[oc], &y) != TCL_OK) {
57
Tcl_SetObjResult (ip, Tcl_NewDoubleObj (sum));
62
Notable about this translation:
64
[list_begin enumerated]
66
[enum] As promised/threatened, all the conversions between the Tcl and
67
C domains are exposed, and the developer should know her way
70
[enum] The four arguments "cd ip oc ov" are our names for the
71
low-level arguments holding
72
[list_begin enumerated]
73
[enum] ClientData (reference)
74
[enum] Tcl_Interp (reference)
75
[enum] Number of arguments, and
76
[enum] Array of argument values, each a Tcl_Obj*.
79
This list of arguments, while not optional in itself, is allowed to be
80
empty, and/or to contain empty strings as argument names. If we do
81
that critcl will supply standard names for the missing pieces, namely:
83
[list_begin enumerated]