To extend pnuts.lang.Package class, the following methods should be defined by the subclass.
protected Value lookup(String symbol, Context context)
- The built-in function 'defined(symbol)' corresponds to 'lookup(symbol, context) != null' .
- Reading values of a package is translated into 'lookup(symbol, context).get()'.
public void set(String symbol, Object obj, Context context)
- An assignment expression "symbol = obj" corresponds to 'set(symbol, obj)'
The following methods can be overriden if needed.
protected void init()
- This method initializes the data structure and defines variables.
protected void init(Context context)
- This method is called when the package becomes the current package.
For example, a package which is implemented with Hashtable would be like:
import pnuts.lang.*; class SimplePackage extends Package { Hashtable table; protected void init(){ table = new Hashtable() } protected void init(Context context){ System.out.println("init(Context) is called"); super.init(context); } protected Value lookup(String symbol, Context context){ final Object obj = table.get(symbol); if (obj != null){ return new Value(){ public Object get(){ return obj; } }; } else { return null; } } public void set(String symbol, Object value, Context context){ table.put(symbol, value); } }
The method lookup(String, Context) was introduced in 1.0beta3. Before then, the method get(String) had been overridden, although it was less efficient because it need to calculate a hash code twice to read a variable.