In addition to the lookup mechanism described in the previous chapter, urbiscript provides a secondary lookup mechanism similar to the one found in most languages, through the import and package keywords.
Consider the example below, where one would try to emulate a C++ namespace or Java package using only object lookup in urbiscript.
// Make a globally-accessible ’namespace’ Shapes.
class Global.Shapes
{
// Create an object representing a point
class Point { var x=0; var y=0};
// And one representing a color
class Color { var r=0; var g=0; var b=0};
// Now try a colored point using the objects below.
class ColoredPoint
{
var point;
var color;
function init()
{
point = Point.new();
color = Color.new();
}
};
}|;
This looks fine, except that Point and Color are not visible from within ColoredPoint.init:
var cp = Global.Shapes.ColoredPoint.new();
[00000001:error] !!! lookup failed: Point
[01234567:error] !!! called from: new
One would need to make ColoredPoint inherit from Shapes, instead of simply having it as one of its variables, or make all classes in Shapes globally accessible. Those are not satisfying solutions.
package works in the way one would expect:
package Shapes
{
// Create an object representing a point
class Point { var x=0; var y=0};
// And one representing a color
class Color { var r=0; var g=0; var b=0};
// Now try a colored point using the objects below.
class ColoredPoint
{
function init()
{
var this.point = Point.new();
var this.color = Color.new();
};
};
var p = ColoredPoint.new();
p.print();
}|;
[00000001] ColoredPoint_0x00000000
Do not nest package declarations, use package and then class as in the example above.
import has two syntax: import foo.bar to make foo.bar visible as bar in the current scope, and import foo.* to make everything in the package foo visible in the local scope.
{
import Shapes.*;
Point;
Color;
};
[00000001] Color
// It only applies to the scope.
Point;
[01234567:error] !!! lookup failed: Point
{
// Import only Point from Shapes
import Shapes.Point;
Point;
Color;
};
[01234567:error] !!! lookup failed: Color
// Packages have visibility over themselves as one might expect,
// like an implicit ’import this.*’.
{
import Shapes.ColoredPoint;
ColoredPoint.new();
};
[00000002] ColoredPoint_0x00000001