题
我使用一个离散事件模拟器称为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的问题还是我的代码...
解决方案
编辑:现在理解,状态机
首先,您使用的引用语法将会给你带来麻烦。你应该使用列表通常建立Tcl命令,这将确保 TCL将不扩大你不希望它扩大什么。
当您拨打呼叫您at-now
调用替换state
变量(即,当值不变,0。你想要的是:
$ns at-now 0.0 {puts "At 0.0 value of state is: $::state"}
$ns at-now 2.0 {puts "At 2.0 value of state is: $::state"}
它看起来像你的changeVal
编写正确(第一个版本有一些相同的替换问题),以及你被传递,将在本地使用变量引用,因此不设置全局状态的事实。
解决的问题的第一个版本的一部分的 - 使用全局引用,并同时报出[
和$
防止替代在调用点:
$ns at-now "set ::state \[expr {\$::state + 1}\]"
或者,使用大括号:
$ns at-now {set ::state [expr {$::state + 1}]}
其他提示
但问题是,你会立即替换您的变量的值,而不是当时的代码进行评估。您需要推迟替换。因此,代替:
$ns at 2.0 "puts \"At 2.0 values of state is: $state\""
这样做:
$ns at 2.0 {puts "At 2.0 values of state is: $state"}
这是很好的做法,把任何东西比一个命令的的简单调用更复杂的不的替代在过程中做这样的呼叫时。更容易作出正确的工作。
[编辑],点击
此外,at-now
仍然推迟做它的身体,直到电流at
返回之后。
我不知道为什么这样的作品,但它的工作原理:
set ns [new Simulator]
set state 0
proc changeVal {} {
global ns
incr ::state
$ns at-now {puts "Local::At [$ns now] values of state is: $::state"}
}
$ns at 0.0 "puts \"Global::At 0.0 value of state is: $state\""
changeVal
$ns at 9.0 "puts \"Global::At 2.0 values of state is: $state\""
$ns run
输出:
Global::At 0.0 value of state is: 0
Local::At 0 values of state is: 1
Global::At 2.0 values of state is: 1
如果有人知道一个解释,那将是巨大的。
不隶属于 StackOverflow