Nasal scripting language

From FlightGear wiki
Revision as of 11:54, 19 December 2011 by Quix0r (talk | contribs) (converted external links pointing on own wiki to internal links)
Jump to navigation Jump to search

Please note that a considerable amount of resources has not yet been incorporated here, you can check these out by going to the "discussion" page, where we are collecting links to webpages and mailing list discussions/postings related to Nasal.


Nasal = Not another scripting language!

The short summary is that Nasal is a scripting language that is tightly integrated with FlightGear itself, 
and provides a very easy way to manipulate the property tree, which is the core data structure within the 
simulator that expose all important internal runtime state of FlightGear. 

FlightGear offers a very powerful functional scripting language called "Nasal", which supports reading and writing of internal FlightGear properties, accessing internal data via extension functions, creating GUI dialogs and much more.

Nasal uses some of the concepts of ECMA/JavaScript, Python and Perl and implements a simple but complete way of Object Oriented Programming (OOP), Nasal uses an internal garbage collector so that no manual memory management is required by the programmer.

People familiar with other programming languages, and scripting languages like JavaScript in particular, are usually able to learn Nasal rather quickly. FlightGear provides a rich library of simulation-specific and general-purpose functions that can be accessed by Nasal scripts.

Nasal code can be run by aircraft configuration files, and it can be embedded in various XML files (dialog files, animation files, bindings for joysticks, keyboard and cockpit controls, and even in scenery objects). Nasal is platform independent and designed to be thread safe.


Some success stories

These were taken from the developers mailing list:

  • "Nasal is *very* well designed, compact, and efficient. It is used heavily throughout many areas of FlightGear."
  • "It's interesting though how much nasal you can actually get away with using without making a blip on frame rates. Nasal is *very* efficient and powerful for being an interpreted script language."
  • "FlightGear needed a built-in scripting language, and it has one. A compact, clean, elegant and fast one, Nasal extension functions interface perfectly to the property tree, the event manager, the built-in XML parser etc. Nasal is very tightly integrated in fgfs and used all over the place."
  • "There's no question that scripting languages are good; fgfs has a lot of Nasal code now. In my profiling I have never seen the nasal interpreter as a hot spot"
  • "I'm a simple content contributor with very little background in programming. When I made my first Aircraft (the bf109) I was confronted with the need to deploy slats automatically at a given speed. I din't want to embed C++ code or had such a complex script that the error messages in FG wouldn't help me and I previously only used a bit of python. I looked at some Nasal scripts and within a few hours it worked. I was impressed how easy it is to write even complex Nasal scripts. Later I started developing the walker feature that made it possible to walk around in the scenery, all with nasal. Stuart kindly enhanced the walker and added an animation system to it (see bluebird), again with nasal. Others have made Flight computers with it (see V-22 and Su-37). Nasal is a worthy tool"
  • "I used Nasal to build several rather complex systems, like Fuel System, Stab Augmentation System, Autopilot Logic, Terrain Avoidance Radar, Radar Warning Receiver and much more, and yes, I love Nasal too. Learning Nasal use was easy and fun and I din't found any limitation yet."
  • There are many vital parts of FlightGear currently coded in nasal. There are also random bits of nasal code scattered around in joystick configurations, instrument and aircraft models, scenery models... everywhere.
  • "We have an entire directory full of Nasal 'function' libraries now, and I'm quite happy using them instead of rolling my own duplicate functionality."
  • Nearly every sophisticated Aircraft uses some kind of Nasal, be it Effects like tyre smoke or important functionalities like Engine and electric management, The Bluebird FDM is completely written in Nasal, vital parts of the V-22 Osprey rely on it, Flyby and Model View wouldn't work anymore, no more interactive objects in the scenery, lots of the MP System would be gone, ... Nasal is THE tool which makes FG development fun and adds nearly unlimited possibilities. If you need an example, look at the Bluebird animated walker, all done in Nasal."
  • "there are good reasons to use Nasal - first of all the user base which regularly compiles their own code is small, whereas people do install addon packages - so I get a lot more feedback and test results. Second that one usually can't really crash the whole system from Nasal. Third, it's very easy to quickly try something and very maintenance-friendly. Fourth, you can actually start developing something without knowing how the core code ties together - which I suppose takes a lot of time to learn. And so on."
  • "Hard-coding every instrument in C++ instead of nasal means only developers following/building the latest cvs head code get to use whatever until the next release cycle."
  • "Hard coding every instrument/flight control in C++ means my WW-II storch (et.al.) is stuck with an autobrake functionality it doesn't have nor need."
  • "I think it boils down to the fact that we have two approaches that can accomplish the same thing. The C/C++ approach offers high performance but there is a dependence on when the C/C++ code was added to FlightGear. The Nasal approach offers fast prototyping, flexibility, and more (but not complete) independence from the C/C++ code."
  • "A basic problem with C++ functions is it is hard/impossible to override them for a special purpose. Writing in pure nasal allows function name hijacking and other tricks that can't be used on C++ code."
  • "Given the fact that FG is platform independent, I don't know if the embedded C++ is doing the same on Windows, Linux, PPC and intel Macs. Apart from the fact that if I was able to code c++ I would embed it to FG rather than in an Aircraft specific script"
  • "If we ported Nasal code over to C++ we'd lose the ability to change small things "on the fly" without compiling over and over again. We'd also lose good programmers, who prefer scripting over C++. Aircraft creation would not be customizable etc etc."
  • "The argument against Nasal is essentially that C++ is faster than Nasal - which, everything else being equal, is certainly correct. But highly specialized Nasal code written for a particular problem outperforms general purpose C++ code - I've given several examples in the past. If someone were e.g. to add movement to Nasal spawned models by adding a velocity property, I'm not sure it would outperform my Nasal quadtree-sorted adaptive range code which priorizes movement for things actually inside the field of view. Of course, if you'd hard-code that specialized algorithm, it would be faster than the Nasal version - but then you couldn't apply it to other problems any more."
  • "How many airplane developer will you loose if you remove the Nasal engine from FGFS because they can write Nasal code but not C++ code?"
  • "The algorithm being equal, I don't think there's a question that C++ is faster (I doubt the factor 10 though - that seems to be an extreme case). Everything else being equal, I also don't think there's a question that Nasal code is more accessible. And I would base any decision what to hard-code and what not on that balance."
  • "Nasal is just much better suited for FlightGear than many alternatives because of it's size, processing speed and because a number of FlightGear core developers have a good idea what's going on."
  • "In theory we could even use VBScript but Nasal has proven to be valuable for almost 10 years, so no reason to change or add another scripting language. Besides, if you know JavaScript then learning Nasal would take little effort."
  • "The pool of people with commit rights to the core C++ code is very, very small."


Nasal really is an excellent choice for prototyping and implementing new features and even completely new systems in FlightGear.

For example, the bombable script implements "dog fighting" support on top of FlightGear, without ANY changes to the C++ side of the code, just by using some fairly advanced scripted code (implemented in the built-in Nasal programming language). You can basically imagine it like a "MOD" of FlightGear. In other words, the bombable script creates a completely new "mode" in FlightGear.

No matter if it's scenery, aircraft, AI scenarios or whatever: many things that were originally never planned to be supported by FlightGear core developers, are now implicitly supported because of the lose coupling between highly configurable and flexible systems, such as the property tree and the Nasal scripting language.

So we are really standing on the shoulders of giants here, because we are now -after 10+ years- in the position to create significant new features (and even completely new systems in FlightGear) within the constraints of the FlightGear base package, without even touching the C++ source code at all - simply because FlightGear has become so flexible and extensible.

All of this became possible by some important architectural decisions, such as for example the use of XML and plain text files for pretty much all configuration files in FlightGear (and thus open file formats in general), a publicly accessible tree of state variables that can be easily inspected and modified at runtime (the property tree). Similarly, the decision to embed a scripting language that can be used for scripting the entire simulator was another important decision.

In FlightGear, Nasal is the most accessible method of customizing the whole simulator to a very high degree. Nasal code can be easily edited using a conventional text editor, there are no special tools required: Nasal source code is interpreted, compiled to bytecode and run by the Nasal "virtual machine" using FlightGear itself.

The emerging Local weather system was entirely prototyped in Nasal space, and is now being increasingly augmented by moving performance-critical functions to C++ space instead.

Using Nasal, it is even possible to create entirely scripted flights and smart "AI bots":

I have something here that I think is kind of fun.  I've been fiddling with
this off and on since last fall and decided it was time to clean it up a bit
and quit hording all the fun for myself.  Basically I have taken the F-14b
and created a high performance Navy "drone" out of it.  It can auto-launch
from a carrier, auto fly a route (if you've input one) and can do circle
holds (compensating for wind.)  I've added a simulated
gyro stabilized camera that will point at anything you click on and then
hold that view steady no matter what the airplane does (similar to what real
uav's can do.)  Finally, you can command it to return home and it will find
the carrier, setup a reasonable approach and nail the landing perfectly
every time (factoring in wind, carrier speed, etc.): http://www.flightgear.org/uas-demo/


As of 03/2009, there were approximately 170.000 lines of reported Nasal source code in the FlightGear base package [1], compared to 2006 this is almost a rate of growth of 600% within 3 years [2]. This illustrates the sheer adoption rate Nasal is experiencing in FlightGear.

(As of 10/2011, the FlightGear base package contained 326.000 lines of Nasal source code in *.nas files)

Note that this page is mostly about FlightGear-specific APIs/extension functions and usage patterns. Thus, you may also want to have a look here:

In addition, the Nasal directory in the FlightGear base package contains a wealth of tested, proven and usually well-commented source code that you may want to check out for additional examples of using the Nasal scripting language in FlightGear [3].

If you have any Nasal specific questions, you will want to check out the Nasal FAQ, feel free to ask new questions or help answer or refine existing ones. If you would like to learn more about existing Nasal modules in FlightGear, you may want to check out Nasal Modules.

If you are a developer and interested in extending Nasal, you may want to check out Howto:Extending Nasal.

Many short "howto"-style tutorials on Nasal programming can be found in the.

Some words on Nasal for fellow C++ programmers

Compared to C++, there is really nothing "low quality" about Nasal per se: Nasal is just the "script glue" that connects different parts of the simulator: Many Nasal scripts leverage C++ code - and it is very easy to add new C++ code that can be called from Nasal.

History has shown, that most code in FlightGear will eventually be made more configurable and more accessible, this usually happens in the same steps: 1) replacing static variables with variables stored in the property tree, 2) using listeners to get update notifications for important variables, 3) fully exposing a "control" interface by making it accessible it in the property tree, 4) providing scripting hooks.

Even if you should know C or C++ already, Nasal probably remains the most accessible and the most powerful method for customizing the simulator, simply because it is extremely easy and fast to get started, you don't need an "integrated development environment", you don't need to install compilers and you don't need to satisfy any 3rd party dependencies; bottom line being: if you can run FlightGear, you can also run Nasal and create new code.

In addition, Nasal code is fairly abstract code, too. Once you start looking at some existing Nasal scripts, you will see that it is also fairly high level code, much more high level than C++ - so Nasal has a much higher density of code, too. Nasal's role in FlightGear really is like JavaScript's role in Firefox, where it is also used for many/most core-related logics (CSS/XUL).

Performance

Obviously, C++ code will usually be faster than the corresponding Nasal code. But, while performance is not a design goal, Nasal isn't especially slow either. For example, early benchmarks of the garbage collector showed it as faster than perl's reference counter, and its number crunching performance is on par with python. But in all cases, simplicity, transparency and a sane feature set are preferred over speed in Nasal.

Nasal was specifically designed for use as an extension language in an larger project such as FlightGear. The problem with many otherwise excellent languages in this environment is that they are huge. Perl and python are great, but enormous. Even their "core" interpreters and library code are larger than most projects that require an embedded language. They cannot be readily shipped with their host application and need to be installed system-wide. This is a pain and a compatibility hassle.

The real goal with Nasal is to have a language that supports most "normal" programming idioms (objects, functions, arrays, hashes) while avoiding the bloat that comes from "platform" scripting languages like perl, python, ruby and php.


Garbage collection

Nasal garbage collects runtime storage, so the programmer need not worry about manual allocation, or even circular references. The current implementation is a simple mark/sweep collector, which should be acceptable for most applications. Future enhancements will include a "return early" capability for latency-critical applications. The collector can be instructed to return after a certain maximum delay, and be restarted later.


