Skip to content

JavaScript

ThePix edited this page Feb 25, 2020 · 27 revisions

JavaScript has some important differences if you are used to ASL, the coding language for Quest 5.

ASL is a somewhat cut down language, and as it runs on top of the Quest player, you do not have access to everything, so is a little limited. One of the biggest limitations is that you cannot pass parameters to a script or return a value (well, you can, using delegates, but the editor does not support it, so it is a bad idea).

JavaScript is a fully-fledge programming language, and as everything is written in JavaScript, you have access to everything. When you convert from ASL to JavaScript, you will tend to encounter the downside of JavaScript, because your existing code will not be designed to make use of the features only in JavaScript.

The basic structure of an ASL script will be the same in JavaScript; the order of each line, the arrangement of blocks and loops. Also, if and else are used the same.

As with ASL, comments are denoted by two slashes. //. You can have block quotes too with /* and */.

The world, w

In ASL the global world of the code contains all the objects in the game. If there is an object called "table", you can just refer to it as table.

In JavaScript the global world includes every built in function, elements of the web page, etc. It is therefore necessary to have a sealed off section that is the game world. This is called "w". To access an object called "table", you have to go via w, so must use w.table or `w["table"] to get it.

Numbers

ASL has two types of numbers, int, short for integer, i.e., a whole number, and double, short for double-precision floating-point number, which is a number with a decimal part (and rarely if ever used in Quest). JavaScript is rather unusual in just having one type, number, which is equivalent to a double, but can be used as an int with no prblem in most cases.

The issue to be aware of is division, as the result of dividing an int by an int is another int in Quest 5, so 3 divided by 2 is 1. In JavaScript it is 1.5. Arguably the ASL result is the surprise, but just be aware it is different.

To convert back to a whole number used one of these:

Math.round(5.5)    // round to the nearest whole number, or the greater number if 0.5
Math.round(-5.5)   // so these would be 6 and -5

Math.floor(5.5)    // round to lower whole number
Math.floor(-5.5)   // so these would be 5 and -6

Math.ceiling(5.5)    // round to greater whole number
Math.ceiling(-5.5)   // so these would be 6 and -5

Declare variables

In JavaScript you have to declare a variable before you use. If it is going to change, use let, if it is not going to change, useconst.

const height = obj.getHeight()  // height cannot change
let n                           // n can change
n = height + 4                  // so now n changes
const list = []                 // list cannot change...
list.push(n)                    // but its contents can

If you are unsure if a variable will change, use let. There is also an older keyword, var, which is much like let.

[In fact, you do not need to declare them if your file is not in "strict" mode, but you will have less bugs if you use "strict" mode, so declare your variables.]

End a line with a semi-colon... or not

I started putting a semi-colon at the end of each line, but they are optional, so lately I have not bothered.

If you have two statements on the same line, then you do need a semi-colon to separate them, but really this is to be avoided anyway.

You will find a lot of web pages by people insisting semi-colons should be used. There are some really weird uses of JavaScript that people cite (eg here, but the solution is removing a line break; adding a semi-colon does not solve the issue. The only time there seems to be an issue is with lines that start with ( or [, so be aware of that, and recognise that you are very unlikely to do that.

Testing equality and inequality

I you want to compare two variables to see if they are equal, in ASL you use an equals sign. For not equal, use less than then greater than:

if (height = 12) {

if (height <> 12) {

Most modern programming languages use two equals signs to differentiate from when you are assigning a value, and an exclamation mark and equals sign for "not equals". JavaScript is the same, but will first try to "coerce" the types, which can give some unexpected behaviour. It is safer to use three equals signed:

if (height === 12) {

if (height !== 12) {

For Boolean operations:

and     &&
or      ||
not     !

Strings

As in ASL, a string can be denoted by double quotes, but you can also use singles - as long as they are the same at both ends. This allows you to include quotes in your string.

s = "Strings with double quotes are cool, aren't they?"
s = '"No!" she said emphatically.'

Get and Has functions

ASL has a bunch of functions for checking if an object has a certain attribute or to get its value.

if (HasString(table, "alias")) {
  msg(GetString(table, "alias"))
}

In JavaScript you can just access it directly. If you are not worried about what type the attribute is, you just want to know if it exists:

if (w.table.alias)) {
  msg(w.table.alias))
}

If you need to ensure the type of the attribute, use typeof:

if (typeof w.table.alias === 'string')) {
  msg(w.table.alias))
}

In ASL you would probably not use GetString as you can use the . operator there too (the function exists for the visual editor), however it is common to use GetBoolean as that handles the case where the attribute does not exist.

if (GetBoolean(table, "smashed")) {
  msg(GetString(table, "alias"))
}

Not a problem in JavaScript, as a missing attribute is the same as one set to false inside an if statement.

if (w.table.smashed)) {
  msg(w.table.alias))
}

Functions

A lot of functions can be quickly swapped for the JavaScript version, which does the same thing.

As JavaScript is object-orientated, several functions are part of the object, rather than floating free. The means the name of the function goes after the object it is associated with, separated by a dot, so for example Split(mystring, "!") becomes mystring.split("!"). This is noted in the tables below as "append to string".

String Functions

ASL Quest 6 Comment
CapFirst sentenceCase
Conjugate conjugate
DisplayMoney displayMoney
DisplayNumber displayNumber
EndsWith endsWith append to string
FormatList formatList different parameters
Instr indexOf append to string
InstrRev lastIndexOf append to string
IsNumeric isNaN returns true if NOT a number
IsRegexMatch match append to string
Join join append to string
LCase toLowerCase append to string
LengthOf length append to string
Mid substr append to string
PadString padString append to string
ProcessText processText
Replace replace append to string
Split split append to string
StartsWith startsWith append to string
ToRoman toRoman
ToWords toWords
Trim trim append to string
UCase toUpperCase append to string
WriteVerb nounVerb

Random Functions

ASL Quest 6 Comment
DiceRoll diceRoll
GetRandomDouble
GetRandomInt randomInt
PickOneChild
PickOneChildOfType
PickOneExit
PickOneObject randomFromArray
PickOneString randomFromArray
PickOneUnlockedExit
RandomChance randomChance

Maths functions

All the mathematical functions are the same, but require "Math." prepended and start with a lower case character, so "Log" becomes "Math.log".

Dictionaries and lists

Dictionaries and lists are built in to JavaScript, making them easier to use, but somewhat different to ASL. Here is the ASL to create a list and a dictionary, in each case adding three items, then printing the first.

myList = NewStringList()
list add(mylist, "one")
list add(mylist, "two")
list add(mylist, "three")
msg(StringListItem(mylist, 0)

myDictionary = NewStringDictionary()
dictionary add(myDictionary, "first", "one")
dictionary add(myDictionary, "second", "two")
dictionary add(myDictionary, "third", "three")
msg(StringDictionaryItem(myDictionary, "first")

In JavaScript:

const myList = []
mylist.push("one")
mylist.push("two")
mylist.push("three")
msg(mylist[0])

const myDictionary = {}
myDictionary["first"] = "one"
myDictionary["second"] = "two"
myDictionary["third"] = "three"
msg(myDictionary["first"])

Or even quicker:

const myList = ["one", "two", "three"]
msg(mylist[0])

const myDictionary = {
  first:"one",
  second:"two",
  third:"three",
}
msg(myDictionary.first)

JavaScript dictionaries are very useful, and pervade Quest 6 extensively, so it is important to understand them.

Loops

JavaScript while loops are just like ASL.

The for looks are a little different. Here is the ASL version; i is the variable inside the loop. It will start with a value of 3, go up to a value of 7, in steps of 2 (the last parameter defaults to 1 if missing).

for (i, 3, 7, 2) {
  msg(i)
}

In JavaScript it looks like this, which is more complicated, but more flexible:

for (let i = 3; i <= 7; i += 2) {
  msg(i)
}

The for statement has three parts:

let i = 3   // Initialisation: declare a variable i and set to 3
i <= 7      // Condition: continue while i is 7 or less
i += 2      // Step: after each iteration add 2

ASL has foreach for iterating over a list or dictionary.

foreach (s, myList) {
  msg(s)
}
foreach (key, myDictionary) {
  msg(StringDictionaryItem(myDictionary, key))
}

JavaScript use for, but in a different format. Note that you have to use of for a list and in for a dictionary.

for (let s of myList) {
  msg(s)
}
for (let key in myDictionary) {
  msg(myDictionary[key])
}

Assignment operators

This is a cool feature in JavaScript that ASL does not have. If you are converting code, you can ignore it, but it is great when writing new code.

There are often times when you do arithmetic on two values and assign the result to one of them. Let us say the player buys an object, and you need to determine how much money the player now has. In ASL (and JavaScript):

player.money = player.money - item.price

In JavaScript you can also do this:

player.money -= item.price

You can also do +=, /= and *=.

Increment and decrement

Another short cut, when adding or subtracting 1. Is ASL (or JavaScript):

player.counter = player.counter - 1

In JavaScript:

player.counter--

You can use ++ to increment.

The switch statement

In ASL:

switch (s) {
  case ("cat") {
    msg("It's a cat!")
  }
  case ("dog") {
    msg("It's a dog!")
  }
  default {
    msg("No idea")
  }

In JavaScript, less curly braces, but more colons and the word break after each script:

switch (s) {
  case ("cat"):
    msg("It's a cat!")
    break
  case ("dog"):
    msg("It's a dog!")
    break
  default:
    msg("No idea")
}

Calling scripts

ASL has some special commands to run scripts, do for a script attached to an object, and invoke for any.

  do(myObject, "specialscript")

In JavaScript that is not necessary, you just call the function.

  myObject.specialscript()

This makes it very easy to pass parameters to a script. In ASL you need to put them into a dictionary first. It also means you can get a return value from a script, something that requires delegates in ASL.

  const result = myObject.specialscript(4, player)

Note that JavaScript is very relaxed about the parameters passed to a script. Ifyou send more than the script is expecting, it will just discard the excess ones. If you send too few it will pad them out with the special undefined value.

Other Quest 5 script commands

The picture and msg functions are the same in JavaScript, though they can be used with additional parameters in Quest 6, as discussed elsewhere.

Use clearScreen instead of the ClearScreen function. Instead of error("message") do `throw new Error("message").

