Howto:Understand Namespaces and Methods

From FlightGear wiki
Jump to navigation Jump to search

Namespaces

A namespace is a "context", i.e. an environment where a certain symbol (variable) is valid.

In Nasal, a namespace is just a conventional hash. It stores values in the form of key/value pairs, each value is linked to a key that can be used to look up it:

var foo = {};

To add members or fields to this "context" (or namespace), you can use several different notations, such as using conventional assignment:

foo.altitude = 100; 
foo["altitude"] = 100;

or even specify fields during initialization using a key, colon, value notation (key:value):

var foo = { altitude: 100 };

To add multiple keys to such a dictionary, you just separate them using a comma:

var foo = { altitude: 100, latitude: 0, longitude: 0 };

# trailing commas are also allowed
# var foo = { altitude: 100, latitude: 0, longitude: 0, };

In addition, it is valid to omit the key's value too:

var foo = { altitude:, latitude:, longitude:, };

# equivalent to
# var foo = { altitude: nil, latitude: nil, longitude: nil, };

In order to access these fields or "members" of a namespace, you need to provide a valid namespace first:

print(foo.altitude);

So, basically namespaces are all about organizing and structuring your variables and the overall symbol space. In object oriented programming, this concept is very powerful because you cannot only have hash-specific variables but also hash-specific functions. This makes it possible to create new objects by using a template hash and inheriting fields and behavior (methods).

Methods

Methods are somewhat related to "namespaces" in that they are class-specific functions (OOP), i.e. functions that are specific to a certain instance of an already instantiated class. In Nasal space, this means that the function is embedded inside a Nasal hash and that it makes use of instance data (using "me") or accessing the parents vector.

For example, to switch off the lights in the bath room, there could be a method "switch_off_lights" in the "house" class:

house.bath.switch_off_lights

Defining methods

Variable me can only be used inside methods.

# var fn = func { debug.dump(me); }; # invalid ("me" cannot be used outside objects)

var obj = {fn: func {
    debug.dump(me);
}};
obj.fn(); # prints obj

Global namespace

There is a global namespace globals, similar to globalThis in JavaScript.

Related content