[STICKY] Quick-Reference for JavaScripting in UOX3

Need help with your JScripts? Got questions concerning the DFNs? Come forward, step inside :)
Post Reply
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Quick-Reference for JavaScripting in UOX3

Post by Xuri »

This post is merely meant as a quick-reference for UOX3-related JavaScripting. I've posted a few basic ways to achieve specific things through UOX3's JavaScript-engine, and will try to update this file with more tidbits and tricks as time goes.

First, a few links that might be interesting to potential/current JavaScripters:
A re-introduction to JavaScript
UOX3's JavaScripting Documentation

Declaring a variable:
var myVar = 3;
or
var myVar = "This is a string";
Declaring a global variable:
NOTE: Declaring a variable outside functions in a script will make it a global variable for the entire script, and for all instances of that script
To declare a global variable from within a function, simply use:
newVar = 5;
newVar = "This is a string";
Declaring a case insensitive string-variable:
var myVar = /follow/i;
Perform a search in a string:
if( mySpeech.match( follow ) ) 
Check which type of variable:
pSock.SysMessage( "The variable myVar is a "+typeof( myVar )+" variable." );
Convert the variable myVar from one type to another:
myString = myInt.toString(); //convert to string
myHex = myInt.toString( 16 ); //convert to hex-decimal
myInt = parseInt( myString ); //convert to int
Convert variables between uppercase/lowercase:
myVar = toUpperCase( myVar );
myVar = toLowerCase( myVar );
Checking the length of a string:
pSock.SysMessage( "The string is "+myVar.length+" characters long." );
Do something until condition is met:
do {expr} while (!cond)
Optional method of multiple If/then:
switch( value/variable )
{
    case value1:
        blah;
        break;
    case value2:
        bleh;
        break;
    default:
        bluh;
        break;
}
Extract part of a string only:
var myVar = "This is a string variable.";
pUser.SysMessage( myVar.slice(5,17) );
//Produces "is a string" as the system message
Round numbers off:
// Round to whole number:
var pi = "3.1415926535";
pi = Math.round(pi);

// Round to tenths:
var pi = "3.1415926535";
pi = Math.round(pi*10)/10;

// Round to hundredths
var pi = "3.1415926535";
pi = Math.round(pi*100)/100;
Check if a value is NOT a number:
if( isNaNo( myVar ) )
    pUser.SysMessage( "myVar does NOT contain a number value! Woho!" );

or

if( myVar.NaN )
    pUser.SysMessage( "myVar is NOT a number! Whee!" );
Convert all of the elements of an Array to one joined String:
var myArray = new Array();
myArray[0] = "This";
myArray[1] = "is";
myArray[2] = "a";
myArray[3] = "long";
myArray[4] = "string";
myArray[5] = "in";
myArray[6] = "many";
myArray[7] = "parts.";
myVar = myArray.join( " ");
pUser.SysMessage( myVar );
Split the elements of a string into an array:
var myString = "Kal Vas Flam";
var SpellWrd_Array = myString.split(" "); //the contents of " " determines where to split the string. In this example a space was used.)
Catching errors in your scripts
try
{
    //Put the script code you want to test for errors here
    bogusObject.x++;
}
catch( exception )
{
    //Handle the error, display error message, etc
    socket.SysMessage( exception );
}
finally
{
    //Any code here will run whether or not an exception is thrown
}
Check for existence of property, and whether said property has a value set:
if( pUser.hasOwnProperty( "target" ))
    pUser.TextMessage( "Target property found AND has a value!" );
else
    pUser.TextMessage( "Target property either NOT found, or has no value!" );
Check for existence of property, but ignore value
if( "target" in pUser )
    pUser.TextMessage( "Target property found!" );
else
    pUser.TextMessage( "Target property NOT found!" );
Last edited by Xuri on Thu Feb 16, 2006 8:22 am, edited 1 time in total.
-= Ho Eyo He Hum =-
giwo
Developer
Posts: 1780
Joined: Fri Jun 18, 2004 4:17 pm
Location: California
Has thanked: 0
Been thanked: 0

Post by giwo »

Just so you know, Xuri.

In testing with spidermonkey, and my research on JavaScript built-in functions.

To convert a number to a string, you use this:

myVar = 0;
myString = myVar.toString();

Notably to get a hexadecimal number, you can do myVar.toString( 16 );

As for converting a string to a number, using parseInt( myString ) will convert it back to an integer.
Scott
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Alrighty, updated my post =)
-= Ho Eyo He Hum =-
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Time to add something to this thread!

Pausing a wandering NPC in his tracks for X seconds
myNPC.SetTimer( 11, 10000 ); //10000 = 10 seconds

