Andrej Mitrović
Andrej Mitrović

Reputation: 3342

How do I add two variables together and store the result into another variable?

I can't figure out the most basic Tcl syntax, what is the right way to write the following:

set var1 5
set var2 3
set var3 $var1 - $var2; # error line

puts $var3

Upvotes: 4

Views: 16836

Answers (4)

potrzebie
potrzebie

Reputation: 1798

Since Tcl 8.5, the math operators and functions are also available as commands. Check the examples section of the mathop manual for an alternative to expr.

Upvotes: 0

Jerry
Jerry

Reputation: 71558

In Tcl, you need the function expr for evaluations:

set var3 [expr {$var1 - $var2}]

You can however skip them in Tcl 8.5+ when you are dealing with indices, for example:

% set numberlist [list 1 2 3 4]
% set index 2
% puts [lindex $numberlist $index-1]
2

Otherwise in older versions, you'd have to use expr again:

% set numberlist [list 1 2 3 4]
% set index 2
% puts [lindex $numberlist [expr {$index-1}]]
2

It's good practice to put braces in your expressions, though you don't have to.

Upvotes: 4

slebetman
slebetman

Reputation: 113926

Tcl has no syntax for math operations. Instead it relies on the expr command/function to do math:

set var3 [expr $var1 - $var2]

Best practice is to supply only a single argument to expr quoted by braces to avoid subtle issues like double substitution:

set var3 [expr {$var1 - $var2}]

Upvotes: 8

Related Questions