Re: if else else



Fredderic wrote:

(ie. if any of the regular
clauses DID match) would be handy for such cleanup (or in this case,
follow-up) code.

Yet another one:

---
proc ifany {args} {
set condition "\{\([lindex $args 0]\) && \[set ::doFinally true\]\}"
set ifscript "if $condition \{[lindex $args 1]\}"
set ::doFinally false
set finally {}
foreach {key condition script} [lrange $args 2 end] {
lappend ifscript $key
if { $key == "elseif" } {
set condition "\{\($condition\) && \[set ::doFinally true\]\}"
set ifscript "$ifscript $condition \{$script\}"
} elseif { $key == "else" } {
set ifscript "$ifscript \{$condition\}"
if { $script == "any" } {
set finally [lindex $args end]
break
}
}
}
uplevel 1 $ifscript
if {$::doFinally} {
uplevel 1 $finally
}
}
---

Check the code:

---
foreach c {0 1 2 3} {
puts "ifany c=$c: "
ifany {$c==0} {
puts "if-0 matches"
} elseif {$c==1} {
puts "if-1 matches"
} elseif {$c==2} {
puts "if-2 matches"
} else {
puts "else matches"
} any {
puts "do final things\n\n"
}
}
---

Results in:

---
ifany c=0:
if-0 matches
do final things


ifany c=1:
if-1 matches
do final things


ifany c=2:
if-2 matches
do final things


ifany c=3:
else matches
---

Works by adding an additional piece of code to the conditions. No checks for
sanity or anything else, but one gets the idea...

Regards
Stephan


.