Instead of set, you can just set attributes directly.

set(myObject, "size" 7)
att = "count"
set(myObject, att, 14)

In Quest 6

w.myObject.size = 7
const att = "count"
w.myObject[att] = 14
const objName = 'table'
w[objName][att] = 14

The wait statement in ASL is a bit different, as is showMenuas they require callback functions...

The firsttime function also requires a unique id, as there is no (obvious) way to otherwise tell one call from another. You are probably best avoiding this altogether.

Because of the way Quest 6 saves a game, creating and destroying things during game play is problematic. Therefore these commands have no simple alternative: create, create exit, create timer, create turnscript, destroy.

These commands still need to be implemented: finish, firsttime, get input, play sound, stop sound.

There is no equivalent to on ready (should only be used by the built-in libraries), request (already deprecated in Quest 5), 'rundelegate' (not required) and start transaction (not required).

Tutorial

QuestJS Basics

The Text Processor

Commands

Templates for Items

See also:

Handing NPCs

The User Experience (UI)

The main screen

The Side Panes

Multi-media (sounds, images, maps, etc.)

Dialogue boxes

Other Elements

Role-playing Games

Web Basics

How-to

Time

Items

Locations

Exits

Meta

Meta: About The Whole Game

Releasing Your Game

Reference

Clone this wiki locally