Difference between revisions of "Oolite Javascript basics"

From Elite Wiki
(Created page with "Just playing around with the wiki. I may continue this, or I may return to my day job which currently consists of making smaller rocks from larger rocks & hoping that there's...")
(No difference)

Revision as of 23:32, 1 October 2022

Just playing around with the wiki. I may continue this, or I may return to my day job which currently consists of making smaller rocks from larger rocks & hoping that there's gold in them thar 'roids...


Oolite Javascript basics

So you want to write scripts for Oolite that'll do all sorts of neat stuff, but you don't know where to start. Well, I was once like you when I started to learn Oolite Javascript and look at where I am today: a broken-down, hollow husk of a man... but that's a whole 'nother story.

The very first thing you need to know and always remember is this:

Javascript is object-oriented and (largely) event-driven

In many non-object-oriented programming languages, you use commands to do things- commands like "print". You might write something like: print "Hello World!". When you run your program, you'll be rewarded with a friendly greeting on-screen.

Things are done a little differently in Oolite Javascript because... reasons. Commands are called methods in object-oriented lingo. One of the commands (methods) to print something in Oolite is the consoleMessage method. Your print "Hello World!" will look like this:

consoleMessage ("Hello World!")

That, however, is not complete and will not work. For non-object-oriented humans, amphibians and occasional rhinoceri reading this- always remember and never forget the following: methods ALWAYS ALWAYS ALWAYS need to be attached to an object. Without it, it's like driving your car... but without your car. consoleMessage is a method of the object, player. So our example should now look like this:

player.consoleMessage ("Hello World!")

Knowing this is still not quite enough for your first script. This brings us to the next important point: Javascript is event-driven. Not only does Oolite need to know what to do (methods) and who or what wants to do it (objects), it needs to know when to do it. To this end, almost everything you write needs to be in an event handler (for further enlightenment/confusion, see here and here). Putting your commands in an event handler answers the when. Let's use the startUp event. This is the event (one of them, at least) when you start a new game or load a save file. Here's the format: this.startUp = function () {}

So the TL;DR version:

Don't do this:

consoleMessage ("Hello World!")

Don't even do this:

player.consoleMessage ("Hello World!")

Do this:

this.startUp = function () {
player.consoleMessage ("Hello World!")
}

There- you've written your very first Oolite Javascript script! Congrats & break out the bubbly- we're gonna party like it's 2084004!