Nasal scripting language: Difference between revisions

From FlightGear wiki
Jump to navigation Jump to search
(Some more cleanup)
 
(26 intermediate revisions by 3 users not shown)
Line 1: Line 1:
:''Please note that a considerable amount of resources has not yet been incorporated here, you can check these out by going to the [[Talk:Nasal scripting language|discussion page]], where we are collecting links to webpages and mailing list discussions/postings related to Nasal.''
{{Nasal Navigation}}
'''Nasal''' is FlightGear's built-in scripting language. Originally written and developed by Andy Ross for a personal project, it was integrated into FlightGear in November 2003, and has been continuously developed, improved, and refined since then. Over time, it has become probably FlightGear's most powerful, and has been used to create a huge variety of systems, ranging from [[wildfire simulation|wildfires]] to [[Control Display Unit]]s.


[[FlightGear]] offers a very powerful functional '''scripting language''' called '''[http://plausible.org/nasal/ Nasal]''', which supports reading and writing of internal [[Property Tree Intro|FlightGear properties]], accessing internal data via extension functions, creating GUI dialogs and much more.  
Within FlightGear, Nasal supports the reading and writing of internal [[Property Tree|properties]], accessing internal data via extension functions, creating GUI dialogs and much, much more. Please see the right navigation bar to get additional information.


{{Template:Nasal Navigation}}
[[File:Highlight parse.png]]<!--


== Not another scripting language ==
<syntaxhighlight lang="nasal">
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.
# to be saved in $FG_ROOT/Nasal/hello.nas
 