=)
-= Ho Eyo He Hum =-
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Some more helpful tidbits:

To reset the decaytimer on an item manually
myItem.decaytime = 0;

To remove an item from a container:
myItem.container = null;
(need to teleport item to desired location after)

To move an item from the ground and into a container:
myItem.container = containerObj;

To move an item into a character's backpack:
myItem.container = myChar.pack;

To equip an item on a character (check for conflicting item in layer first):
myItem.container = myChar;
myItem.layer = <layerID>;
)

To temporarily store an object in a player-character's socket (say, from one function to another, where it's not possible to include the object in the function-call):
mySocket.tempObj = myObject;
or
myChar.socket.tempObj = myObject;

Other temporary storage variables available on sockets:
mySocket.tempInt - Temporary variable to store larger numbers (supports negatives).
mySocket.xText - Temporary variable to store strings of text.
mySocket.clickX - Temporary variable to store small numbers (supports negatives).
mySocket.clickY - Temporary variable to store small numbers (supports negatives).
mySocket.clickZ - Temporary variables to store very small numbers (-128 to 128).
-= Ho Eyo He Hum =-
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Finding characters or items near a character:
function onUseChecked( pUser, iUsed )
{
    // Finding items within a radius of 10 tiles from pUser
    // Replace with AreaCharacterFunction to find characters.
    // Socket can be a player socket or NULL (if script runs for item/npc)
    // var numberOfCharsFound = AreaCharacterFunction( "findNearbyChars", pUser, 10, pUser.socket );
    var numberOfItemsFound = AreaItemFunction( "findNearbyItems", pUser, 10, pUser.socket );
    pUser.TextMessage( "I found "+numberOfItemsFound+" items nearby!" );
    return false;
}

// function findNearbyChars( pUser, trgChar, pSock )
function findNearbyItems( pUser, trgItem, pSock )
{
    if( trgItem && trgItem.isItem )
        return true;
    else
        return false;
}
-= Ho Eyo He Hum =-
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Fetching sub-values of MORE item property:
var iMore = iUsed.more;
var iMorePart1 = ( iMore>> 24 );
var iMorePart2 = ( iMore>> 16 );
var iMorePart3 = ( iMore>> 8 );
var iMorePart4 = ( iMore% 256 );
Same applies to MOREX, MOREZ and MOREY. For instance, to fetch the 'trapped' status of a container:
var iMoreZ = iUsed.morez;
var iMoreZPart1 = ( iMoreZ>> 24 );
var iMoreZPart2 = ( iMoreZ>> 16 );
var iMoreZPart3 = ( iMoreZ>> 8 );
var iMoreZPart4 = ( iMoreZ% 256 );
In this case the container is trapped if iMoreZPart1 equals 1, while iMoreZPart2 contains the damage dealt by the trap if sprung!
-= Ho Eyo He Hum =-
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Getting coordinates of target location
Coordinates of the last targeted location can be gotten via Socket properties, for instance in the onCallback#() functions. One thing to note is that there is some difference in how this behaves for older clients (which don't by default include the height of targeted tiles for the Z value) vs newer clients (which do). This means, for older client versions, the height of the tile must be added on manually via the GetTileHeight() function.

Also note that this extra step is only needed when targeting items (static or dynamic), and is not needed when a map-tile has been targeted.
var x = socket.GetWord( 11 );
var y = socket.GetWord( 13 );
var z = socket.GetSByte( 16 );

// If connected with a client lower than v7.0.9, manually add height of targeted tile
if( socket.clientMajorVer <= 7 && socket.clientSubVer < 9 )
    z += GetTileHeight( socket.GetWord( 17 ));
-= Ho Eyo He Hum =-
User avatar
Xuri
Site Admin
Posts: 3704
Joined: Mon Jun 02, 2003 9:11 am
Location: Norway
Has thanked: 48 times
Been thanked: 8 times
Contact:

Post by Xuri »

Creating the illusion of a progress bar in a gump
Method A - Tiled Gumps
// Display a 50% filled progress bar using two tiled gumps with different colors
myGump.AddTiledGump( 100, 20, 200, 12, 5055 );
myGump.AddTiledGump( 100, 20, 100, 12, 9271 );
Method B - HTML Background Color
// Display a 50% filled progress bar using HTML background colors
myGump.AddHTMLGump( 100, 20, 100, 20, 0, 0, "<BODYBGCOLOR=black></BODYBGCOLOR>" );
myGump.AddHTMLGump( 100, 20, 50, 20, 0, 0, "<BODYBGCOLOR=green></BODYBGCOLOR>" );
-= Ho Eyo He Hum =-
Post Reply