Skip to content

Using libraries

Wolfyxon edited this page Jul 9, 2024 · 4 revisions

Basics

Libraries are scripts that contain useful functions that can be called in other scripts when that library is imported.

Importing

Libraries are located in the scripts/lib directory.

First import the library script before your script

<script src="../../scripts/lib/libraryName.js" type="text/javascript"></script>

Then add

depend("libraryName");
const myCoolLib = {};

On the top of your script to ensure the library is loaded (and throw an error otherwise).

Example

<script src="../../scripts/lib/gameBase.js" type="text/javascript"></script>
<script src="myCoolGame.js" type="text/javascript"></script>
depend("gameBase");

const deg = 90;
const rad = deg2rad(deg); // deg2rad() is a gameBase function that converts degrees to radians

console.log(deg + " degrees is " + rad + " radians");

Creating your own libraries

To create your own library, create a script in the scripts/lib directory. Put this code on top containing the library's name:

libName("myCoolLibrary");
const myCoolLib = {}

The constant is the place to store the functions and variables of your library.
If your library requires other libraries, use depend() (it won't import them, but will show an error telling the user that those dependencies are not loaded)

libName("myCoolLibrary");
depend("gameBase");
depend("net");

const myCoolLib = {}

Then you can put functions and variables in your library and they will be accessible from scripts using it.

libName("myCoolLibrary");
const myCoolLib = {}

/**
* Adds two numbers
* @param {number} a First number
* @param {number} b Second number
*/
myCoolLib.sum = function(a, b) {
    return a + b;
}
Clone this wiki locally