pebble icon indicating copy to clipboard operation
pebble copied to clipboard

Access to EvaluationContext variables

Open awestwell opened this issue 5 years ago • 1 comments

Good Evening All,

I am attempting to access a variable defined in the EvaluationContex using the following

final Object test = this.evaluationContext.getVariable("$context");

However from the screen shot attached you can see it is returning null instead of continuing to iterate the next scope definition which has the "$context" variable defined.

In the code I am passing _context down to the macro so $context should be available if I am correct.

How do I attempt to access a variable if its scope stops at local? Please see the attached debug screen shot

issue

Thanks

Ash

awestwell avatar Aug 04 '20 17:08 awestwell

You can do a PR with a configuration to allows access to all variables or use this hack that I use to access the entire scope chain:

List<Scope> getScopeChain(EvaluationContext context) {
        ScopeChain chain = ((EvaluationContextImpl) context).getScopeChain();
        LinkedList<Scope> scopes = (LinkedList<Scope>) getFieldValue("stack", chain);
        return scopes == null ? Collections.emptyList() : scopes;
    }

public static Object getFieldValue(String fieldName, Object instance) {
        Field field;

        try {
            field = instance.getClass().getField(fieldName);
        } catch (NoSuchFieldException e) {
            try {
                field = instance.getClass().getDeclaredField(fieldName);
            } catch (NoSuchFieldException ignore) {
                return null;
            }
        }
        try {
            if (field.trySetAccessible()) {
                return field.get(instance);
            }
        } catch (Exception ignore) {
        }
        return null;
    }

You can then access everything else inside macros

SharkFourSix avatar Dec 05 '21 18:12 SharkFourSix