Variable Scope

     Variables have a lifecycle in the action context, and the lifecycle of variables is achieved through the stack of the action context.

1.Action context stack operation

import org.xmeta.ActionContext;
import org.xmeta.Bindings;

ActionContext actionContext = new ActionContext();

//Get the top bindings
actionContext.peek().put("x", 1);
System.out.println(actionContext.get("x")); //The print result is 1

//Push into a stack and pop out one by one.
try{   
    Bindings bindings = actionContext.push();
    bindings.put("x", 2);
    System.out.println(actionContext.get('x")); //The print result is 2

    //Put another stack, pop one by one.
    try{
        Bindings bindings = actionContext.push();
        bindings.put("x", 3);
        System.out.println(actionContext.get('x")); //The print result is 3
    }finally{
        actionContext.pop();
        System.out.println(actionContext.get('x")); //The print result is 2
    }
}finally{
     actionContext.pop();
     System.out.println(actionContext.get("x")); //The print result is 1
}

     In the above code, ActionContext is also a stack, where the elements are Bindings, in which variables can be stored. When the value is taken from the ActionContext, it goes down from the top of the variable, and returns when a Bindings contains a variable, otherwise it goes down to the bottom of the stack. When a Bindings is removed (pop), the variables in Bindings are removed along with them, and there is no such variable in ActionContext.

2.Local and global variables

    Local and global variables can be realized by the operation of the stack in the action context. The method is that the engine always pushes and pops up the stack when executing the action.

    The action shown above corresponds to the Java code below.

public void TestScope(){
    int x = 100;
    int y = 200;
    {   //Begin
        int z = 300;   //在Variables节点下定义
        {   //第二个Begin
                System.out.println(x + y + z);
        }
    }
}

    The life cycle of variables x, y and z in the model is the same as that of variables x, y and z in Java code, where the blue node in the action screenshot is the node of local variable, corresponding to the parentheses {} in Java code.

    In the action context, the lowest stack layer is always not removed, so the variables stored in this layer are relatively global variables.

 

Copyright ©  2007-2019 XWorker.org  版权所有  沪ICP备08000575号