Show in Frame No Frame
Up Previous Next Title Page Index Contents Search

5.2.2 Context and the element stack

As the generator travels through the do and foreach loops, it builds up a stack of model elements: each element on the stack corresponds to the context of an enclosing loop, an element we have passed through directly on the way to the current element. In most cases we are only interested in the information found in the current context, but when we need information from earlier parts of our route the stack provides an easy way to access the elements in the context hierarchy. Consider the following fragment from our example code:
02 'SpecSheet for ' id newline newline
03 foreach >Watch
04 { 'Watch: ' id newline
As explained before, the id commands on lines 2 and 4 operate on different contexts: the first one fetches the name of the graph while the second returns the name of the Watch relationship from the current loop iteration. But what if we need to get the name for the graph while we are inside the loop, in the context of the Watch relationship? It is of course possible to use a variable to cache the graph name for future use but MERL also provides a special syntax for cases like this. We can simply refer to the preceding element in the context hierarchy with a ;1 suffix, where 1 is the number of levels back we want to refer to. The level of the current element is always 0 and each previous element is removed from it by one, i.e. the previous element in the stack is ;1, the one before that ;2, etc. So, to access the name of the graph from within the foreach loop in our example code, we can simply use id;1. This applies to property values also, so the same graph name could be fetched using :Name;1.

It is also possible to loop over the elements in the stack using a do loop. For example, to list all elements of type ‘Watch’ that we have passed through (starting from and including our current context) would look like this:
do stack { if type = 'Watch' then id newline endif }

Show in Frame No Frame
Up Previous Next Title Page Index Contents Search