Posted to tcl by bairui at Tue Sep 08 23:11:59 GMT 2020view pretty

#!/usr/bin/env tclsh

namespace eval myapp {}

proc ::myapp::main {argv0 argv} {
    variable reload 0
    puts "frame=<[info frame]>"

    while {([puts -nonewline "? "] eq "") && ([flush stdout] eq "") && [gets stdin line]} {
        switch -- $line {
            r {set ::myapp::reload 1 ; break}
            default {puts $line}
        }
    }

    if {$reload} {
        # Reload the server script and restart the server.
        uplevel #0 [list source [info script]]
        if {[info commands tailcall] eq {tailcall}} {
            puts "tail calling main"
            tailcall ::myapp::main $argv0 $argv
        } else {
            puts "recursing main"
            ::myapp::main $argv0 $argv
        }
    }
}

puts "\nLoading script: ::myapp::reload=<[expr {[info exists ::myapp::reload] ? $::myapp::reload : {}}]>"

# If this is the main script...
if {[info exists argv0]
    && ([file tail [info script]] eq [file tail $argv0])} {
    # If this is not a reload...
    if {![info exists ::myapp::reload] || $::myapp::reload} {
        ::myapp::main $argv0 $argv
    }
}