Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the line number of executing code in TCL

Tags:

tcl

how to print the line number of executing TCL script?

#! /usr/bin/tclsh

set a "100"
set b "200"
set c [expr $a + $b]
puts [info script] ;# it will display the script name which it is executing. 
                    # similarly I need to print the script line number.
puts $c
like image 984
user2693933 Avatar asked Dec 30 '25 08:12

user2693933


1 Answers

You have to use info frame to get this done simply.

info frame ?number?

This command provides access to all frames on the stack, even those hidden from info level. If number is not specified, this command returns a number giving the frame level of the command. This is 1 if the command is invoked at top-level. If number is specified, then the result is a dictionary containing the location information for the command at the numbered level on the stack.

If number is positive (> 0) then it selects a particular stack level (1 refers to the top-most active command, i.e., info frame itself, 2 to the command it was called from, and so on); otherwise it gives a level relative to the current command (0 refers to the current command, i.e., info frame itself, -1 to its caller, and so on).

We are going to make use of the dictionary returned by the info frame command. One of the key is 'line' which contains the line number of the script.

Have a simple proc as,

proc printLine {frame_info} {
    # Getting value of the key 'line' from the dictionary 
    # returned by 'info frame'
    set result [dict get [info frame $frame_info]  line] 
}

In general, the resulting dictionary from [info frame $frame_info] will be something like,

type source line 17 file /home/dinesh/stackoverflow/test cmd {printLine [info frame] } proc ::B level 1

From this, we are just getting the key value 'line' with dict get

Just call this proc with the current frame number of that context which can be achieved with info frame itself.

i.e.

set lineNumber [printLine [info frame]]; #Place this line in your code.

A demonstration of this logic is as below.

printLineNumber.tcl

#!/usr/bin/tclsh
proc printLine {frame_info} {
        # Getting value of the key 'line' from the dictionary 
        # returned by 'info frame'
        set result [dict get [info frame $frame_info]  line]
}
proc D {} {
        puts "proc D"
        puts [ printLine [info frame] ]
}
proc C {} {
        puts "proc C"
        puts [ printLine [info frame] ]
        D
}
proc B {} {
        puts "proc B"
        puts [ printLine [info frame] ]
        C
}
proc A {} {
        puts "proc A"
        puts [ printLine [info frame] ]
        B
}

puts "Global"
puts [ printLine [info frame] ]
A

Documentation : info, dict

like image 85
Dinesh Avatar answered Jan 03 '26 11:01

Dinesh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!