As far as speed goes, the last any benchmarking Nasal was done, it was about as fast as Perl 5 or Python 2.2 at most things. It's garbage collector was faster, its symbol lookup about the same or slightly faster, and its bytecode interpreter somewhat slower.

Thread safety

Unlike almost all other script interpreters (and unlike the FlightGear/Nasal interface itself) , Nasal is thread safe and scalable when called from multiple CPU threads (as opposed to the userspace interpreter threads implemented by Ruby).

No special treatment is required (as for perl, which clones a separate interpreter with separate data for each thread and uses locking around specifically-designated shared data) and the threads can be scheduled simultaneously. There is no global lock on the interpreter, as used by Python or Lua. The only limit on scalability is garbage collection, which must block all interpreter threads before running.

When running threaded code, Nasal provides "minimal threadsafety", meaning that the interpreter itself can be safely called from multiple CPU threads without risk of corrupting or deadlocking the interpreter internals. Multithreaded operations are therefore "safe", although they are not guaranteed to be atomic. In particular, poorly synchronized insertions into containers can "drop" objects into oblivion (which is OK from an interpreter stability standpoint, since the GC will clean them up normally). Nasal itself provides no synchronization primitives to address this; thread architecture is a "top-level" design job, and Nasal is intended to be an extension language in a larger project. Choice of synchronization mechanisms is going to be highly application dependent.

Exception handling

Like python, nasal supports exception handling as a first-class language feature, with built-in runtime-inspectable stack trace. Rather like perl, however, there is no special "try" syntax for exception handling, nor inheritance-based catching semantics. Instead, you use the call() builtin to invoke a function object and inspect the results to determine what error was thrown (either with the die() builtin or via an internal runtime error) and what the stack trace looked like. Elaborate exception handling isn't really appropriate for embedded scripting languages.

High level programming

Thus, programmers already familiar with C++ shouldn't just disregard Nasal as a "toy" that doesn't seem suitable for serious development: some of the more complex Nasal scripts can literally make one's head spin around and it would quite obviously take much more C++ or Java code to implement the same features, while sacrificing all the flexibility and power that a scripting language offers.

Some features can certainly be more easily implemented in Nasal space, than in C++ space. Often, the Nasal solution is "on par" with similar solutions in C++.

Accessibility

For instance, Nasal code cannot only be easily run and contributed by all users, but it can also be easily reused and maintained by other users. This means, that given the number of active C++ developers, compared to the number of base package contributors, your Nasal code is more likely to be actively maintained by fellow users if it is written in Nasal.

In other words, if there are some experimental features you'd like to explore, Nasal is an excellent way to ensure that other FlightGear users can easily test your new features. This could be witnessed during the development of the local weather system or the bombable addon,too.

This is in stark contrast to features developed solely in C++ space, because these can usually only be tested by people able to build FlightGear from source, especially if your code isn't yet in the main repository, where it would eventually be available in the form of a binary snapshot.

Obviously, none of this is to say that Nasal is the perfect solution for any problem, there are many things for which Nasal isn't necessarily a perfect choice, such as low level code for example (i.e. rendering).

On the other hand, Nasal really is a powerful tool in FlightGear, and if you find that something should, but cannot, be done in Nasal space, it is extremely easy to add support for new features to the Nasal engine using extension functions or property listeners to trigger C/C++ code.

Creating new Scripts

Nasal scripts need to be plain text files, saved with a *.nas extension.

Aircraft specific Nasal code

Generally, aircraft specific Nasal scripts reside in the corresponding aircraft's folder (or a corresponding /Nasal subfolder) where they are usually included by adding a corresponding <nasal> tag to the aircraft-set.xml file (see Writing simple scripts in "nasal"). Also see the section on namespaces which contains more specific examples.

Instrument specific Nasal code

While instrument specific scripts are saved within the instrument's folder (as previously mentioned, Nasal scripts can also be embedded in various other XML files), Nasal scripts driving shared instruments are generally stored in $FG ROOT/Aircraft/Generic/

Nasal code as bindings in XML files

Nasal scripts can also be used as "binding" objects, and can therefore appear anywhere in a configuration file (keyboard, mouse and joystick bindings, etc...) that accepts a <binding> tag. The relevant command type is "nasal", and you place your Nasal code inside of the <script> tag:

<binding>
 <command>nasal</command>
 <script>
  print("Binding Invoked!");
 </script>
</binding>

The code above invokes the print() function. This is a simple extension function that simply prints out its arguments, in order, to the FlightGear console as a single-line log entry. It is useful for debugging, but little else.

System-wide Nasal code

Nasal scripts that are not specific to certain aircraft, instruments or other uses, generally reside in the system-wide $FG ROOT/Nasal directory.

Nasal scripts that are placed inside $FG ROOT/Nasal (with a *.nas extension) are automatically loaded and run during FlightGear startup.

Nasal sub modules

As of 06/2011, FlightGear also supports so called Nasal "sub modules" which may reside in their own sub folder under $FG_ROOT/Nasal/ and which provide support for on-demand loading at runtime by toggling properties.

Some advantages are:

  • Nasal files can be grouped neatly instead of all scripts being mixed up in a single fgdata/Nasal directory. Grouping makes a lot of sense for modules consisting of several scripts - local weather is the best example.
  • Guaranteed loading sequence. Submodules are loaded _after_ the main fgdata/Nasal scripts, so they can rely on all fgdata/Nasal content to be already present. No more need for awkward listener callbacks, just to make sure that basic "props" or "gui" modules are available.
  • Finally, users have the option to disable loading modules. Unfortunately, just loading scripts (code/data) into memory already causes certain _run-time_ performance effects - even if the Nasal code was never executed (so even when all listeners/timers were disabled).

Please note that there is a difference between the _individual_ Nasal files in fgdata/Nasal and files belonging to a common Nasal _module in general (no matter whether loaded at run-time or loaded at start-up using a "<nasal>" tag).

The individual Nasal files in fgdata/Nasal have an own namespace _each_. The namespace get's the name of the Nasal file itself. So if you have a "gui.nas" in the directory, then you can reference a symbol "foo" using "gui.foo".

Nasal modules also have a single namespace. But all files belonging to the module share this _single_ namespace. The name of their namespace is made from its directory (for the run-time loadable modules), or from the specific tag given below the <nasal> XML element, which are often used for a/c specific modules (e.g. <nasal><ufo>...</ufo></nasal> creates the ufo Nasal namespace in ufo-set.xml).

So each Nasal file in a new Nasal "module" folder now shares the same namespace.

For more information on Nasal sub modules, please see [4] and [5].

User specific Nasal scripts

It's also possible to put Nasal files into $FG_HOME/Nasal/, that is: ~/.fgfs/Nasal/ on Unix, and %APPDATA%\flightgear.org\Nasal\ on MS Windows. This has the following advantages:

  • one doesn't have to mix local extensions with standard files
  • one is less likely to lose such local additions when upgrading
  • one doesn't need write permission to $FG_ROOT/Nasal/ or
  • one doesn't have to become "root" to edit such files

The files are guaranteed to be read after all the files in $FG_ROOT/Nasal/, so one can safely use elements of files like props.nas (props.Node), or globals.nas (setlistener() without leading underscore).

The files are guaranteed to be read in alphabetic order. So, if there are two files where one depends on the other, just name them appropriately.

The contents of each file are added to a namespace derived from the filename. So, all functions and variables of a file ~/.fgfs/nasal/local.nas will be added to nasal namespace "local", and a function test() is globally accessible as local.test().

It's possible to extend a standard module like "math" with definitions in ~/.fgfs/Nasal/math.nas, though this should, of course, not be exploited by code that is to be submitted to cvs.

Hello world

A simple hello world example in Nasal would be:

# hello.nas
print('Hello World!');

