Method Environment - tanevnikola/lua-oos GitHub Wiki
The methods have no access to the global environment and they are sandboxed. In this section we can see how can we mold the environment to our liking.
Rule: The Method Environment is same for all the methods of an instance but per class. What it means is that there is one Method Environment per class when there is inheritance. Sounds complex but it's not :).
Lets explain it with an example
ft.class.Base(){
baseFoo1 = function() return _ENV; end;
baseFoo2 = function() return _ENV; end;
}
ft.class.Extended(ft.class.Base){
extendedFoo1 = function() return _ENV; end;
}
local instance = ft.class.Extended();
print(instance.extendedFoo1() == instance.baseFoo1());
print(instance.extendedFoo1() == instance.baseFoo2());
print(instance.baseFoo1() == instance.baseFoo1());
Output
false
false
true
In the above example, when we create an instance of the class, 2 method environments will spawn - one for each class in the inheritance hierarchy:
baseFoo1andbaseFoo2will share the same Method Environment,extendedFoo1will has its own Method Environment,
That's it!
Note: This rule is a consequence of the super table. To achieve a separate super table depending on where the method is located (in the class hierarchy) we must have a separate environment per class;
Note: See how can we achieve encapsulation as a consequence of this rule;
Lets discuss in more details about how the method environment is constructed and accessed
The method environment is consisted of 4 different things or concepts:
thistable,supertable,- upvalues,
- method environment extension table;