我正在使用名爲ns-2的使用Tcl和C++構建的離散事件模擬器。我試圖寫一些代碼在TCL:無法更改變量的值
set ns [new Simulator]
set state 0
$ns at 0.0 "puts \"At 0.0 value of state is: $state\""
$ns at 1.0 "changeVal"
$ns at 2.0 "puts \"At 2.0 values of state is: $state\""
proc changeVal {} {
global state
global ns
$ns at-now "set state [expr $state+1]"
puts "Changed value of state to $state"
}
$ns run
下面是輸出:
At 0.0 value of state is: 0
Changed value of state to 0
At 2.0 values of state is: 0
狀態的價值似乎並沒有改變。我不確定我是否在使用TCL方面做錯了什麼。任何人都有一個想法,可能會出現什麼問題?
編輯:謝謝你的幫助。實際上,ns-2是我無法控制的東西(除非我自己重新編譯模擬器)。我嘗試了建議和這裏的輸出:
的代碼:
set ns [new Simulator]
set state 0
$ns at 0.0 "puts \"At 0.0 value of state is: $state\""
$ns at 1.0 "changeVal"
$ns at 9.0 "puts \"At 2.0 values of state is: $state\""
proc changeVal {} {
global ns
set ::state [expr {$::state+1}]
$ns at-now "puts \"At [$ns now] changed value of state to $::state\""
}
$ns run
輸出爲:
At 0.0 value of state is: 0
At 1 changed value of state to 1
At 2.0 values of state is: 0
而對於代碼:
set ns [new Simulator]
set state 0
$ns at 0.0 "puts \"At 0.0 value of state is: $state\""
$ns at 1.0 "changeVal"
$ns at 9.0 "puts \"At 2.0 values of state is: $state\""
proc changeVal {} {
global ns
set ::state [expr {$::state+1}]
$ns at 1.0 {puts "At 1.0 values of state is: $::state"}
}
$ns run
輸出是:
At 0.0 value of state is: 0
At 1.0 values of state is: 1
At 2.0 values of state is: 0
似乎不工作...不知道它與NS2和我的代碼有問題...
您是否考慮過'incr state'而不是'set state [expr {$ state + 1}]'? – 2010-03-29 15:37:56
是的。剛剛嘗試過......似乎沒有工作。 – Legend 2010-03-29 15:44:29
它應該與全球參考 – 2010-03-29 23:10:33