This will show the "Hello World" string during startup in the console window. The hash sign (#) just introduces comments (i.e. will be ignored by the interpreter).

Note: Script-specific symbols such as global variables (or functions) will be put into a scope (namespace) based on the script's name, scripts embedded via aircraft-set.xml files can separately specify a corresponding module name (see Howto: Make an aircraft for details).

Strings in Nasal can also use double quotes which support escaping:

# hello.nas
print("Hello\nWorld!");

Double quotes support typical escape sequences:

  • \n Newline
  • \t Horizontal Tab
  • \v Vertical Tab
  • \b Backspace
  • \r Carriage Return
  • \f Form feed
  • \a Audible Alert (bell)
  • \\ Backslash
  • \? Question mark
  • \' Single quote
  • \" Double quote

For example, to print a new line, use:

print ("\n");

To print a quoted string, use:

print ("\"quoted string\"");

and so on.

Single quotes treat everything as literal except for embedded single quotes (including embedded whitespace like newlines).

Nasal strings are always arrays of bytes (never characters: see the utf8 library if you want character-based equivalents of substr() et. al.). They can be indexed just like in C (although note that there is no nul termination -- get the length with size()):

Editing code files

Note that there is currently no way to tell FlightGear to reload Nasal scripts from the global Nasal directory at runtime, so in order to see changes take effect, you will have to exit and restart FlightGear for the time being. Note that there are some workarounds available, see: reloading Nasal code without re-starting FlightGear.

Also, note that as of 05/2009, Nasal in FlightGear does not yet support any form of dependency resolution. In other words, there's no "import", "require" or "include" directive - this is also why most code in FlightGear is wrapped inside a _setlistener() call instead, which in turn waits for a FlightGear signal before executing the code (see below for details).

Variables

Nasal scripts should make use of the var keyword when declaring variables. The "var" keyword makes a variable guaranteed to be local. Nasal, natively provides support for scalars (numbers, strings), lists (arrays, vectors) and hashes (objects or dictionaries), more complex data structures (such as trees) can be built using vectors or hashes.

var w=100;     # w is a local numerical variable
var x="hello"; # x is a local string variable
var y=[];      # y is a local vector (array)
var z={};      # z is a local hash (dictionary or table) - also used for OOP

Nasal supports a "nil" value for use as a null pointer equivalent:

var foo=nil; 

Also, note that Nasal symbols are case-sensitive, these are all different variables:

var show = func(what) {print(what,"\n");}
var abc=1; # these are all different symbols
var ABC=2; # different from abc 
var aBc=3; # different from abc and ABC

show(abc);
show(ABC);
show(aBc);

Please note that functions assigned to variables are no exception. If you write code without using "var" on variables, then you risk (often hard to debug) breakage at a later time because you may be overwriting symbols in another namespace.

So functions bound to variables should use the "var" keyword as well:

var hello = func { 
  print("hello\n"); 
}

But there's another reason why "var" should be used consequently, even if a variable is safe enough from later side effects, because it has a relatively specific or unique name: The "var" keyword makes reading code for others (and for the author after some time) easier, as it makes clear: "this variable starts its life *HERE*". No need to search around to see whether assigning a value to it means something to other code outside or not. Also, with an editor offering proper syntax highlighting reading such code is actually easier, despite the "noise".

The problem with nasal code that does not make use of the var keyword is, that it can break other code, and with it the whole system, but no Nasal error message will point you there, as it's syntactically and semantically correct code. Just doing things that it wasn't supposed to do. For a more in-depth discussion, please see [6].

Also, Nasal scripts that are loaded from $FG_ROOT/Nasal are automatically placed inside a namespace that is based on the script's name.

For example, referring to our earlier "Hello World" example, global variables defined in the hello.nas script would be accessible by using "hello" as prefix from other modules:

# hello.nas
var greeting="Hello World"; # define a greeting symbol inside the hello namespace

If you were now to read out the value from the greeting variable from another Nasal module, you would have to use the hello prefix:

# greetme.nas
print(hello.greeting); # the hello prefix is referring to the hello namespace (or module).

Namespaces

The Nasal Console built into FlightGear is quite handy when it comes to debugging code. However, here the namespaces need to be considered. In addition, Nasal sub modules (see above) have some special rules, too - basically, all Nasal files part of a "sub module" share a single name space based on the folder's name rather than the name of the individual Nasal files.

For cases of Nasal code specific for an aircraft (like instruments, for example), the corresponding scripts could be loaded through the aircraft's -set.xml file by putting it into the <nasal>...</nasal> section

 <nasal>
   ...
   <moduleA>
     <file>path/to/file1.nas</file>
     <file>path/to/file2.nas</file>		
   </moduleA>
   <moduleB>
     <file>path/to/file3.nas</file>	
   </moduleB>
 </nasal>

In this case, variables in files path/to/file1.nas and path/to/file2.nas can be used in the Nasal console as

 moduleA.varName;

Variables in path/to/file3.nas can be accessed as

 moduleB.varName;

Please note that Nasal sub modules (i.e. files loaded and run from their own Nasal sub directory), are subject to some special rules, as all Nasal source files are automatically loaded into the same namespace, which is by default based on the sub module's folder name.

Variables - Advanced Uses

Nasal, also supports Multi-assignment expressions. You can assign more than one variable (or lvalue) at a time by putting them in a parenthesized list:

  (var a, var b) = (1, 2);
  var (a, b) = (1, 2);               # Shorthand for (var a, var b)
  (var a, v[0], obj.field) = (1,2,3) # Any assignable lvalue works
  var color = [1, 1, 0.5];
  var (r, g, b) = color;  # works with runtime vectors too


Vectors (lists or arrays) can be created from others using an ordered list of indexes and ranges. This is usually called "vector slicing". For example:

  var v1 = ["a","b","c","d","e"]
  # 
  var v2 = v1[3,2];   # == ["d","c"];
  var v3 = v1[1:3];   # i.e. range from 1 to 3: ["b","c","d"];
  var v4 = v1[1:];    # no value means "to the end": ["b","c","d","e"]
  var i = 2;
  var v5 = v1[i];     # runtime expressions are fine: ["c"]
  var v6 = v1[-2,-1]; # negative indexes are relative to end: ["d","e"]

The range values can be computed at runtime (e.g. i=1; v5=v1[i:]). Negative indices work the same way they do with the vector functions (-1 is the last element, -2 is 2nd to last, etc...).

Storage: property tree vs. Nasal

With FlightGear's built-in property tree and Nasal's support for it, there are two obvious, and two somewhat competing, ways for storing scalar data: native Nasal variables and FlightGear properties, both of which can be easily accessed and managed from Nasal.

The advantage to native Nasal-space data is that it's fast and simple. If the only thing that will care about the value is your script, they are good choices.

The property tree is an inter-subsystem communication thing. This is what you want if you want to share data with the C++ world (for example, YASim <control-output> tags write to properties -- they don't understand Nasal), or read in via configuration files.

Also, native Nasal data structures are usually far faster than their equivalent in property tree space. This is because there are several layers of indirection in retrieving a property tree value.

In general, this means that you shouldn't make overly excessive use of the property tree for storing state that isn't otherwise relevant to FlightGear or any of its subsystems. Doing that would in fact have adverse effects on the performance of your code. In general, you should favor Nasal variables and data structures and should only make use of properties to interface with the rest of FlightGear, or to easily provide debugging information at run time.

As of FG 2.4.0, retrieving a value from the property tree via getprop is about 50% slower than accessing a native Nasal variable, and accessing the value via node.getValue() is 10-20% slower yet. This is an insignificant amount of time if you are retrieving and storing a few individual values from the property tree, but adds up fast if you are storing or retrieving hashes or large amounts of data. (You can easily benchmark times on your own code using systime() or debug.benchmark.)

In addition, it is worth noting that the Nasal/FlightGear APIs cannot currently be considered to be thread safe, this mean that -at least for now- the explicit use of pure Nasal space variables is the only way to exploit possible parallelism in your code by making use of threads.

Functions

What is a function ?

A "function" is a piece of code that can be easily used repeatedly (without repeating the same code over and over again), this is achieved by associating a symbolic name with the piece of code, such as "print", "show" or "get" for example. Whenever this symbolic name is then used in the program, the program will "jump" to the definition of the function and start running it, once the called function has completed it will automatically return to the instruction following the call.

By using so called "function arguments" (see below) it is possible to parametrize a function (using variables) so that it may use data that is specific to each invocation.

As previously shown, Nasal functions are implemented using the func keyword, The following snippet of code defines a new function named "log_message" with an empty function body (the curly braces).

var log_message = func {}

Function bodies

To add a function body, you need to add code in between these curly braces.

Anonymous function arguments

In Nasal, arguments are by default passed in the "arg" array, not unlike perl. To understand how this works, you should probably first read up on Nasal vectors.

var log_message = func {
   print(arg[0]);
}

Note that this is equivalent to:

var log_message = func() {
   print(arg[0]);
}

In other words, the argument list "()" can be omitted if it is empty. However, if you are new to Nasal or programming in general, it is probably a good idea to ALWAYS use parentheses, i.e. also for functions with empty argument lists - that makes it easy to get used to the syntax.

Note that this is just an assignment of an (anonymous) function argument to the local "log_message" variable. There is no function declaration syntax in Nasal.

Also, Nasal being a functional programming language, all passed arguments will be local to the corresponding scope. If you want to modify state in a function, you'll preferably return new state to the caller.

Named function arguments

You can also pass named arguments to a function, thus saving the typing and performance costs of extracting them from the arg array:

var log_message = func(msg) {
   print(msg);
}

The list of function arguments is called a function's "signature".

Default values for function arguments

Function arguments can have default values, as in C++. Note that the default value must be a scalar (number, string, function, nil) and not a mutable composite object (list, hash).

var log_message = func(msg="error") {
   print(msg);
}

If some arguments have default values and some do not, those with default values must come first in the argument list:

#Incorrect:
var log_message = func(msg="error", line, object="ground") { #some code }
#Correct:
var log_message = func(msg="error", object="ground", line) { #some code }

Any extra arguments after the named list are placed in the "arg" vector as above. You can rename this to something other than "arg" by specifying a final argument name with an ellipsis:

listify = func(elements...) { return elements; }
listify(1, 2, 3, 4); # returns a list: [1, 2, 3, 4]

Returning from functions

In Nasal, functions return implicitly the values of the last expression (i.e. "nil" in empty function bodies), you can also add an explicit "return" statement, for example to leave a function early. In addition, it is possible to return values, too.

So, semantically, the previous snippet of code is equivalent to these:

var log_message = func {return;}
var log_message = func {nil;}
var log_message = func {}; 
var log_message = func return;
var log_message = func nil;

Named arguments in function calls

Nasal supports named function arguments in function calls, too.

As an alternative to the comma-separated list of positional function arguments, you can specify a hash literal in place of ordered function arguments, and it will become the local variable namespace for the called function, with variables named according to the hash indexes and with values according to the hash values. This makes functions with many arguments more readable.

And it also makes it possible to call function's without having to take care of the right order of passing arguments.

Examples:

#if we have functions defined:
var log_message = func (msg="") { #some code to log variable msg }
var lookat =  func (heading=0, pitch=0, roll=0, x=nil, y=nil, z=nil, time=hil, fov=20) { #some code using those variables }
#we can use them them the usual way with comma separated list of arguments:
log_message("Hello World!");
lookat (180, 20, 0, XO, YO, ZO, now, 55);
#or we can use the hash literal arguments instead:
log_message(msg:"Hello World!");
lookat(heading:180, pitch:20, roll:0, x:X0, y:Y0, z:Z0,time:now, fov:55);

Both methods for calling the functions above are equivalent, but note the the second method is more readable, less prone to error, and self-documenting in the code for the function call.

As another example, consider:

var setPosition = func (latitude_deg, longitude_deg, altitude_ft) {
 # do something here 
}
# the actual function call:
setPosition( latitude_deg:34.00, longitude_deg:7.00, alt_ft:10000);

In other words, such function calls become much more self-explanatory because everybody can see immediately what a value is doing. This is a good practice, as you may eventually have to take a longer break, away from your code - and then even you yourself will come to appreciate such small things that make code more intuitive to work with.

Declared arguments are checked and defaulted as would be expected: it's an error if you fail to pass a value for an undefaulted argument, missing default arguments get assigned as usual, and any rest parameter (e.g. "func(a,b=2,rest...){}") will be assigned with an empty vector.

Nested functions, implicit return

Also, Nasal functions can be easily nested, for example:

 var calculate = func(param1,param2,operator) {
  var add = func(p1,p2) {p1+p2;}
  var sub = func(p1,p2) {p1-p2;}
  var mul = func(p1,p2) {p1*p2;}
  var div = func(p1,p2) {p1/p2;}
  if (operator=="+") return add(param1,param2);
  if (operator=="-") return sub(param1,param2);
  if (operator=="*") return mul(param1,param2);
  if (operator=="/") return div(param1,param2);
 }

Note that the add,sub,mul and div functions in this example do not make use of an explicit return statement, instead the result of each expression is implicitly returned to the caller.

Nasal functions that just consist of such simple expressions can also be further simplified to read:

 var add = func(val1,val2) val1+val2;

Function overloading

Note that Nasal functions can generally not be [overloaded], and that operator overloading in particular is also not supported.

However, the effects of function overloading can obviously be implemented individually by each function, simply by processing the number and type of passed arguments at the start of the function body. The FlightGear code base contains a number of examples for this, i.e. it is for example possible to pass properties in the form of plain strings to a callback or in the form of a Nasal wrapper like props.Node.

So this can be accomplished by first checking the argument count and then the types of arguments passed to the function.

To provide an example, here's a simple function to multiply two numbers, no matter if they are provided as scalars, as a vector or as x/y members of a hash:

var multiply2 = func (params) {
 if (typeof(params)=="scalar") return params*arg[0];
 if (typeof(params)=="vector") return params[0]*params[1];
 if (typeof(params)=="hash")   return params.x*params.y;
 die("cannot do what you want me to do");
}

So, now you have a very simple form of an "overloaded" function that supports different argument types and numbers:

multiply2(  2,6); # multiply two scalars
multiply2( [5,7] ); # multiply two scalars stored in a vector
multiply2( {x:8, y:9} ); # multiply two scalars stored in a hash

You could obviously extend this easily to support an arbitrary number of arguments by just using a for loop here.

As you can see, the basic idea is pretty simple and also scalable, you could easily extend this to and also return different types of values, such as vectors or hashes. This could for example be used to create wrappers in Nasal space for doing 3D maths, with vectors and matrices, so that a matrix multiplication could return a new matrix, too.

Functional programming, higher order functions, generators;

As previously mentioned, arguments to a Nasal function can also be functions themselves (Nasal being a functional programming language), this means that Nasal functions are higher order functions so that you can easily pass and return functions to and from Nasal functions. This can for example be used to dynamically create new functions (such functions are commonly called 'generators'):

 # a function that returns a new custom function
 var i18n_hello = func(hello) {
  return func(name) { # returns an anonymous/unnamed function
    print(hello,name);
  }
 }

 # create three new functions
 var english_hello = i18n_hello("Good Day ");
 var spanish_hello = i18n_hello("Buenos Dias ");
 var italian_hello = i18n_hello("Buon giorno ");

 # actually call these functions
 english_hello("FlightGear");
 spanish_hello("FlightGear");
 italian_hello("FlightGear");

Using helper functions

It is possible to simplify complex function calls by introducing small helper functions, for example consider:

var l = thermalLift.new(ev.lat, ev.lon, ev.radius, ev.height, ev.cn, ev.sh, ev.max_lift, ev.f_lift_radius);


So, you could just as well create a small helper function named"thermalLift.new_from_ev(ev)":

 thermalLift.new_from_ev = func (ev) {
  thermalLift.new(ev.lat, ev.lon, ev.radius, ev.height, ev.cn, ev.sh, ev.max_lift, ev.f_lift_radius);
}
var l=thermalLift.new_from_ev(ev);

Note that the expression to invoke your code would then also become less complicated and much more comprehensible.


When you have expressions of nested method calls, such as:

   t.getNode("latitude-deg").setValue(f.getNode("latitude-deg").getValue());
   t.getNode("longitude-deg").setValue(f.getNode("longitude-deg").getValue());

You could just as easily introduce a small helper function to wrap the code, that would be less typing for you, less code to read (and understand) for others and generally it would help localize functionality (and possible errors):

   var copyNode = func(t,f,path) t.getNode(path).setValue(f.getNode(path).getValue());

So you would simply take the complex expression and generalize it by adding variables that you pass in from a function object, then you could simply call your new function like this:

   copyNode(t,f,"latitude-deg");
   copyNode(t,f,"longitude-deg");

or:

   foreach(var p; ["latitude-deg", "longitude-deg","generated-flag"])
     copyNode(t,f,p);

or as a complete function accepting a vector of properties:

   var copyNode = func(target,source,properties) { 
    if (typeof(properties)!="vector") properties=[properties];
    if (typeof(target)!="hash") target=props.globals.getNode(target);
    if (typeof(source)!="hash") target=props.globals.getNode(source)
    foreach(var path; properties)
     target.getNode(path).setValue( source.getNode(path).getValue() );
   }
   copyNode("/temp/test", "/position", ["latitude-deg", "longitude-deg", "altitude-ft"]);

Whenever you have very similar lines of code that seem fairly repetitive, it is a good idea to consider introducing small helper functions. You can use plenty of small helper functions and then just "chain" them together, rather than using complex nested expressions that make your head spin.

Conditionals

Nasal has no "statements", which means that any expression can appear in any context. This means that you can use an if/else clause to do what the ?: does in C. The last semicolon in a code block is optional, to make this prettier

abs = func(n) { if(n<0) { -n } else { n } }

But for those who don't like typing, the ternary operator works like you expect:

abs = func(n) { n < 0 ? -n : n }

In addition, Nasal supports braceless blocks, like they're known from C/C++ and other languages:

var foo=1;
if (foo)
  print("1\n");
else
  print("0\n");
print("this is printed regardless\n")

Instead of a switch statement one can use

 if (1==2) {
   print("wrong");
 } else if (1==3) { # NOTE the space between else and if
   print("wronger");
 } else {
   print("don't know");
 }

which produces the expected output of don't know


The nil logic is actually quite logical, let's just restate the obvious:

 if (nil) {
   print("This should never be printed");
 } else {
   print("This will be printed, because nil is always false");		
 };


Nasal's binary boolean operators are "and" and "or", unlike C. unary not is still "!" however. They short-circuit like you expect

var toggle = 0;
var a = nil;
if(a and a.field == 42) {
   toggle = !toggle; # doesn't crash when a is nil
}

You can easily reduce the complexity of huge conditional (IF) statements, such as this one:

   if (a==1) function_a();
   else
   if (a==2) function_b();
   else
   if (a==3) function_c();
   else
   if (a==4) function_d();
   else
   if (a==5) function_e();

.. just by using the variable as a key (index) into a hash, so that you can directly call the corresponding function:

   var mapping = {1:function_a, 2:function_b, 3:function_c, 4:function_d,5:function_e};
   mapping[a] ();

This initializes first a hash map of values and maps a function "pointer" to each value, so that accessing mapping[x] will return the function pointer for the key "x".

Next, you can actually call the function by appending a list of function arguments (empty parentheses for no args) to the hash lookup.

Using this technique, you can reduce the complexity of huge conditional blocks. For example, consider:

   # weather_tile_management.nas
   460         if (code == "altocumulus_sky"){weather_tiles.set_altocumulus_tile();}
   461         else if (code == "broken_layers") {weather_tiles.set_broken_layers_tile();}
   462         else if (code == "stratus") {weather_tiles.set_overcast_stratus_tile();}
   463         else if (code == "cumulus_sky") {weather_tiles.set_fair_weather_tile();}
   464         else if (code == "gliders_sky") {weather_tiles.set_gliders_sky_tile();}
   465         else if (code == "blue_thermals") {weather_tiles.set_blue_thermals_tile();}
   466         else if (code == "summer_rain") {weather_tiles.set_summer_rain_tile();}
   467         else if (code == "high_pressure_core") {weather_tiles.set_high_pressure_core_tile();}
   468         else if (code == "high_pressure") {weather_tiles.set_high_pressure_tile();}
   469         else if (code == "high_pressure_border") {weather_tiles.set_high_pressure_border_tile();}
   470         else if (code == "low_pressure_border") {weather_tiles.set_low_pressure_border_tile();}
   471         else if (code == "low_pressure") {weather_tiles.set_low_pressure_tile();}
   472         else if (code == "low_pressure_core") {weather_tiles.set_low_pressure_core_tile();}
   473         else if (code == "cold_sector") {weather_tiles.set_cold_sector_tile();}
   474         else if (code == "warm_sector") {weather_tiles.set_warm_sector_tile();}
   475         else if (code == "tropical_weather") {weather_tiles.set_tropical_weather_tile();}
   476         else if (code == "test") {weather_tiles.set_4_8_stratus_tile();}
   477         else ...

While this is not a very complex or huge block of code, it is an excellent example for very good naming conventions used already, because the consistency of naming variables and functions can pay off easily here, with just some very small changes, you can already reduce the whole thing to a hash lookup like this:

 weather_tiles["set_"~code~"_tile"]();  # naming convention

This would dynamically concatenate a key consisting of "set_" + code + "_title" into the hash named weather_tiles, and then call the function that is returned from the hash lookup.

So for this to work you only need to enforce consistency when naming your functions (i.e. this would of course CURRENTLY fail when the variable code contains "test" because there is no such hash member (it's "4_8_stratus" instead).

The same applies to cumulus sky (fair weather), stratus/overcast stratus.

But these are very simple changes to do (just renaming these functions to match the existing conventions). When you do that, you can easily replace such huge IF statements and replace them with a single hash lookup and function call:

hash[key] (arguments...);

For example, consider:

var makeFuncString = func(c) return tolower("set_"~c~"_tile");
var isFunc = func(f) typeof(f)=='func';
var hasMethod = func(h,m) contains(h,m) and isFunc;
var callIfAvailable = func(hash, method, unavailable=func{} ) {
 var c=hasMethod(hash,makeFuncString(m) ) or unavailable();
 hash[makeFuncString(m)] ();
}
callIfAvailable( weather_tiles,code, func {die("key not found in hash or not a func");} );


Initializing data structures

There are some more possibilities to increase the density of your code, such as by removing redundant code or by generalizing and refactoring existing code so that it can be reused in different places (i.e. avoiding duplicate code):

For example see weather_tile_management.nas #1000 (create_neighbours function):

   1008 x = -40000.0; y = 40000.0;
   1009 setprop(lw~"tiles/tile[0]/latitude-deg",blat + get_lat(x,y,phi));
   1010 setprop(lw~"tiles/tile[0]/longitude-deg",blon + get_lon(x,y,phi));
   1011 setprop(lw~"tiles/tile[0]/generated-flag",0);
   1012 setprop(lw~"tiles/tile[0]/tile-index",-1);
   1013 setprop(lw~"tiles/tile[0]/code","");
   1014 setprop(lw~"tiles/tile[0]/timestamp-sec",weather_dynamics.time_lw);
   1015 setprop(lw~"tiles/tile[0]/orientation-deg",alpha);
   1016
   1017 x = 0.0; y = 40000.0;
   1018 setprop(lw~"tiles/tile[1]/latitude-deg",blat + get_lat(x,y,phi));
   1019 setprop(lw~"tiles/tile[1]/longitude-deg",blon + get_lon(x,y,phi));
   1020 setprop(lw~"tiles/tile[1]/generated-flag",0);
   1021 setprop(lw~"tiles/tile[1]/tile-index",-1);
   1022 setprop(lw~"tiles/tile[1]/code","");
   1023 setprop(lw~"tiles/tile[1]/timestamp-sec",weather_dynamics.time_lw);
   1024 setprop(lw~"tiles/tile[1]/orientation-deg",alpha);
   1025
   1026 x = 40000.0; y = 40000.0;
   1027 setprop(lw~"tiles/tile[2]/latitude-deg",blat + get_lat(x,y,phi));
   1028 setprop(lw~"tiles/tile[2]/longitude-deg",blon + get_lon(x,y,phi));
   1029 setprop(lw~"tiles/tile[2]/generated-flag",0);
   1030 setprop(lw~"tiles/tile[2]/tile-index",-1);
   1031 setprop(lw~"tiles/tile[2]/code","");
   1032 setprop(lw~"tiles/tile[2]/timestamp-sec",weather_dynamics.time_lw);
   1033 setprop(lw~"tiles/tile[2]/orientation-deg",alpha);
   1034
   1035 x = -40000.0; y = 0.0;
   1036 setprop(lw~"tiles/tile[3]/latitude-deg",blat + get_lat(x,y,phi));
   1037 setprop(lw~"tiles/tile[3]/longitude-deg",blon + get_lon(x,y,phi));
   1038 setprop(lw~"tiles/tile[3]/generated-flag",0);
   1039 setprop(lw~"tiles/tile[3]/tile-index",-1);
   1040 setprop(lw~"tiles/tile[3]/code","");
   1041 setprop(lw~"tiles/tile[3]/timestamp-sec",weather_dynamics.time_lw);
   1042 setprop(lw~"tiles/tile[3]/orientation-deg",alpha);
   1043
   1044 # this is the current tile
   1045 x = 0.0; y = 0.0;
   1046 setprop(lw~"tiles/tile[4]/latitude-deg",blat + get_lat(x,y,phi));
   1047 setprop(lw~"tiles/tile[4]/longitude-deg",blon + get_lon(x,y,phi));
   1048 setprop(lw~"tiles/tile[4]/generated-flag",1);
   1049 setprop(lw~"tiles/tile[4]/tile-index",1);
   1050 setprop(lw~"tiles/tile[4]/code","");
   1051 setprop(lw~"tiles/tile[4]/timestamp-sec",weather_dynamics.time_lw);
   1052 setprop(lw~"tiles/tile[4]/orientation-deg",getprop(lw~"tmp/tile-orientation-deg"));
   1053
   1054
   1055 x = 40000.0; y = 0.0;
   1056 setprop(lw~"tiles/tile[5]/latitude-deg",blat + get_lat(x,y,phi));
   1057 setprop(lw~"tiles/tile[5]/longitude-deg",blon + get_lon(x,y,phi));
   1058 setprop(lw~"tiles/tile[5]/generated-flag",0);
   1059 setprop(lw~"tiles/tile[5]/tile-index",-1);
   1060 setprop(lw~"tiles/tile[5]/code","");
   1061 setprop(lw~"tiles/tile[5]/timestamp-sec",weather_dynamics.time_lw);
   1062 setprop(lw~"tiles/tile[5]/orientation-deg",alpha);
   1063
   1064 x = -40000.0; y = -40000.0;
   1065 setprop(lw~"tiles/tile[6]/latitude-deg",blat + get_lat(x,y,phi));
   1066 setprop(lw~"tiles/tile[6]/longitude-deg",blon + get_lon(x,y,phi));
   1067 setprop(lw~"tiles/tile[6]/generated-flag",0);
   1068 setprop(lw~"tiles/tile[6]/tile-index",-1);
   1069 setprop(lw~"tiles/tile[6]/code","");
   1070 setprop(lw~"tiles/tile[6]/timestamp-sec",weather_dynamics.time_lw);
   1071 setprop(lw~"tiles/tile[6]/orientation-deg",alpha);
   1072
   1073 x = 0.0; y = -40000.0;
   1074 setprop(lw~"tiles/tile[7]/latitude-deg",blat + get_lat(x,y,phi));
   1075 setprop(lw~"tiles/tile[7]/longitude-deg",blon + get_lon(x,y,phi));
   1076 setprop(lw~"tiles/tile[7]/generated-flag",0);
   1077 setprop(lw~"tiles/tile[7]/tile-index",-1);
   1078 setprop(lw~"tiles/tile[7]/code","");
   1079 setprop(lw~"tiles/tile[7]/timestamp-sec",weather_dynamics.time_lw);
   1080 setprop(lw~"tiles/tile[7]/orientation-deg",alpha);
   1081
   1082 x = 40000.0; y = -40000.0;
   1083 setprop(lw~"tiles/tile[8]/latitude-deg",blat + get_lat(x,y,phi));
   1084 setprop(lw~"tiles/tile[8]/longitude-deg",blon + get_lon(x,y,phi));
   1085 setprop(lw~"tiles/tile[8]/generated-flag",0);
   1086 setprop(lw~"tiles/tile[8]/tile-index",-1);
   1087 setprop(lw~"tiles/tile[8]/code","");
   1088 setprop(lw~"tiles/tile[8]/timestamp-sec",weather_dynamics.time_lw);
   1089 setprop(lw~"tiles/tile[8]/orientation-deg",alpha);
   1090 }

At first glance, this seems like a fairly repetitive and redundant block of code, so it could probably be simplified easily:

   var create_neighbours = func (blat, blon, alpha)        {
   var phi = alpha * math.pi/180.0;
   calc_geo(blat);
   var index=0;
   var pos = [  [-40000.0,40000.0], [0.0, 40.000], [40000.0, 40000.0], [-40000, 0],  [0,0], [40000,0], [-40000,-40000], [0,-40000], [40000,-40000] ];
   foreach (var p;pos) {
   x=p[0]; y=p[1];
   setprop(lw~"tiles/tile[index]/latitude-deg",blat + get_lat(x,y,phi));
   setprop(lw~"tiles/tile[index]/longitude-deg",blon + get_lon(x,y,phi));
   setprop(lw~"tiles/tile[index]/generated-flag",0);
   setprop(lw~"tiles/tile[index]/tile-index",-1);
   setprop(lw~"tiles/tile[index]/code","");
   setprop(lw~"tiles/tile[index]/timestamp-sec",weather_dynamics.time_lw);
   setprop(lw~"tiles/tile[index]/orientation-deg",alpha);
   index=index+1;
     }
   }

Loops

Nasal has several ways to implement an iteration.

for, while, foreach, and forindex loops

Nasal's looping constructs are mostly C-like:

for(var i=0; i < 3; i = i+1) {
 # loop body
 }
while (condition) {
# loop body
}

The differences are that there is no do{}while(); construct, and there is a foreach, which takes a local variable name as its first argument and a vector as its second:

 foreach(elem; list1) { doSomething(elem); }  # NOTE: the delimiter is a SEMICOLON ;

The hash/vector index expression is an lvalue that can be assigned as well as inspected:

 foreach(light; lights) { lightNodes[light] = propertyPath; }

To walk through all elements of a hash, for a foreach loop on the keys of they hash. Then you call pull up the values of the hash using the key. Example:

myhash= {first: 1000, second: 250, third: 25.2 };
foreach (var i; keys (myhash)) {
  #multiply each value by 2:
  myhash[i] *= 2; 
  #print the key and new value:
  print (i, ": ", myhash[i]);
}

There is also a "forindex", which is like foreach except that it assigns the index of each element, instead of the value, to the loop variable.

forindex(i; list1) { doSomething(list1[i]); }

Also, braceless blocks work for loops equally well:

var c=0;
while( c<5 )
 print( c+=1 );
print("end of loop\n");

settimer loops

Loops using while, for, foreach, and forindex block all of FlightGear's subsystems that run in the main thread, and can, thus, only be used for instantaneous operations that don't take too long.

For operations that should continue over a longer period, one needs a non-blocking solution. This is done by letting functions call themselves after a timed delay:

var loop = func {
    print("this line appears once every two seconds");
    settimer(loop, 2);
}

loop();        # start loop

Note that the settimer function expects a function object (loop), not a function call (loop()) (though it is possible to make a function call return a function object--an advanced functional programming technique that you won't need to worry about if you're just getting started with Nasal).

The fewer code FlightGear has to execute, the better, so it is desirable to run loops only when they are needed. But how does one stop a loop? A once triggered timer function can't be revoked. But one can let the loop function check an outside variable and refuse calling itself, which makes the loop chain die off:

var running = 1;
var loop = func {
    if (running) {
        print("this line appears once every two seconds");
        settimer(loop, 2);
    }
}

loop();        # start loop ...
...
running = 0;   # ... and let it die

Unfortunately, this method is rather unreliable. What if the loop is "stopped" and a new instance immediately started again? Then the running variable would be 1 again, and a pending old loop call, which should really finish this chain, would happily continue. And the new loop chain would start, too, so that we would end up with two loop chains.

This can be solved by providing each loop chain with a loop identifier and letting the function end itself if the id doesn't match the global loop-id. Self-called loop functions need to inherit the chain id. So, every time the global loop id is increased, all loop chains die, and a new one can immediately be started.

var loopid = 0;
var loop = func(id) {
    id == loopid or return;           # stop here if the id doesn't match the global loop-id
    ...
    settimer(func { loop(id) }, 2);   # call self with own loop id
}

loop(loopid);       # start loop
...
loopid += 1;        # this kills off all pending loops, as none can have this new identifier yet
...
loop(loopid);       # start new chain; this can also be abbreviated to:  loop(loopid += 1);

More information about the settimer function is below

OOP - Object Oriented Programming

In Nasal, objects ("classes") are regular hashes. Self-reference and inheritance are implemented through special variables me and parents. To get a better understanding of the concept, let's start with the very basics.


Hashes

Hashes, also known as "dictionaries" in Python or "maps" in C++/STL are data structures that hold key/value pairs in a way that allows quick access to a value via its key.

var airport = {
    "LOXZ": "Zeltweg",
    "LOWI": "Innsbruck",
    "LOXL": "Linz Hoersching",     # the last comma is optional
};

print(airport["LOXZ"]);            # prints "Zeltweg"
airport["LOXA"] = "Aigen";         # adds LOXA to the hash

The built-in function keys() returns a vector with the keys of the hash. The function values() returns a vector with the values of the hash. For example:

 debug.dump (keys(airport)); #prints ['LOXZ', 'LOWI', 'LOXL']
 debug.dump (values (airport)); #prints ['Zeltweg', 'Innsbruck', 'Linz Hoersching'] 

The quotes around keys can be left away in a hash definition if the key is a valid variable name or a number. This works just as well:

var airport = {
    LOXZ: "Zeltweg",
};

There's also an alternative way to access hash members if the keys are valid variable names: airport.LOXI can be used instead of airport["LOXI"]. There is a difference, though, which is described in the next section.

Note that assigning a hash (or a vector) to another variable does never copy the contents. It only creates another reference to the same data structure. So manipulating the hash via its new name does in fact change the one, original hash.

var a = airport;
a.LOXL = "Linz";           # same as airport.LOXL!
print(airport.LOXL);       # prints now "Linz", not "Linz Hoersching"

(True copies of vectors can be made by assigning a full slice: var copy = vec[:]. There's no such method for hashes.)

Self-reference: "me"

Values stored in a hash can be of any type, even of type function. Member functions ("methods") can reference their own enclosing hash via reserved keyword me. This is comparable to the this keyword in C++ classes, or the self keyword in Python.

var value = "test";

var data = {
    value: 23,                         # scalar member variable
    write1: func { print(value); },    # function member
    write2: func { print(me.value); }, # function member
};

data.write1();     # prints "test"
data.write2();     # prints 23

The above example is already a simple form of an object. It has its own variable namespace (data), its own methods, and it can be passed around by-reference as one unit. Such classes are sometimes called singleton classes, as they are unique, with no independent class instances. They mostly serve as a way to keep data and methods nicely encapsulated within a Nasal module. Often they contain a method for initializing, which is usually called init.


Inheritance: "parents"

What we learned about me in the last section is only half the truth. "me" doesn't only reference an object's own hash, but also one or more parent hashes. parents is another reserved keyword. It denotes a vector referencing other object hashes, which are "inherited" that way.

Please note that Nasal's currently supported form of encapsulation does not provide support for any form of data/information hiding (restricting access), i.e. all hash fields (but also all hash methods) are always publicly accessible (so there's nothing like the "private" or "protected" keywords in C++: in this sense, Nasal's inheritance mechanism can be thought of like C++ structs which are also public by default).

The major difference being, that all members (functions and fields) are also always mutable, which means that functions can modify the behavior of other functions quite easily, this also applies to the parents vector, too.

var parent_object = {
    value: 123,
};

var object = {
    parents: [parent_object],
    write: func { print(me.value) },
};

object.write();    # prints 123

Even though object itself doesn't contain a member value, it finds and uses the one of its parent object. parents is a vector that can contain several parent objects. These are then searched in the order from left to right, until a matching member variable or method is found. Each of the parents can itself have parents, which are all recursively searched.

In the section about hashes it was said that hash members can be accessed in two alternative ways, and that's also true for methods. object.write() could also be called as object["write"](). But only in the first form will members also be searched in parent hashes if not found in the base hash, whereas the second form creates an error if it's not a direct member.

Creating class instances

With me and parents we can implement a class object and create independent instances from that:

var Class = {
    write:     func { print(me.value); },
    increment: func { me.value += 1; },
};

var instance1 = { parents: [Class], value: 123 };
var instance2 = { parents: [Class], value: 456 };

instance1.write();    # prints 123
instance2.write();    # prints 456

As you can see, the two class instances are separate, independent objects, which share another object as parent -- they "inherit" from object Class. One can now easily change members of any of these three objects. The following will redefine the parent's write method, and all instances will automatically use this new version:

Class.write = func { print("VALUE = " ~ me.value) }

But one can also add a method to just one instance:

instance1.write = func { print("VALUE = " ~ me.value) }

Because instance1 does now have its own write method, the parents won't be searched for one, so Class.write is now overridden by instance1's own method. Nothing changed for instance2 -- it will still only find and use Class.write via its parent.

Note, the we couldn't create a class instance by simple assignment, because, as we learned above, this wouldn't create a separate copy of the Class object. All "instances" would reference the same hash!

var bad_instance1 = Class;   # bad
var bad_instance2 = Class;   # bad

bad_instance1.value = 123;   # sets Class.value to 123
bad_instance2.value = 456;   # sets Class.value to 456

bad_instance1.write();       # prints 456, not 123


Constructor

Defining each class instance by explicitly creating a hash with parents is clumsy. It is nicer to have a function that does that for us. Then we can also use function arguments to initialize members of this instance.

var new_class = func(val) {
    return { parents: [Class], value: val };
}

var instance1 = new_class(123);
var instance2 = new_class(456);

instance1.write();   # prints 123
instance2.write();   # prints 456

Because the class generating function new_class() really belongs to class Class, it would be nicer to put it into the class hash as well. In this case we call it a class "constructor", and as a convention, give it the name new. It could have any name, though, and there could be more than one constructor.

var Class = {
    new: func(val) {
        return { parents: [Class], value: val };
    },
    write: func {
        print("VALUE=" ~ me.value);
    },
};

var instance1 = Class.new(123);
var instance2 = Class.new(456);

As you can see, new() doesn't return a copy of Class, but rather a small hash that contains only a list of parents and one individual member value.

Classes aren't always as simple as in our example. Usually they contain several members, of which some may have yet to be calculated in the constructor. In that case it's easier to create a local object hash first, and to let the constructor finally return it. Such local hashes are often named m (as a short reference to me), or obj.

var Class = {
    new: func(val) {
        var m = { parents: [Class] };
        m.value = val;
        return m;
    },
    write: func {
        print("VALUE=" ~ me.value);
    },
};

This last example is the most frequently used form of class definitions in FlightGear-Nasal.


Destructor

There's no such thing in Nasal. In other languages destructors are automatically called when the class gets destroyed, so that memory and other resources that were allocated by the constructor can be freed. In Nasal that's all done by the Garbage Collector (GC), anyway. In the FlightGear context, however, there are resources that should get freed. Listeners should get removed, self-calling functions ("loops") stopped. For that it's recommended to create a destructor function and to call that manually. Such functions are often called del, similar to Python and to pair nicely with the three-letter constructor name new.


Memory management

Finally, as you know now, Nasal, being a dynamic programming language, doesn't require or support any manual memory management, so unlike C++, you don't need to call operators like "new" or "delete" to allocate or free your memory.

However, if you do know that you don't need a certain variable anymore, you can certainly give a hint to the built-in garbage collector to free it, by assigning a "nil" value to it.

This can certainly pay off when using more complex data structures such as nested vectors or hashes, because it will tell the built-in garbage collector to remove all references to the corresponding symbols, so that they can be freed.

It is also possible to make use of Nasal's delete() function to remove a symbol from a namespace (hash).

So, if you are concerned about your script's memory requirements, using a combination of setting symbols to nil, or deleting them as appropriate, would allow you to create helper functions for freeing data structures easily.

In addition, it is probably worth noting that this is also the only way to sanely reset an active Nasal namespace or even the whole interpreter. You need to do this in order to reload or re-initialize your code without restarting the whole FlightGear session Nasal_scripting_language#Managing_timers_and_listeners.

Obviously, you should first of all ensure that there is no more code running, this includes any registered listeners or timers, but also any others loops or recursive functions.

Thus, if you'd like to reload a Nasal source file at run time, you should disable all running code, and then reset the corresponding namespace, too. This is to ensure that you get a clean and consistent namespace.

Nasal provides a number of core library functions to manipulate namespaces, such as:

  • caller() - to get a strack trace of active functions currently on the Nasal stack
  • compile() - to compile new Nasal code "on the fly", i.e. dynamically from a string
  • closure() - to query the lexical namespace of active functions
  • bind() - to create new function objects

More information is available here: http://www.plausible.org/nasal/lib.html

If, on the other hand, you are using these data structures in some repeated fashion, it might make sense to keep the data structure itself around and simply re-use it next time (overwriting data as required), instead of always allocating/creating a new one, this is called "caching" and can pay off from a performance perspective.

Multiple inheritance

A class can inherit from one or more other classes. It can then access all methods and class members of all parent classes, but also override them and add additional members.

var A = {                                            # simple class A
    new: func {
        return { parents: [A] };
    },
    alpha: func print("\tALPHA"),
    test:  func print("\tthis is A.test"),
};

var B = {                                            # simple class B
    new: func(v) {                                   # ... whose constructor takes an argument
        return { parents: [B], value: v };
    },
    bravo: func print("\tBRAVO"),
    test:  func print("\tthis is B.test"),
    write: func print("\tmy value is: ", me.value),
},

var C = {                                            # class C that inherits ...
    new: func(v) {
        return { parents: [C, A.new(), B.new(v)] };  # ... from class A and B
    },
    charlie: func print("\tCHARLIE"),
    test:    func print("\tthis is C.test"),         # overrides A.test() and B.test()
};


print("A instance");
var a = A.new();
a.alpha();

print("B instance");
var b = B.new(123);
b.bravo();
b.write();

print("C instance");
var c = C.new(456);
c.alpha();                        # use alpha from the A parent
c.bravo();                        # use bravo from the B parent
c.charlie();                      # use charlie from C itself
c.test();                         # use C.test(), which overrides A.test() and B.test()
c.write();

Even if a class overrides a method of a parent with the same name, the parent's version can still be accessed via parents vector.

c.test()               # use C.test()
c.parents[0].test();   # use C.test()
c.parents[1].test();   # use A.test()
c.parents[2].test();   # use B.test()


More on methods

Methods are function members of a class hash. They can access other class members via the me variable, which is a reference to the class hash. For this reason, a method returning me can be used like the class itself, and one can apply further methods to the return value (this is usually called "method chaining"):

var Object = {
    new: func(coords...) {
        return { parents: [Object], coords: coords };
    },
    rotate: func(angle) {
        # do the rotation
        return me;
    },
    scale: func(factor) {
        # do the scaling
        return me;
    },
    translate: func(x, y) {
        # do the translation
        return me;
    },
};

var triangle = Object.new([0, 0], [10, 0], [5, 7]);
triangle.translate(-9, -4).scale(5).rotate(33).translate(9, 4);    # concatenated methods thanks to "me"


me, however, is only known in the scope of the class. If a method is to be called as a listener callback or a timer function, me has to get wrapped in a function, so that it's stored in the function closure.

var Manager = {
    new: func {
        return { parents: [Manager] };
    },
    start_timers: func {  
        settimer(do_stuff, 5);            # BAD: there's no "do_stuff" function in the scope
        settimer(me.do_stuff, 5);         # BAD: function exists, but "me" won't be known
                                          #      when the timer function is actually executed
        settimer(func me.do_stuff(), 5);  # GOOD: new function object packs "me" in the closure

        setlistener("/sim/foo", func me.do_stuff());  # GOOD  (same as with timers) 
    },         
    do_stuff: func {
        print("doing stuff");
    },
};

var manager = Manager.new();
manager.start_timers();

Exception handling

die() aborts a function with an error message (this can be compared to the throw() mechanism in C++).

var divide = func(a, b) {
    if (b == 0)
        die("division by zero");
    return a / b;     # this line won't be reached if b == 0
}

die() is also used internally by built-in extension functions or Nasal core functions. getprop("/4me"), for example, dies with an error message "name must begin with alpha or '_'". Now assume we want to write a dialog where the user can type a property path into an input field, and we display the property's value in a popup dialog. What if the user typed an invalid path and we hand that over to getprop()? We don't want Nasal to abort our code because of that. We want to display a nice error message instead. The call() function can catch die() exceptions:

var value = getprop(property);                                    # dies if 'property' is invalid
var value = call(func getprop(property), nil, var err = []);      # catches invalid-property-exception and continues

The second line calls getprop(property) just like the first, and returns its value. But if 'property' was invalid then the call() function catches the exception and sets the 'err' vector instead. That vector remains empty on success.

if (size(err))
    print("ERROR: bad property ", property, " (", err[0], ")");   # err[0] contains the die() message
else
    print("value of ", property, " is ", value);

The first argument of call() is a function object, the second a vector of function arguments (or nil), and the third a vector where the function will return a possible error. For more information on the call() function see the Nasal library documentation.

die() doesn't really care about what its argument is. It doesn't have to be a string, and can be any variable, for example a class. This can be used to pass values through a chain of functions.

var Error = {                                                             # exception class
    new: func(msg, number) {
        return { parents: [Error], message: msg, number: number };
    },
};

var A = func(a) {
    if (a < 0)
        die(Error.new("negative argument to A", a));                      # throw Error
    return "A received " ~ a;
}

var B = func(val) {
    var result = A(val);
    print("B finished");      # this line is not reached if A threw an exception
    return result;
}

var value = call(B, [-4], var err = []);                                  # try B(-4)

if (size(err)) {                                                          # catch (...)
    print("ERROR: ", err[0].message, "; bad value was ", err[0].number);
    die(err[0]);                                                          # re-throw
} else {
    print("SUCCESS: ", value);
}

Listeners and Signals

Listeners are callback functions that are attached to property nodes. They are triggered whenever the node is written to, or, depending on the listener type, also when children are added or removed, and when children are written to. Unlike polling loops, listeners don't have the least effect on the frame rate when they aren't triggered, which makes them preferable to monitor properties that aren't written to frequently.

setlistener() vs. _setlistener()

You are requested *not* to use the raw _setlistener() function, except in files in $FG_ROOT/Nasal/ when they are needed immediately. Only then the raw function is required, as it doesn't rely on props.nas.

When listeners don't work

Unfortunately, listeners don't work on so-called "tied" properties when the node value isn't set via property methods. (You can spot such tied properties by Ctrl-clicking the "." entry in the property browser: they are marked with a "T".) Most of the FDM properties are "tied".

Examples of properties where setlistener won't work:

  • /position/elevation-ft
  • /ai/models/aircraft/orientation/heading-deg
  • Any property node created as an alias
  • Lots of others

Before working to create a listener, always check whether a listener will work with that property node by control-clicking the "." in property browser to put it into verbose mode, and then checking whether the property node for which you want to set up a listener is marked with a "T" or not.

If you can't set a listener for a particular property, the alternative is to use settimer to set up a timer loop that checks the property value regularly.

Listeners are most efficient for properties that change only occasionally. No code is called at all during frames where the listener function is not called. If the property value changes every frame, setting up a settimer loop with time=0 will execute every frame, just the same as setlistener would, and the settimer loop is more efficient than setting a listener. This is one reason the fact the setlistener doesn't work on certain tied and FDM properties is not a great loss. See the section on timer loops below.

setlistener()

Syntax:

var listener_id = setlistener(<property>, <function> [, <startup=0> [, <runtime=1>]]);

The first argument is a property node object (props.Node() hash) or a property path. Because the node hash depends on the props.nas module being loaded, setlistener() calls need to be deferred when used in an $FG_ROOT/Nasal/*.nas file, usually by calling them in a settimer(func {}, 0) construction. To avoid that, one can use the raw _setlistener() function directly, for which setlistener() is a wrapper. The raw function does only accept node paths (e.g. "/sim/menubar/visibility"), but not props.Node() objects.

The second argument is a function object (not a function call!). The func keyword turns code into a function object.

The third argument is optional. If it is non-null, then it causes the listener to be called initially. This is useful to let the callback function pick up the node value at startup.

The fourth argument is optional, and defaults to 1. This means that the callback function will be executed whenever the property is written to, independent of the value.

If the argument is set to 0, then the function will only get triggered if a value other than the current value is written to the node. This is important for cases where a property is written to once per frame, no matter if the value changed or not. YASim, for example, does that for /gear/gear/wow or /gear/launchbar/state. So, this should be used for properties that are written to in every frame, although the written value is mostly the same. If the argument is 2, then also write access to children will get reported, as well as the creation and removal of children nodes.

For both optional flags 0 means less calls, and 1 means more calls. The first is for startup behavior, and the second for runtime behavior.

Here's a real-life example:

 setlistener("/gear/launchbar/state", func {
     if (cmdarg().getValue() == "Engaged")
         setprop("/sim/messages/copilot", "Engaged!");
 }, 1, 0);

YASim writes once per frame the string "Disengaged" to property /gear/launchbar/state. When an aircraft on deck of the aircraft carrier locks into the catapult, this changes to "Engaged", which is then written again in every frame, until the aircraft leaves the catapult. Because the locking in is a bit difficult -- one has to target the sensitive area quite exactly --, it was desirable to get some quick feedback: a screen message that's also spoken by the Festival speech synthesis. With the args 1 and 0, this is done initially (for the unlikely case that we are locked in from the beginning), and then only when the node changes from an arbitrary value to "Engaged".

setlistener() returns a unique listener id on success, and nil on error. The id is nothing else than a counter that is 0 for the first Nasal listener, 1 for the second etc. You need this id number to remove the listener. Most listeners are never removed, so that one doesn't assign the return value, but simply drop it.

Listener callback functions can access up to four values via regular function arguments, the first two of which are property nodes in the form of a props.Node() object hash.

If you have set a callback function named myCallbackFunc via setlistener (setlistener(myNode, myCallbackFunc)), you can use this syntax in the callback function:

myCallbackFunc ([<changed_node> [, <listened_to_node> [, <operation> [, <is_child_event>]]]])

removelistener()

Syntax:

var num_listeners = removelistener(<listener id>);

removelistener() takes one argument: the unique listener id that a setlistener() call returned. It returns the number of remaining active Nasal listeners on success, nil on error, or -1 if a listener function applies removelistener() to itself. The fact that a listener can remove itself, can be used to implement a one-shot listener function:

var L = setlistener("/some/property", func {
    print("I can only be triggered once.");
    removelistener(L);
});


Listener Examples

The following example attaches an anonymous callback function to a "signal". The function will be executed when FlightGear is closed.

setlistener("/sim/signals/exit", func { print("bye!") });


Instead of an anonymous function, a named function can be used as well:

var say_bye = func { print("bye") }
setlistener("/sim/signals/exit", say_bye);

Callback functions can, optionally, access up to four parameters which are handed over via regular function arguments. Many times none of these parameters is used at all, as in the above example.

Most often, only the first parameter is used--which gives the node of the changed value.

The following code attaches the monitor_course() function to a gps property, using the argument course to get the node with the changed value.

var monitor_course = func(course) {
    print("Monitored course set to ", course.getValue());
}
var i = setlistener("instrumentation/gps/wp/leg-course-deviation-deg", monitor_course);

# here the listener is active

removelistener(i);                    # remove that listener again

Here is code that accesses two arguments--the changed node and the listened-to node (these may be different when monitoring all children of a certain node)--and also shows how to monitor changes to a node including changes to children:

var monitor_course = func(course, flightinfo) {
    print("One way to get the course setting: ", flightinfo.leg-course-deviation-deg.getValue());
    print("Another way to get the same setting ", course.getValue());
}
var i = setlistener("instrumentation/gps/wp", monitor_course, 0, 2);


The function object doesn't need to be a separate, external function -- it can also be an anonymous function made directly in the setlistener() call:

setlistener("/sim/signals/exit", func { print("bye") });    # say "bye" on exit

Beware, however, that the contents of a function defined within the setlistener call are not evaluated until the call is actually made. If, for instance, local variables change before the setlistener call happens, the call will reflect the current value of those variables at the time the callback function is called, not the value at the time the listener was set.

For example, with this loop, the function will always return the value 10--even if mynode[1], mynode[2], mynode[3] or any of the others is the one that changed. It is because the contents of the setlistener are evaluated after the loop has completed running and at that point, i=10:

var output = func(number) {
    print("mynode", number, " has changed!"); #This won't work!
}
for(i=1; i <= 10; i = i+1) {
   var i = setlistener("mynode["~i~"]", func{ output (i); });
}

You can also access the four available function properties (or just one, two, or three of them as you need) in your anonymous function. Here is an example that accesses the first value:

for(i=1; i <= 10; i = i+1) {
   var i = setlistener("mynode["~i~"]", func (changedNode) { print (changedNode.getPath() ~ " : " ~ changedNode.getValue()); });
}

Attaching a function to a node that is specified as props.Node() hash:

var node = props.globals.getNode("/sim/signals/click", 1);
setlistener(node, func { gui.popupTip("don't click here!") });

Sometimes it is desirable to call the listener function initially, so that it can pick up the node value. In the following example a listener watches the view number, and turns the HUD on in cockpit view, and off in all other views. It doesn't only do that on writing to "view-number", but also once when the listener gets attached, thanks to the third argument "1":

setlistener("/sim/current-view/view-number", func(n) {
    setprop("/sim/hud/visibility[0]", n.getValue() == 0);
}, 1);

There's no limit for listeners on a node. Several functions can get attached to one node, just as one function can get attached to several nodes. Listeners may write to the node they are listening to. This will not make the listener call itself causing an endless recursion.

Signals

In addition to "normal" nodes, there are "signal" nodes that were created solely for the purpose of having listeners attached:

/sim/signals/exit ... set to "true" on quitting FlightGear

/sim/signals/reinit ... set to "true" right before resetting FlightGear (Shift-Esc), and to "false" afterwards

/sim/signals/click ... set to "true" after a mouse click at the terrain. Hint that the geo coords for the click spot were updated and can be retrieved from /sim/input/click/{longitude-deg,latitude-deg,elevation-ft,elevation-m}

/sim/signals/screenshot ... set to "true" right before the screenshot is taken, and set to "false" after it. Can be used to hide and reveal dialogs etc.

/sim/signals/nasal-dir-initialized ... set to "true" after all Nasal "library" files in $FG_ROOT/Nasal/ were loaded and executed. It is only set once and can only be used to trigger listener functions that were defined in one of the Nasal files in that directory. After that signal was set Nasal starts loading and executing aircraft Nasal files, and only later are settimer() functions called and the next signal is set:

/sim/signals/fdm-initialized ... set to "true" when then FDM has just finished its initialization

/sim/signals/reinit-gui ... set to "true" when the GUI has just been reset (e.g. via Help menu). This is used by the gui.Dialog class to reload Nasal-loaded XML dialogs.

/sim/signals/frame ... triggered at the beginning of each iteration of the main loop (a.k.a. "frame"). This is meant for debugging purposes. Normally, one would just use a settimer() with interval 0 for the same effect. The difference is that the signal is guaranteed to be raised at a defined moment, while the timer call may change when subsystems are re-ordered.

FlightGear extension functions

cmdarg()

cmdarg() is a mechanism to pass arguments to a nasal script (wrapped in properties) instead of "normal" function parameters. Note that cmdarg() should be primarily used in Nasal code embedded in XML files and should be considered depreciated otherwise (see [7] and [8]).

cmdarg() will keep working in (joystick) XML-bindings and on the top-level of embedded Nasal scripts (i.e. dialog and animation XML files).

As such, the cmdarg() function is primarily used for listener callbacks declared in XML markup, cmdarg() returns the listened-to property as props.Node object, so you can use it with all its methods (see $FG_ROOT/Nasal/props.nas) for example:

 print(cmdarg().getPath(), " has been changed to ", cmdarg().getValue())

The cmdarg() function avoids that you have to type the exact same path twice (once here and once in the setlistener() command) and it makes clear that this is the listened to property. Also, you can use all the nice props.Node methods on cmdarg() directly:

setlistener("/gear/launchbar/state", func {
     if (cmdarg().getValue() == "Engaged")
         setprop("/sim/messages/copilot", "Engaged!");
 }, 1, 0);

Use of cmdarg() outside of XML-bindings won't cause an error, but (still) return the last cmdarg() property. This just won't be the listened-to property anymore, but whatever the last legitimate cmdarg() user set. Most of the time it will be the property root of a joystick binding.

Don't make any assumptions and use cmdarg() only in one of these cases:

  • binding: returns root of this binding's property branch. Needed for accessing an axis' value: cmdarg().getNode("setting").getValue()
  • dialog xml files: returns root of that file's property branch in memory. This can be used to let embedded Nasal change the dialog (e.g. clear and build lists) before the final layout is decided
  • animation xml files: returns root of this model's place in /ai/models/ when used as AI/MP model. Examples: /ai/models/multiplayer[3], /ai/models/tanker[1], etc. [9]
  • AI aircraft XML files

In all cases, the cmdarg() call must not be delayed until later using settimer() or setlistener(). Because later it'll again return some unrelated property!

fgcommand()

Runs an internal "fgcommand", see $FG_ROOT/Docs/README.commands for a list of available commands: http://gitorious.org/fg/fgdata/blobs/master/Docs/README.commands

print()

Concatenates an arbitrary number of arguments to one string, appends a new-line, and prints it to the terminal. Returns the number of printed characters.

print("Just", " a ", "test");


getprop()

Returns the node value for a given path, or nil if the node doesn't exist or hasn't been initialized yet.

getprop(<path>);

Example:

print("The frame rate is ", getprop("/sim/frame-rate"), " FPS");


setprop()

Sets a property value for a given node path string. Always returns nil.

setprop(<path> [, <path>, [...]], <value>);

All arguments but the last are concatenated to a path string, with a slash (/) inserted between each element. The last value is written to the respective node. If the node isn't writable, then an error message is printed to the console.

Note: setprop() concatenates a list of input arguments by means of inserting a "/" in between. That is nice for properties, as this slash is part of the tree. However, when one wants to make use of indices, like [0], one has to concatenate by hand (using "~") inside one part of the string argument list. An example is:

 var i = 4;
 setprop("instrumentation","cdu","page["~i~"]","title","MENU");

This results in instrumentation/cdu/page[4]/title = 'MENU' (string)

Examples:

setprop("/sim/current-view/view-number", 2);
setprop("/controls", "engines/engine[0]", "reverser", 1);


Erasing a property from the property tree: a property that has been created, for example through setprop() can be erased via

 props.globals.getNode("foo/bar").remove(); 		# take out the complete node
 props.globals.getNode("/foo").removeChild("bar"); 	# take out a certain child node

settimer()

Runs a function after a given simulation time (default) or real time in seconds.

settimer(<function>, 

The first object is a function object (ie, "func { ... }"). Note that this is different from a function call (ie, "func ( ... )"). If you don't understand what this means, just remember to always enclose the first argument in any call to settimer with the word "func" and braces "{ }", and it will always work. For instance, if you want print the words "My result" in five seconds, use this code:

settimer ( func { print ( "My result"); }, 5);

Inside the braces of the func object you can put any valid Nasal code, including a function call. In fact, if you want to call a function with certain values as arguments, the way to do it is to turn it into a function object by enclosing it with a func{}, for example:

myarg1="My favorite string";
myarg2=432;
settimer ( func { myfunction ( myarg1, myarg2); }, 25);

The third argument is optional and defaults to 0, which lets the time argument be interpreted as "seconds simulation time". In this case the timer doesn't run when FlightGear is paused. For user interaction purposes (measuring key press time, displaying popups, etc.) one usually prefers real time.

# simulation time example
var copilot_annoyed = func { setprop("/sim/messages/copilot", "Stop it! Immediately!") }
settimer(copilot_annoyed, 10);
# real time example
var popdown = func ( tipArg ) { 
 fgcommand("dialog-close", tipArg); 
}

var selfStatusPopupTip = func (label, delay = 10, override = nil) {	
   var tmpl = props.Node.new({
           name : "PopTipSelf", modal : 0, layout : "hbox",
           y: 140,
           text : { label : label, padding : 6 }
   });
   if (override != nil) tmpl.setValues(override);
   
   popdown(tipArgSelf);
   fgcommand("dialog-new", tmpl);
   fgcommand("dialog-show", tipArgSelf);

   currTimerSelf += 1;
   var thisTimerSelf = currTimerSelf;

   # Final argument 1 is a flag to use "real" time, not simulated time
   settimer(func { if(currTimerSelf == thisTimerSelf) { popdown(tipArgSelf) } }, delay, 1);
}

More information about best practices for using the settimer function to create loops in Nasal is elsewhere on this page.

systime()

Returns epoch time (time since 1972/01/01 00:00) in seconds as a floating point number with high resolution. This is useful for benchmarking purposes.

 #benchmarking example:
 var start = systime();
 how_fast_am_I(123);
 var end = systime();
 print("took ", end - start, " seconds");

carttogeod()

Converts cartesian coordinates x/y/z to geodetic coordinates lat/lon/alt, which are returned as a vector. Units are degree and meter.

var geod = carttogeod(-2737504, -4264101, 3862172);
print("lat=", geod[0], " lon=", geod[1], " alt=", geod[2]);

# outputs
lat=37.49999782141546 lon=-122.6999914632327 alt=998.6042055172776


geodtocart()

Converts geodetic coordinates lat/lon/alt to cartesian coordinates x/y/z. Units are degree and meter.

var cart = geodtocart(37.5, -122.7, 1000); # lat/lon/alt(m)
print("x=", cart[0], " y=", cart[1], " z=", cart[2]);

# outputs
x=-2737504.667684828 y=-4264101.900993474 z=3862172.834656495


geodinfo()

Returns information about geodetic coordinates. Takes two arguments: lat, lon (in degree) and returns a vector with two entries, or nil if no information could be obtained because the terrain tile wasn't loaded. The first entry is the elevation (in meters) for the given point, and the second is a hash with information about the assigned material, or nil if there was no material information available, because there is, for instance, an untextured building at that spot or the scenery tile is not loaded.

var lat = getprop("/position/latitude-deg");
var lon = getprop("/position/longitude-deg");
var info = geodinfo(lat, lon);

if (info != nil) {
    print("the terrain under the aircraft is at elevation ", info[0], " m");
    if (info[1] != nil)
        print("and it is ", info[1].solid ? "solid ground" : "covered by water");
}

A full data set looks like this:

debug.dump(geodinfo(lat, lon));

# outputs
[ 106.9892101062052, { light_coverage : 0, bumpiness : 0.5999999999999999, load_resistance : 1e+30,
solid : 0,  names : [ "Lake", "Pond", "Reservoir", "Stream", "Canal" ], friction_factor : 1, 
rolling_friction : 1.5 } ]

Note that geodinfo is a *very* CPU intensive operation, particularly in FG 2.4.0 and earlier, so use sparingly (discussion here).

parsexml()

This function is an interface to the built-in Expat XML parser. It takes up to five arguments. The first is a mandatory absolute path to an XML file, the remaining four are optional callback functions, each of which can be nil (which is also the default value).

var ret = parsexml(<path> [, <start-elem> [, <end-elem> [,  [, <pi> ]]]]);

<start-elem>  ... called for every starting tag with two arguments: the tag name, and an attribute hash
<end-elem>    ... called for every ending tag with one argument: the tag name
        ... called for every piece of data with one argument: the data string
<pi>          ... called for every "processing information" with two args: target and data string

<ret>         ... the return value is nil on error, and the <path> otherwise

Example:

var start = func(name, attr) {
    print("starting tag ", name);
    foreach (var a; keys(attr))
        print("\twith attribute ", a, "=", attr[a]);
}
var end = func(name) { print("ending tag ", name) }
var data = func(data) { print("data=", data) }
var pi = func(target, data) { print("processing instruction: target=", target, " data=", data) }
parsexml("/tmp/foo.xml", start, end, data, pi);

airportinfo()

Function for retrieval of airport/runway information. Usage:

 var apt = airportinfo("KHAF");   # get info about KHAF
 var apt = airportinfo(lat, lon); # get info about apt closest to lat/lon
 var apt = airportinfo();         # get info about apt closest to aircraft  

The command debug.dump(airportinfo("KHAF")) outputs this:

 { lon : -122.4962626410256, lat : 37.51343502564102, has_metar : 0,
 runways : { 12 : { stopway2 : 0, threshold1 : 232.5624,
 lon : -122.5010889999999, lat : 37.513831, stopway1 : 0, width : 45.72,
 threshold2 : 232.5624, heading : 138.1199999999999, length : 1523.0856 } },
 elevation : 20.42159999999999, id : "KHAF", name : "Half Moon Bay" }

That is: a hash with elements lat/lon/elev/id/name/has_metar for the airport, and a hash with runways, each of which consists of lat/lon/ /length/width/heading/threshold[12]/stopway[12]. Only one side of each runway is listed -- the other can easily be deduced.

Built-in functions

sort(vector, function)

Creates a new vector containing the elements in the input vector sorted in ascending order according to the rule given by function, which takes two arguments (elements of the input vector) and should return less than zero, zero, or greater than zero if the first argument is, respectively, less than, equal to, or greater than the second argument. Despite being implemented with ANSI C qsort(), the sort is stable; "equal" elements in the output vector will appear in the same relative order as they do in the input.

Because you can define the sort function, sort allows you to create a list of keys sorting a hash by any criterion--by key, value, or (if, for instance the hash values are hashes themselves) any subvalue.

vec = [100,24,45];
sortvec = sort (vec, func (a,b) cmp (a,b));
debug.dump (sortvec); #output is [24,45,100]

Here is an example of how to output the contents of a hash in sorted order. Note that the function does not actually sort the hash but returns a list of the hash keys in sorted order.

var airport = {
  "LOXZ": "Zeltweg",
  "LOWI": "Innsbruck",
  "LOXL": "Linz Hoersching",     # the last comma is optional
};

var sortedkeys= sort (keys(airport), func (a,b) cmp (airport[a], airport[b]));

foreach (var i; sortedkeys) 
 print (i, ": ", airport[i]);

The output is:

  LOWI: Innsbruck
  LOXL: Linz Hoersching
  LOXZ: Zeltweg  

If the hash values are themselves hashes, sorting by any of the subvalues is possible. For example:

var airport = {
   "LOXZ": {city: "Zeltweg", altitude_m: 1300 },
   "LOWI": {city: "Innsbruck", altitude_m: 2312 }, 
   "LOXL": {city: "Linz Hoersching", altitude_m: 1932 },
};
 
#return a list of the hash keys sorted by altitude_m
var sortedkeys= sort (keys(airport), func (a,b) airport[a].altitude_m - airport[b].altitude_m);
 
foreach (var i; sortedkeys) 
 print (i, ": ", airport[i].city, ", ", airport[i].altitude_m);

Note that sort will return errors, and in FG 2.4.0 may even stop working, if the sort function you provide returns errors. A common cause of this is if your sort vector contains both string and numeric values. The cmp function will return an error for numeric values, and arithmetic operations you may use to sort numeric values will return errors if performed on a string. The error in these cases is typically "function/method call on uncallable object".

Other useful built-in functions

Other basic built-in Nasal functions such as append, setsize, subvec, typeof, contains, delete, int, num, keys, pop, size, streq, cmp, substr, sprintf, find, split, rand, call, die, bind, math.sin, math.pi, math.exp, math.ln math.e, io.read, io.write, regex.exec, and others of that sort, are detailed in this external document.

Useful functions in the Nasal directory

Other functions are available in the Nasal files found in the Nasal directory of a FlightGear install. Simply open those Nasal files in text editor to see what is inside. Reference those functions by putting the filename in front of the function, method, variable, or object you wish to use. For instance, to use the method Coord.new() in the file geo.nas, you simply write:

geo.Coord.new()

Distance calculations

To calculate the distance between two points (in two different ways):

# mylat1, mylong1, mylat2, mylong2 are lat & long in degrees 
# myalt1 & myalt2 are altitude in meters

var GeoCoord1 = geo.Coord.new();
GeoCoord1.set_latlon(mylat1, mylong1,myalt1);

var GeoCoord2 = geo.Coord.new();
GeoCoord2.set_latlon(mylat2, mylong2, myalt2);

var directDistance = GeoCoord1.direct_distance_to(GeoCoord2);
var surfaceDistance = GeoCoord1.distance_to(GeoCoord2);

The results are distances in meters.

  • distance_to - returns distance in meters along Earth curvature, ignoring altitudes; useful for map distance
  • direct_distance_to - returns distance in meters direct; considers altitude, but cuts through Earth surface

Other useful geographical functions

Other useful geographical functions are found in geo.nas (in the FlightGear/data/Nasal directory of a FlightGear installation). geo.nas also includes documentation/explanation of the functions available.

Developing and debugging in Nasal

Developing Nasal code

Because code in the Nasal directory is parsed only at Flightgear startup, testing and debugging Nasal code can by slow and difficult.

Flightgear provides a couple of ways to work around this issue:

Nasal Console

The Nasal Console is available in Flightgear's menu (Debug/Nasal Console). Selecting this menu opens a Nasal Console dialog.

This dialog has several tabs, of which each can hold separate Nasal code snippets, all of which are saved on exit and reloaded next time. This is useful for little tests, or for executing code for which writing a key binding is just too much work, such as "props.dump(props.globals)".

If you want to add more tabs (radio buttons in the Nasal Console dialog) to hold more code samples, just add more <code> nodes to autosave.xml.

Loading/reloading Nasal code without re-starting Flightgear

A common problem in testing and debugging Nasal programs is that each testing step requires stopping and re-starting Flightgear, a slow process.

Below is described a technique for loading and executing a Nasal file while Flightgear is running. Flightgear will parse the file, display any errors in the Flightgear console window, and then execute the code as usual.

Using this technique, you can start Flightgear, load the Nasal code you want to test observe any errors or test functionality as you wish, make changes to the Nasal file, reload it to observe parse errors or change in functionality, and so on to repeatedly and quickly run through the change/load/parse/test cycle without needing to re-start Flightgear each time.

The key to this technique is the function io.load_nasal(), which loads a nasal file into a nasal namespace.

Step-by-step instructions showing how to use this technique to load, parse, and test a Nasal file while Flightgear is running:

Create the Nasal file to test

Create a text file named $FG_ROOT/foo/test.nas with this text:

 print("hi!");
 var msg="My message.";
 var hello = func { print("I'm the test.hello() function") }

Notes: You can create the file in any directory you wish, as long as Nasal can read the directory--but the file IOrules in the Nasal directory restricts which directories Nasal may read and write from.

You can give the file any name and extension you wish, though it is generally most convenient to use the .nas extension with Nasal files.

Load the file and test

Start Flightgear. You can import the file above into Flightgear by typing the following into the Nasal Console dialog and executing the code:

 io.load_nasal(getprop("/sim/fg-root") ~ "/foo/test.nas", "example");

getprop("/sim/fg-root") gets the root directory of the FlightGear installation, ~ "/foo/test.nas" appends the directory and filename you created. The final variable "example" tells the namespace to load for the Nasal file.

You'll see the message "hi!" on the terminal, and have function "example.hello()" immediately available. You can, for instance, type "example.hello();" into one of the Nasal console windows and press "Execute" to see the results; similarly you could execute "print (example.msg);".

If you find errors or want to make changes, simply make them in your text editor, save the file, and execute the io.load_nasal() command again in the Nasal Console to re-load the file with changes.


It's worth noting that Nasal code embedded in XML GUI dialog files can be reloaded by using the "debug" menu ("reload GUI").

You may also want to check out the remarks on Memory management.

Managing timers and listeners

Note: If your Nasal program sets listeners, timer loops, and so on, they will remain set even when the code is reloaded, and reloading the code will set additional listeners and timer loops.

This can lead to extremely slow framerates and unexpected behavior. For timers you can avoid this problem by using the loopid method (described above); for listeners you can create a function to destroy all timers your Nasal program creates, and call that function before reloading the program. (And cleaning up timer loops and listeners is a best practice for creating Nasal programs in Flightgear regardless.)

The same problem may occur while resetting or re-initializing parts of FlightGear if your code isn't prepared for this. And obviously this applies in particular also to any worker threads you may have started, too!

For complex Nasal scripts with many timers and listeners, it is therefore generally a very good idea to implement special callbacks so that your scripts can respond to the most important simulator "signals", this can be achieved by registering script-specific listeners to signals like "reinit" or "freeze" (pause): the corresponding callbacks can then suspend or re-initialize the Nasal code by suspending listeners and timers. Following this practice helps ensure that your code will behave properly even during simulator resets.

In other words, it makes sense to provide a separate high-level controller routine to look for important simulator events and then pause or re-initialize your main Nasal code as required.

If you are using System-wide Nasal modules, you should register listeners to properly re-initialize and clean up your Nasal code.

In its simplest form, this could look like this:

var cleanup = func {}
setlistener("/sim/signals/reinit", cleanup);

This will invoke your "cleanup" function, whenever the "reinit" signal is set by the FlighGear core.

Obviously, you now need to populare your cleanup function with some code, too.

One of the easiest ways to do this, is removing all listeners/timers manually here, i.e. by adding calls to removelistener():

var cleanup = func {
 removelistener(id);
 removelistener(id);
 removelistener(id);
}


This would ensure that the corresponding listeners would be removed once the signal is triggered.

On the other hand, you could just as well use a vector of listener IDs here, and then use a Nasal foreach loop:

var cleanup = func(id_list) {
 foreach(var id; id_list)
  removelistener(id);
}

Obviously, this would require that you maintain a list of active listeners, too - so that you can actually pass a list of IDs to the cleanup function.

This is one of those things that can be easily done in Nasal, too - just by introducing a little helper wrapper:

var id_list=[];
var store_listener = func(id) append(id_list,id);

The only thing required here, would be replacing/wrapping the conventional "setlistener" call with calls to your helper:

store_listener( setlistener("/sim/foo") );
store_listener( setlistener("/foo/bar") );

If you were to do this consistently across all your Nasal code, you'd end up with a high level way to manage all your registered listeners centrally.

Now, you'll probably have noticed that it would make sense to consider wrapping all these helpers and variables inside an enclosing helper class, this can be accomplished in Nasal using a hash. This would enable you to to implement everything neatly organized in an object and use RAII-like patterns to manage Nasal resources like timers, listeners and even threads.

Debugging

The file debug.nas, included in the Nasal directory of the Flightgear distribution, has several functions useful for debugging Nasal code. These functions are available to any Nasal program or code executed by Flightgear.

Aside from those listed below, several other useful debugging functions are found in debug.nas; see the debug.nas file for the list of functions and explanation.

Note that the debug module makes extensive use of ANSI terminal color codes. These create colored output on Linux/Unix systems but on other systems they may add numerous visible control codes. To turn off the color codes, go to the internal property tree and set

/sim/startup/terminal-ansi-colors=0

Or within a Nasal program:

setprop ("/sim/startup/terminal-ansi-colors",0);

debug.dump

debug.dump([<variable>])             ... dumps full contents of variable or of local variables if none given

The function debug.dump() dumps the contents of the given variable to the console. On Unix/Linux this is done with some syntax coloring. For example, these lines

 var as = props.globals.getNode("/velocities/airspeed-kt", 1);
 debug.dump(as);

would output

 </velocities/airspeed-kt=1.021376474393101 (DOUBLE; T)>

The "T" means that it's a "tied" property. The same letters are used here as in the property-browser. The angle brackets seem superfluous, but are useful because debug.dump() also outputs compound data types, such as vectors and hashes. For example:

 var as = props.globals.getNode("/velocities/airspeed-kt", 1);
 var ac = props.globals.getNode("/sim/aircraft", 1);
 var nodes = [as, ac];
 var hash = { airspeed_node: as, aircraft_name: ac, all_nodes: nodes };
 debug.dump(hash);

yields:

 { all_nodes : [ </velocities/airspeed-kt=1.021376474393101 (DOUBLE; T)>,
 </sim/aircraft="bo105" (STRING)> ], airspeed_node : </velocities/airspe
 ed-kt=1.021376474393101 (DOUBLE; T)>, aircraft_name : </sim/aircraft="bo
 105" (STRING)> }

debug.backtrace

 debug.backtrace([<comment:string>]}  ... writes backtrace with local variables
 debug.bt                             ... abbreviation for debug.backtrace

The function debug.backtrace() outputs all local variables of the current function and all parent functions.


debug.benchmark

debug.benchmark(<label:string>, <func> [, <repeat:int>])

... runs function <repeat> times (default: 1) and prints execution time in seconds,prefixed with <label>.

This is extremely useful for benchmarking pieces of code to determin

debug.exit

 debug.exit()                         ... exits fgfs

Related content

External links