# Using local variables inside WhenEvent

Using WhenEvent inside Module is quite strange. The local variables are not evaluated in WhenEvent. For example

eq = Module[{time1 = 200, time2 = 400},
{WhenEvent[t > time1, a[t] -> 1],
WhenEvent[t > time2, a[t] -> 0]}]


returns

{WhenEvent[t > time1$$1064, a[t] -> 1], WhenEvent[t > time2$$1064, a[t] -> 0]}


I guess it has something to do with the attribute of the WhenEvent?

Attributes[WhenEvent]
(* {HoldAll, Protected} *)


Is there anyway to force the local variables in WhenEvent to be evaluated?

• Yes, it's related to HoldAll: Module[{a = 1}, Hold@a]. May 9 '20 at 6:58
• @xzczd how can I solve this problem then? May 9 '20 at 7:03

Yes, it's related to HoldAll, so, just Evaluate:

Module[{time = 200}, WhenEvent[t > time // Evaluate, a[t] -> 1]]


Alternatively, use With instead:

With[{time = 200}, WhenEvent[t > time, a[t] -> 1]]


To understand the behavior of With you may want to read:

What are the use cases for different scoping constructs?