How do I allow access to variables in enclosing scope in modelica?

Viewed 68

I tried this model from the book by Fritzson (2015, section 3.16 on page 102) to better understand variable lookup. The one modification I made is that I instantiated IC and BC as variables ic and bc.

class RC
  Real x;
  class IC
    Integer x;
  equation 
    x = 2;
  end IC;
  class BC
    Real y;
    equation 
    x = y;
  end BC;
  IC ic;
  BC bc;
equation 
  x = 3.14;
end RC;

The problem with this example is that it runs fine in openmodelica 1.18.1 (y will get the value 3.14), but Dymola complains:

Variables found in types or in global scope must be constant, but x wasn't. In class RC.BC.

Note that the original example model (without instantiation of BC and IC) runs fine in both programs.

On the next page, Fritzson says that "references to variables and parameters in enclosing scopes is illegal". I therefore assume that dymola is right in rejecting the model. It would have been so much clearer if that had been indicated in the model through some comment.

  • which program is not compliant? I think the answer is openmodelica, but I'm not sure.
  • Is a proper way to fix this model to use inner/outer?
1 Answers

It is possible to fix using inner outer as follows (there are also other possibilities):

class RC
  inner Real x; // <<-- Inner
  class IC
    Integer x;
  equation 
    x = 2;
  end IC;

  class BC
    Real y;
    outer Real x; // <-- Outer
  equation 
    x = y;
  end BC;
  IC ic;
  BC bc;
equation 
  x = 3.14;
end RC;

The specification has the restriction in https://specification.modelica.org/master/scoping-name-lookup-and-flattening.html#simple-name-lookup

Reference to variables successfully looked up in an enclosing class is only allowed for variables declared as constant.

Related