Howto:Start using vectors and hashes in Nasal: Difference between revisions

Jump to navigation Jump to search
m
mNo edit summary
Line 402: Line 402:
</syntaxhighlight>
</syntaxhighlight>


On the other hand, we were just about to make construction of such hashes much simpler. So we are going to change the function and make it return a new hash that is properly set up:
On the other hand, we were just about to make construction of such hashes much simpler. This can be done by creating a new function that constructs hashes dynamically using a hash:


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
var waypoint = {
 
number:1,
var make_waypoint = func {
altitude:2,
  return { parents:[waypoint] };
distance:3,
angle:4,
length:5,
ID:6,
bearing:7,
hello: func {
return {parents:[waypoint]}
}
}
};


</syntaxhighlight>
</syntaxhighlight>


Note how the hello function has now been modified to return a new hash to its caller. So we could just change its name to something more telling like "new":
Next, we are going to change the function and and embed it into the hash, so that the constructor function becomes a part of the class, renaming it to "new":


<syntaxhighlight lang="php">
<syntaxhighlight lang="php">
Line 443: Line 435:
var wp = waypoint.new();
var wp = waypoint.new();
</syntaxhighlight>
</syntaxhighlight>
Sometimes, you'll work with classes that do not have any custom constructor functions - but you can easily create a generic constructor, too:
<syntaxhighlight lang="php">
var new = func {
var t=[];
foreach(var a; args) append(t,a);
return {parents:t};
}
var Position3D = {x:0.0, y:0.0, z:0.0};
var p = new( Position3D );
</syntaxhighlight>
You could even implement an overloaded function that creates arrays of objects.


Now, let's imagine you want to add another member function to print a certain field's value, such as "number". This can be accomplished using the "me" keyword which ensures that the member function is always referring to the active object:
Now, let's imagine you want to add another member function to print a certain field's value, such as "number". This can be accomplished using the "me" keyword which ensures that the member function is always referring to the active object:

Navigation menu