Skip to content

proc

Define a procedure (function).

Syntax

tcl
proc name args body

Parameters

  • name: The procedure name. Can be namespace-qualified (e.g., ::myns::myproc). Intermediate namespaces are created automatically if they don't exist.
  • args: Parameter list. Supports default values with {param default} and variadic arguments with args.
  • body: The script to execute when the procedure is called.

Parameter Types

Simple parameters

tcl
proc greet {name} { ... }

Parameters with defaults

tcl
proc greet {name {greeting "Hello"}} { ... }

Variadic parameters

tcl
proc log {level args} { ... }

The special parameter args captures all remaining arguments as a list.

Mixed required and optional arguments

tcl
proc example {required1 required2 {optional1 default1} {optional2 default2}} {
    # ...
}

When optional parameters are followed by required ones, the optional parameters become effectively required.

Return Values

  • The return value is the value from an explicit return command
  • If no explicit return, the return value is the result of the last command executed
  • Errors in the procedure body propagate to the caller
  • The return command with -code and -level options is supported for non-local returns

Local Variables and Namespace Context

  • Each procedure invocation creates a new call frame with its own local variables
  • When a procedure is invoked, the current namespace is set to the namespace where the procedure was defined

Replacing Existing Commands

Defining a proc with the same name as an existing command (user-defined or builtin) replaces it.

Examples

Basic procedure

Output

Default parameter values

Output

Variadic arguments

Output

Recursive procedure

Output

Namespace-qualified procedure

Output

Optional parameters with args

Output

Replacing existing commands

Output

See Also