print("Hello World!");
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 [[joystick]]s, keyboard and cockpit controls, and even in [[Howto:Nasal in scenery object XML files|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 loose 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 [[A local weather system|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":
 
{{cquote|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/ Curt Olson]}}
 
As of 03/2009, there were approximately 170,000 lines of reported Nasal source code in the FlightGear base package <ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg21333.html |title=Nasal alternatives : possible, of course, but trivial or hair pulling task? |author=Melchior Franz |date=8 March 2009 }}</ref>, compared to 2006 this is almost a rate of growth of 600% within 3 years <ref>{{cite web |url=http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg01728.html |title=FlightGear Make Process: Amazing |author=Ampere K. Hardraade |date=27 February 2006 }}</ref>. 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:
 
* [http://plausible.org/nasal/lib.html core language/library documentation]
* [http://plausible.org/nasal/sample.nas annotated source code examples]
* [http://plausible.org/nasal/doc.html Nasal design document]
* [http://www.plausible.org/nasal/flightgear.html a helpful tutorial about using Nasal in FlightGear].
 
In addition, the [http://gitorious.org/fg/fgdata/trees/master/Nasal 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.
 
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 [[:Category:Nasal|Nasal category]].
 
== Hello world ==
 
A simple hello world example in Nasal would be:
 
<syntaxhighlight lang="php">
# hello.nas
print('Hello World!');
</syntaxhighlight>
 
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:
<syntaxhighlight lang="php">
# hello.nas
print("Hello\nWorld!");
</syntaxhighlight>
 
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: [[Nasal_scripting_language#Loading.2Freloading_Nasal_code_without_re-starting_FlightGear|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.
 
<syntaxhighlight lang="php">
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
</syntaxhighlight>
 
Now you may be wondering, what the heck is a vector, and what is a hash - and where's the difference?
The difference is, elements in a vector are sequentially numbered, i.e. each element has a numeric index:
 
<syntaxhighlight lang="php">
var my_vector = ['A','B','C'];
</syntaxhighlight>
 
This initializes a vector with three elements: A, B and C.
Now, to access each element of the vector, you would need to use the element's numerical index:
 
<syntaxhighlight lang="php">
var my_vector = ['A','B','C'];
print (my_vector[0] ); #prints A
print (my_vector[1] ); #prints B
print (my_vector[2] ); #prints C
</syntaxhighlight>
 
As can be seen, indexing starts at 0.
 
Compared to vectors, hashes don't use square brackets but curly  braces instead:
<syntaxhighlight lang="php">
var my_hash = {};
</syntaxhighlight>
 
Now, hashes may not just have numerical indexes, but also symbolic indexes as lookup keys:
<syntaxhighlight lang="php">
var my_hash = {first:'A',second:'B',third:'C'};
</syntaxhighlight>
 
This will create a hash (imagine it like a storage container for a bunch of related variables) and initialize it with three values (A,B and C) which are assigned to three different lookup keys: first, second, third.
 
In other words, you can access each element in the hash by using its lookup key:
 
<syntaxhighlight lang="php">
var my_hash = {first:'A',second:'B',third:'C'};
print ( my_hash.first ); # will print A
print ( my_hash.second ); # will print B
print ( my_hash.third ); # will print C
</syntaxhighlight>
 
 
Nasal supports a "nil" value for use as a null pointer equivalent:
 
<syntaxhighlight lang="php">
var foo=nil;
</syntaxhighlight>
 
Also, note that Nasal symbols are case-sensitive, these are all different variables:
 
<syntaxhighlight lang="php">
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);
</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="php">
var hello = func {
  print("hello\n");
}
</syntaxhighlight>
 
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 [http://www.mail-archive.com/flightgear-devel@lists.sourceforge.net/msg13557.html Nasal & "var"].
 
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:
 
<syntaxhighlight lang="php">
# hello.nas
var greeting="Hello World"; # define a greeting symbol inside the hello namespace
</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="php">
# greetme.nas
print(hello.greeting); # the hello prefix is referring to the hello namespace (or module).
</syntaxhighlight>
 
==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 <tt>-set.xml</tt> file by putting it into the <tt><nasal>...</nasal><tt> section
 
<syntaxhighlight lang="xml">
  <nasal>
    ...
    <moduleA>
      <file>path/to/file1.nas</file>
      <file>path/to/file2.nas</file>
    </moduleA>
    <moduleB>
      <file>path/to/file3.nas</file>
    </moduleB>
  </nasal>
</syntaxhighlight>
 
In this case, variables in files <tt>path/to/file1.nas</tt> and <tt>path/to/file2.nas</tt> can be used in the Nasal console as
 
  moduleA.varName;
 
Variables in <tt>path/to/file3.nas</tt> 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.
 
 
'''''More information can be found at [[Namespaces and Methods]].'''''
 
== 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:
 
<syntaxhighlight lang="php">
  (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
</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="php">
  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"]
</syntaxhighlight>
 
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.
 
== 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
 
<syntaxhighlight lang="php">
var abs = func(n) { if(n<0) { -n } else { n } }
</syntaxhighlight>
 
But for those who don't like typing, the ternary operator works like you expect:
 
<syntaxhighlight lang="php">
var abs = func(n) { n < 0 ? -n : n }
</syntaxhighlight>
 
In addition, Nasal supports braceless blocks, like they're known from C/C++ and other languages. This means basically that the first statement (expression) after a conditional is evaluated if the condition is true, otherwise it will be ignored:
 
<syntaxhighlight lang="php">
var foo=1;
if (foo)
  print("1\n");
else
  print("0\n");
print("this is printed regardless\n")
</syntaxhighlight>
 
 
Instead of a switch statement one can use
 
<syntaxhighlight lang="php">
  if (1==2) {
    print("wrong");
  } else if (1==3) { # NOTE the space between else and if
    print("wronger");
  } else {
    print("don't know");
  }
</syntaxhighlight>
 
Instead of "else if", you can also use the shorter equivalent form "elsif".
 
which produces the expected output of <code>don't know</code>
 
In addition to "else if", Nasal also supports a short-hand version of it, called "elsif", which is semantically identical:
 
<syntaxhighlight lang="php">
  if (1==2) {
    print("wrong");
  } elsif (1==3) {
    print("wronger");
  } else {
    print("don't know");
  }
</syntaxhighlight>
 
 
The <tt>nil</tt> logic is actually quite logical, let's just restate the obvious:
 
<syntaxhighlight lang="php">
  if (nil) {
    print("This should never be printed");
  } else {
    print("This will be printed, because nil is always false");
  };
</syntaxhighlight>
 
 
 
Nasal's binary boolean operators are "and" and "or", unlike C. unary not is still "!" however.
They short-circuit like you expect
 
<syntaxhighlight lang="php">
var toggle = 0;
var a = nil;
if(a and a.field == 42) {
    toggle = !toggle; # doesn't crash when a is nil
}
</syntaxhighlight>
 
Note that you should always surround multiple conditions within outer parentheses, e.g.:
 
<syntaxhighlight lang="php">
if (1) do_something();
if (1 and 1) do_something();
if ( (1) and (1) ) do_something();
if ( (1) or (0) ) do_something();
</syntaxhighlight>
 
Nasal's binary boolean operators can also be used to default expressions to certain values:
 
<syntaxhighlight lang="php">
var altitude = getprop("/position/altitude-ft") or 0.00;
</syntaxhighlight>
 
Basically this will first execute the getprop() call and if it doesn't return "true" (i.e. non zero/nil), it will instead use 0.00 as the value for the altitude variable.
 
Regarding boolean operators like and/or: This is working because they "short circuit", i.e. in an OR comparison, the remaining checks are NEVER done IF any single of the previous checks is true (1), because that'll suffice to satisfy the OR expression (i.e. knowing that a single check evaluates to true).
 
Similarly, an "and" expression will inevitably need to do ALL "and" checks in order to evaluate the whole expression.
 
At first, this may seem pretty complex and counter-intuitive - but it's important to keep this technique in mind, especially for variables that are later on used in calcuations:
 
<syntaxhighlight lang="php">
var x=getprop("/velocities/airspeed-kts") or 0.00; # to ensure that x is always valid number
var foo= 10*3.1*x; # ... for this computation
</syntaxhighlight>
 
So this is to ensure that invalid property tree state does not mess up the calculations done in Nasal by defaulting x to 0.00, i.e. a valid numeric value.
 
Bottom line being, using "or" to default a variable to a given value is a short and succinct way to avoid otherwise elaborate checks, e.g. compare:
 
<syntaxhighlight lang="php">
var altitude_ft = getprop("/position/altitude-ft");
if (altitude_ft == nil) {
  altitude_ft = 0.0;
}
</syntaxhighlight>
 
versus:
 
<syntaxhighlight lang="php">
var altitude_ft = getprop("/position/altitude-ft") or 0.00;
</syntaxhighlight>
 
 
 
Basically: whenever you read important state from the property tree that you'll use in calculations, it's a good practice to default the value to some sane value.
 
But this technique isn't really specific to getprop (or any other library call).
 
Nasal is a language that has no statements, it's all about EXPRESSIONS. So you can put things in pretty much arbitrary places.
 
<syntaxhighlight lang="php">
var do_something = func return 0;
if (a==1) {
  do_something() or print("failed");
}
 
var do_something = func return 0;
( (a==1) and do_something() ) or print("failed");
</syntaxhighlight>
 
In a boolean comparison, 1 always means "true" while 0 always means "false". For instance, ANY comparison with if x ==1 can be abbreviated to if (x), because the ==1 check is implictly done:
 
<syntaxhighlight lang="php">
var do_something = func return 0;
( a and do_something() ) or print("failed");
</syntaxhighlight>
 
== Using Hashs to map keys to functions ==
 
You can easily reduce the complexity of huge conditional (IF) statements, such as this one:
 
<syntaxhighlight lang="php">
    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();
</syntaxhighlight>
 
.. just by using the variable as a key (index) into a hash, so that you can directly call the corresponding function:
 
<syntaxhighlight lang="php">
    var mapping = {1:function_a, 2:function_b, 3:function_c, 4:function_d,5:function_e};
    mapping[a] ();
</syntaxhighlight>
 
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:
 
<syntaxhighlight lang="php">
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");} );
</syntaxhighlight>
</syntaxhighlight>


== Initializing data structures ==
[[File:Vim-nasal-syntax-highlighting.png]]
 
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 <tt>while</tt>, <tt>for</tt>, <tt>foreach</tt>, and <tt>forindex</tt> 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 <tt>settimer</tt> function expects a ''function object'' (<tt>loop</tt>), not a function call (<tt>loop()</tt>) (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);
 
[[Nasal_scripting_language#settimer.28.29|More information about the settimer function is below]]
 
==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 [http://www.plausible.org/nasal/lib.html 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 <tt>[[$FG_ROOT]]/Nasal</tt> directory of a FlightGear installation). geo.nas also includes documentation/explanation of the functions available.
 
== Related content ==
{{Forum|30|Nasal}}
* [[:Category:Nasal]]
 
=== External links ===
* http://www.plausible.org/nasal


{{Appendix}}
{{Nasal Efforts}}


[[Category:Nasal]]
-->[[Category:Nasal]]

Latest revision as of 19:17, 28 August 2016

Nasal is FlightGear's built-in scripting language. Originally written and developed by Andy Ross for a personal project, it was integrated into FlightGear in November 2003, and has been continuously developed, improved, and refined since then. Over time, it has become probably FlightGear's most powerful, and has been used to create a huge variety of systems, ranging from wildfires to Control Display Units.

Within FlightGear, Nasal supports the reading and writing of internal properties, accessing internal data via extension functions, creating GUI dialogs and much, much more. Please see the right navigation bar to get additional information.

Highlight parse.png