Script functions documentation

Discussion in 'Server and Client Scripting' started by Mystra, Sep 7, 2010.

Thread Status:
Not open for further replies.
  1. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    [size=+2]This thread is mostly obsolete. Read http://wiki.pokemon-online.eu/view/Scripting for updated info.[/size]

    ———————————————

    Thread will be closed. Comments should go into: http://pokemon-online.eu/forums/sho...s-on-quot-Script-functions-documentation-quot

    Notes:

    • [size=+1]⚠[/size] Assume everything is case sensitive. Parameters should be able to handle value case insensitively but don't use JumpingLetters just because you can.
    • Features that are planned but not yet exist in relesed version of PO will be marked red.

    Client Scripts
     
    Last edited by a moderator: Jul 14, 2012
    Alipio likes this.
  2. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    [size=+1]1.Events[/size]​

    Scripts are triggered when a certain action occurs. The function corresponding to the event is then evaluated by the script engine.

    Note: stoppable events can only be stopped in the 'before' phase (unless there is no before/after separation like with serverStartUp for example). sys.stopEvent() is used to stop an event.

    Here is the list of the events:

    1.1. Server

    • serverStartUp(): when the server starts. Unstoppable event.
    • serverShutDown(): when the server shuts down. Unstoppable event.
    • step(): triggers every second. Unstoppable event.

    1.2. Battle setup

    • battleSetup(source, target, battleId): between 'beforeBattleStarted' and 'afterBattleStarted'. Used to setup battle effects. See prepareWeather() function. Unstoppable event.

    1.3. Other

    • attemptToSpectateBattle(src, player_id_1, player_id_2): if function implementing it will return "allow" (case insensitive) player will be allowed to watch even if spectators are disabled and auth is not high enough. Otherwise has no effect and normal rules apply.

    [size=+1]⚠[/size] All of the following events are to be preceded with before or after. For example, beforeChatMessage(source, message).

    1.3. Log on/off
    • LogIn(source): When a player logs in. Stoppable event.
    • LogOut(source): When a player logs out. Unstoppable event.

    1.4. Chat
    • ChannelJoin(playerId, channelId): When a player logs on, this event will be called, even if this is on the main channel. Stoppable event.
    • ChannelLeave(playerId, channelId): when a player logs off, this event will be called on all channels the player is on. Unstoppable event.
    • ChannelCreated(channelId, channelName, playerId): the playerId is for when a player joins a channel that doesn't exist (hence creating it), you have the id of the player who is creating the channel. Stoppable event.
    • ChannelDestroyed(channelId): stoppable event.
    • ChatMessage(source, message, channelId): When the message of a player is displayed. There's a possibility that in the future, the client could talk directly to the server not being in a channel, and then the id would be -1. Stoppable event.
    • NewMessage(message): When a message is displayed in the server window, but is not a chat message. Stoppable event.

    1.5. Battle
    • BattleMatchup(source, target, clauses, rated, mode): When a battle using findBattle is decided. Stop the event if you don't want the matchup.
    • BattleStarted(source, target, clauses, rated, mode): When a battle starts clauses is an array of 0 and 1 depending on if the corresponding clauses are enabled. Unstoppable event.
    • BattleEnded(winner, loser, result, battle_id): When a battle ends. result is either "win", "forfeit", or "tie". Unstoppable event.
    • ChallengeIssued(source, target, clauses, rated, mode): When a player is challenged. clauses is an array of 0 and 1 depending on if the corresponding clause is enabled, mode is 0 for Singles and 1 for Doubles. rated is always false now that rated battles through direct challenges are disabled.
    • SpectateBattle(src, battler1, battler2)

    1.6. Player
    • ChangeTeam(src): When a player changes teams. Unstoppable event.
    • ChangeTier(src, oldtier, newtier): When a player changes tiers. Stoppable(?) event.
    • PlayerAway(source, away): When a player goes or comes back from away. away is set to true or false, depending on if the players goes away or not. Stoppable(?) event.
    • PlayerBan(source, dest): When a player is banned. Stoppable event.
    • PlayerKick(source, dest): When a player is kicked. Stoppable event.

    There is no need to specify all the variables if you don't need them. You can also give them different names, but must keep the same order. Read "Script reference" to see how to declare an event. To call an event from another, do this.eventName(variables).
     
    Last edited: May 1, 2011
  3. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    [SIZE=+1]2. Functions[/SIZE]​

    All functions listed here must be called with 'sys.' before. For example:
    Code (javascript):
    1.  
    2. sys.modifyTypeChart(sys.typeNum("bug"), sys.typeNum("psychic"), "normal");
    3.  


    will cause Bug attacks to do normal damage to Psychic type pokemon.

    2.1. Messages

    • clearChat(): clears the server mainchat.
    • changeAnnouncement(html): changes announcement in the config and updates it for all players.
    • getAnnouncement(): gets the announcement in the config.
    • print(variable1, variable2, ...): displays the content of the variables in the server's mainchat.
    • sendAll(message, channelId): sends a message to the mainchat. If optional channelId is not present, will send a message to all channels.
    • sendHtmlAll(message, channelId): sends a message to the mainchat. It will be displayed in html. If optional channelId is not present, will send a message to all channels. See section 4.1 for details.
    • sendHtmlMessage(playerId, message, channelId): sends a message only to the mainchat of that player. It will be displayed in html. If optional channelId is not present, will send a message to the user on all his channels. See section 4.1 for details.
    • sendMessage(playerId, message, channelId): sends a message only to the mainchat of that player. If optional channelId is not present, will send a message to the user on all his channels.
    • setAnnouncement(html, playerId): changes announcement. If optional playerId is not specified all players will see updated announcement.

    2.2. Players

    • avatar(playerId): returns player's avatar id.
    • auth(playerId): returns the authority level of that player.
    • away(playerId): is player away? Will return undefined if player is not logged in.
    • ban(playerName): bans someone in DB. Use kick() manually if needed.
    • battling(playerId): returns true or false depending on if the player is battling.
    • changeAvatar(playerId, avatarId): will set player's avatar to avatarId.
    • changeAuth(playerId, newAuth): changes the auth of the player to the new auth. Player must be online.
    • changeAway(playerId, away) : changes the "business" of that player.
    • changeDbAuth(player_name, newAuth): changes the auth of the player in the DB to the new auth. If a player is online effective auth will not change until s/he logs off or changeAuth() called.
    • changeInfo(player_id, new_info): temporary changes player's challenge window info to new_info (HTML).
    • changeName(player_id, new_name): temporary changes player's name to new_name. New player is not created. No uniqueness check is performed. Server window will not be updated. Use at your own risk.
    • changePokeGender(player, slot, gender): gender should be either 0 (neutral), 1 (male), or 2 (female).
    • changePokeHappiness(player_id, slot, new_value): new_value must be in [0..255] range.
    • changePokeItem(playerId, pokeSlot, itemnum): changes the item of the pokemon in that slot.
    • changePokeLevel(playerId, pokeSlot, pokeLevel): changes the level of the pokemon in that slot.
    • changePokeMove(playerId, pokeSlot, moveSlot, movenum): changes the move of that pokemon in that moveslot (move slots range from 0 to 3).
    • changePokeName(player_id, slot, name)
    • changePokeNum(playerId, pokeSlot, pokeNum): changes the pokemon in that slot (eg 150 = Mewtwo), slots range from 0 to 5.
    • changePokeShine(player_id, slot, new_value): new_value is either true or false.
    • changeRating(name, tier, newrating)
    • changeTier(player_id, tier)
    • clearPass(name): removes the password associated to that name.
    • hasLegalTeamForTier(playerId, tier): returns true or false depending on if the player has a team valid for this tier.
    • id(playerName): returns the id of the player with that name.
    • ip(playerId): returns the IP of that player
    • kick(playerId): kicks that player.
    • ladderEnabled(playerId): returns true or false depending on if that player has ladder enabled.
    • ladderRating(playerId, tier): returns the ladder rating of that player. If tier is not specified current one will be used.
    • loggedIn(playerId): returns true or false depending on if the player is logged in or not.
    • name(playerId): returns the name of the player with that id.
    • ranking(playerId): returns the ranking of that player in his tier.
    • ranking(name, tier): returns the ranking of that player for that tier.
    • ratedBattles(player_id): number of rated battles player did.
    • ratedBattles(name, tier): number of rated battles player did in a given tier.
    • resetLadder(tier): reset all players rankings in the selected tier and update them on the server.
    • synchronizeTierWithSQL(tier): clears all the cache and load values from the SQL database.
    • tier(playerId): returns the tier of that player.
    • unban(playerName): unbans a name.
    • updatePlayer(player_id): updated changed player data for all player in server (after changing pokemon with script for example, so the correct team is shown in the challenge window). This is not needed for changeInfo as is does that automatically.

    2.3. Configuration

    • getVal(key): returns the variable stored in the registry with that key.
    • getVal(file, key): returns the variable stored in the file with that key.
    • getValKeys(file): returns an array of keys stored (without values). "file" parameter is optional.
    • removeVal(key): deletes the variable in the registry.
    • removeVal(key, file): deletes the variable in the file.
    • saveVal(key, value): saves a variable in the registry so it'll still be there after a server restart.
    • saveVal(file, key, value): saves a variable to a file so it'll still be there after a server restart.
    • setPA (arrayName): sets an array as a session variable. It creates a global variable that is an array with that name. When a player logs off, arrayName[id] will be set to undefined. Might be useful to use as "session variables" for users.
    • unsetPA (arrayName): unsets session variable.

    2.4. Scripting

    • callLater(script, seconds): runs the script given in parameter seconds later.
    • callQuickly(script, milliseconds): works like callLater() but accepts milliseconds as parameter instead of seconds. Don't overdo it.
    • changeScript(newScript, triggerStartUp): changes the script with the content. Can be used with webCall or getFileContent to do cool stuff. If optional triggerStartUp is true serverStartUp event will be triggered after loading a new script.
    • delayedCall(function, seconds): works like callLater() but accepts a function without arguments as a first parameter instead of a string. See section 4.4 for details.
    • eval(script): runs the script given in parameter. Returns the result.
    • stopEvent(): if called before an event occurs, if possible, stop the events from happening. If called in an event that starts by "before", stops the event from happenning. For example, if called in beforeChatMessage, the message of the player won't display. If called in beforeLogIn, the player won't be allowed to log in. If called in beforeChallengeIssued, the challenge won't be issued.
    • system(command): tell the underlying OS to run the command line.

    2.5. Files

    • appendToFile(filename, content): append content to the content of the file.
    • deleteFile(filename)
    • getFileContent(filename): returns the content of the file.
    • writeToFile(filename, content): clear the content of the file and write that.

    2.6. Web

    • synchronousWebCall(url): calls the web url given, waits for the reply, and returns the reply.
    • synchronousWebCall(url, args): calls the web url given with the args as POST arguments, waits for the reply, and returns the reply.
    • webCall(url, callback): calls the web url given, and when the reply is received runs the callback given in parameter. Callback can be a script as string, then the variable "resp" will contain the response of the web server. It can also be 1-parameter JavaScript function to be called.
    • webCall(url, callback, args): calls the web url given with the args as POST arguments, and otherwise behaves the same way as the previous function.

    2.7. Information

    • ability(num): returns ability name by its id.
    • abilityNum(abilityName): returns ability id by its name.
    • aliases(ip): returns an array of users for that IP.
    • banList(): returns an array of banned user names.
    • dbAuth(name): returns the authority from the member in the database with that name.
    • dbAuths(): returns an array of names of people whose auth is superior to 0.
    • dbIp(name): returns the ip from the member in the database with that name.
    • dbLastOn(name): returns the last date of appearance of that person as shown in the Control Panel.
    • dbRegistered(name): returns if the name is registered with a password or not.
    • gen(pokenum): gives the pokemon's generation.
    • getClauses(tier): will return a packed value which hold default clauses for a given tier.
    • getColor(id): gets a user's hex code for color.
    • getTierList(): returns an array of tiers.
    • hiddenPowerType(hpdv, attdv, defdv, spddv, sattdv, sdefdv): returns type id for given DVs.
    • item(num): returns the name of the item.
    • itemNum(name): returns the number of the item.
    • maxAuth(ip): returns the maximum authority associated to that IP.
    • move(num): returns the name of the move.
    • moveNum(name): returns the num of the move.
    • nature(num): returns the corresponding nature.
    • natureNum(name): returns the number corresponding to that nature.
    • numPlayers(): returns the number of players online.
    • playerIds(): return an array containing the ids of all the players online. You can use this function in your sendall scripts, masskick, etc.
    • pokeAbility(poke_id, slot, gen): returns id of an ability that pokemon can have. slot is either 0, 1, or 2 (which ability to return). gen is optional and last gen is used when omitted. Will return undefined if pokemon is unknown or slot is out of range.
    • pokemon(num): returns the name of the pokemon.
    • pokeNum(name): returns the number of the pokemon.
    • pokeType1(pokeId, gen): returns pokemon's primary type id. If optional gen is not specified last supported Generation will be used.
    • pokeType2(pokeId, gen): returns pokemon's secondary type id. If optional gen is not specified last supported Generation will be used. Returns 17 (i.e. type() from it would be "???") if there is none.
    • totalPlayersByTier(tier): returns the total number of players that are ranked in that tier.
    • type(id): returns pokemon type's display name by id.
    • typeNum(typeName): returns pokemon type's id by name.
    • weather(weatherId): returns weather name by id.
    • weatherNum(weatherName): returns weather id by name. weatherName can be "hailstorm", "rain", "sandstorm", "sunny", and "normal".

    2.8. Team

    • compatibleAsDreamWorldEvent(player_id, slot): checks if the pokemon is a valid male DW pokemon (no breeding moves).
    • hasDreamWorldAbility(id, index): returns true if a pokemon in the team is using a DW ability. Returns false otherwise.
    • hasTeamItem(id, itemnum): returns true or false depending if one pokémon in the team has that move.
    • hasTeamMove(id, movenum): returns true if the team has a pokemon with that move or false otherwise.
    • hasTeamPoke(id, pokenum): returns true or false depending if that player has that pokemon in his team.
    • hasTeamPokeMove(id, pokeslot, movenum): returns true or false depending if that pokémon has the move or not.
    • indexOfTeamPoke(id, pokenum): returns the slot of the pokemon in the team or undefined if the pokemon is not found.
    • indexOfTeamPokeMove(id, pokeslot, movenum): returns the slot of the move in the moveset of that pokemon in the team or undefined if the move is not found.
    • setTeamPokeDV(id, slot, stat, newValue): stat's DV for the selected pokemon will be set to newValue.
    • teamPoke(id, slot): returns pokemon in the team of that player at that slot (slots start from 0).
    • teamPokeAbility(id, slot): returns pokemon's ability id in a specified team slot.
    • teamPokeDV(id, slot, stat): returns DV (IV) of pokemon in a specified slot for specified stat.
    • teamPokeEV(id, slot, stat): returns EV of pokemon in a specified slot for specified stat.
    • teamPokeGender(player_id, slot): returns gender of a pokemon in a specified slot.
    • teamPokeItem(id, pokeslot): returns the item of that pokemon (slots start fromt 0).
    • teamPokeLevel(id, pokeslot): returns the level of the pokemon in that slot.
    • teamPokeMove(id, pokeslot, moveslot): returns the move of the pokemon of the team of that player (slots start from 0).
    • teamPokeNature(id, pokeslot): returns the nature of the pokémon in that slot.
    • teamPokeNick(id, pokeslot)

    2.9. Server management and configuration

    • exportMemberDatabase(): saves all the members database to a file called members.txt, which would be imported on next restart if the SQL database were empty of players.
    • exportTierDatabase(): saves all the tiers database (ratings) to files called tier_NameOfTier.txt, which would be imported on next restart if the SQL database were empty for those tiers
    • makeServerPublic(flag): makes server public if flag parameter is true. Private if false.
    • memoryDump(): prints a state of the memory, was used to evaluate the memory consumption.
    • modifyBaseStat(poke_id, stat, value): will change pokemon's base stat to specified value (0-255).
    • modifyMovePower(moveNum, power, generation): will change move's power to given 'power' value (0-255). 1 will cause zero damage but still counts as attacking move (unlike 0). If optional 'generation' is not specified last supported Generation will be used.
    • modifyMoveAccuracy(moveNum, accuracy, generation): will change move's accuracy to given 'accuracy' value. If optional 'generation' is not specified last supported Generation will be used.
    • modifyMovePP(moveNum, pp, generation): will change move's PP to given 'pp' value. If optional 'generation' is not specified last supported Generation will be used.
    • modifyMovePriority(moveNum, priority, generation): will change move's priority to given 'priority' value (from -128 to 127). If optional 'generation' is not specified last supported Generation will be used.
    • modifyTypeChart(attackerTypeId, defenderTypeId, modifier): will modify type chart for server. modifier must be one of the following strings: "none", "ineffective", "normal", "effective".
    • reloadTiers()
    • shutDown(): shuts down the server. (after calling the serverShutDown() event).
    • updateRatings(): updates all ratings (has something to do with rating decay).

    2.10. Helpers

    • rand(min, max): returns a random number between min inclusive and max exclusive (like rand(0, 4) will return 0, 1, 2 or 3).
    • time(): returns the number of seconds elapsed since 1 Jan 1970.

    2.11. Channels

    It is advised to allow the user to have at least one channel open at all times. Naturally, the server won't allow a user to leave a channel if it's the last channel open, but it's possible with scripts. If a user has no channel open, he has a blank screen replacing main chat, players list, and battles list, and it's not very nice.

    • channel(channelId): returns the name of that channel.
    • channelId(channelName): return channel's id by name.
    • channelIds(): returns an array of channel ids.
    • channelsOfPlayer(playerId): an array of channel ids a player is on.
    • createChannel(channelName): creates an channel with that name. The channel won't be destroyed until one player logs on that channel and off when he's the only player online. Returns the id of the create channel.
    • existChannel(channelName): returns true if a channel with that name exists.
    • isInChannel(playerId, channelId)
    • isInSameChannel(player1, player2)
    • kick(playerId, channelId)
    • playersOfChannel(channelId): an array of players for a channel.
    • putInChannel(playerId, channelId): forces a player to join a channel. Will bypass the 7 channels limit.

    2.12. Battle setup

    Use these functions ONLY in battleSetup event and only with battleId it'll pass to you. Otherwise things will break.

    • inflictStatus(battle_id, to_first_player, slot, status_id): will apply status condition to first player if to_first_player is true. To second one otherwise. Available statuses: paralyze (1), sleep (2), poison (5), freeze (3), burn (4), fine (0) and KO (31).
    • prepareWeather(battleId, weatherId): makes it so a specified weather is already in place when battle starts. This weather will not end by itself but still can be changed with weather changing moves.

    2.13. Battles.

    • getBattleLogFileName(battle_id): returns the file in which the log for the selected battle is saved.
    • forceBattle(player_id_1, player_id_2, clauses_packed, mode, is_rated): will force battle between 2 players.
     
    Last edited by a moderator: Jul 11, 2011
  4. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    [size=+1]3. Global properties[/size]​

    • script: holds the object that contains the event (the one that you would access using this in the events).
    • SESSION: see session storage (section 3.1) below.

    3.1 Session storage *new*​

    There is a global SESSION object that can auto-create objects of your choice on player log in/out and channel create/destroy. For this to work you need to define 1 function to create player objects and 1 function to create channels at the top of the scripts.js (outside of usual ({ something }) code). Then you need to register them.

    User objects are:
    • created between beforeLogIn and afterLogIn events;
    • destroyed after afterLogOut event.

    Channel objects are:
    • created between beforeChannelCreated and afterChannelCreated events;
    • destroyed after afterChannelDestroyed event.

    SESSION methods are:
    • channels(id): will return selected channel's object. Or undefined if there is none.
    • global(): will return session global data object.
    • identifyScriptAs(script_id): will mark current script with user supplied string. When you change script with your server running (Options / Scripts in server for example) this will be compared to previously stored script_id (if any). If it does not match (or if script_id is empty string) all session data will be cleared and recreated anew (unsaved session data will be lost). Call this before registerXXXFactory() functions as they can be cleared as a result.
    • registerChannelFactory(channel_create_function): will register your function to create user objects for SESSION. Function will receive created channel id as parameter. Call this only once in your script to keep SESSION objects consistent.
    • registerGlobalFactory(global_data_create_function): will register your function to create global data storage for your script. Function will receive script id (from identifyScriptAs()) as parameter. Only one object will be created until identifyScriptAs() invalidates it.
    • registerUserFactory(user_create_function): will register your function to create user objects for SESSION. Function will receive logged in user id as parameter. Call this only once in your script to keep SESSION objects consistent.
    • users(id): will return selected user's object. Or undefined if there is none.

    Example:
    Code (javascript):
    1.  
    2. // Will create new objects for each player (id - player id).
    3. function POUser(id)
    4. {
    5.     this.id = id;
    6.     this.muted = true;
    7.     // etc
    8. }
    9.  
    10. // Will create new objects for each channel (id - channel id).
    11. // Including default channel with id 0.
    12. function POChannel(id)
    13. {
    14.     this.id = id;
    15.     this.muted = false;
    16.     // etc
    17. }
    18.  
    19. function POGlobal(id) {
    20.     this.status = {
    21.         battles_allowed: true,
    22.         is_trolling: false
    23.     };
    24. }
    25.  
    26. SESSION.identifyScriptAs("some test script");
    27. SESSION.registerUserFactory(POUser);
    28. SESSION.registerChannelFactory(POChannel);
    29. SESSION.registerGlobalFactory(POGlobal);
    30.  
    31. ({
    32.  
    33. afterLogIn: function(src) {
    34.     var is_muted = SESSION.users(src).muted;
    35.     if (is_muted) {
    36.         sys.sendMessage(src, "~~~ Server ~~~: You are muted.");
    37.     }
    38. }
    39.  
    40. })
    41.  
     
    Last edited: Nov 28, 2010
  5. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    [size=+1]4. Explanations and examples[/size]

    4.1. Messages

    sendHtmlAll(message, channelId), sendHtmlMessage(playerId, message, channelId)

    These functions accept special elements inside a message:

    • <timestamp/> - replaced with a timestamp. You should add this at the start of everything, except for things like borders. It doesn't show up if the players have timestamps off.
    • <ping/> - makes the client flash if this is sent to it.

    Remember to escape external data you pass to these functions. You can add the following function to your code and use it for this:

    Code (javascript):
    1.  
    2. // Will escape "&", ">", and "<" symbols for HTML output.
    3. function html_escape(text)
    4. {
    5.     var m = text.toString();
    6.     if (m.length > 0) {
    7.         return m.replace(/\&/g, "&amp;").replace(/\</g, "&lt;").replace(/\>/g, "&gt;");
    8.     }else{
    9.         return "";
    10.     }
    11. }
    12.  
     
    Last edited: Dec 2, 2010
  6. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.2. Players

    (placeholder)
     
    Last edited: Nov 28, 2010
  7. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.3. Configuration

    getVal, getValKeys, removeVal, and saveVal are inaccessible if PO was compiled with safeonlyscript option.
     
    Last edited: Jun 9, 2011
  8. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.4. Scripting

    delayedCall(function, seconds)

    callLater() works. However using it isn't always convenient. If your code becomes large you can define a new function however if it has parameters… you are into the joy of callLater("myFunction(" + a +","+ b +")") again.

    On the other hand delayedCall() operate using functions. If you know Javascript you may skip following description.

    Example 1:
    Code (javascript):
    1.  
    2. function do_something()
    3. {
    4.     sys.sendAll("1st!");
    5. }
    6.  
    7. ({
    8.  
    9. serverStartUp : function() {
    10.     sys.delayedCall(do_something, 4);
    11. }
    12.  
    13. })
    14.  
    is the same as callLater("do_something();"). Which is the same as callLater("sys.sendAll('1st!');") in this example.

    Example 2. As using a separate function for a single call may be overkill you can use anonymous function as 1st parameter:
    Code (javascript):
    1.  
    2. ({
    3.  
    4. serverStartUp : function() {
    5.     sys.delayedCall(function() { sys.sendAll("1st!"); }, 4);
    6. }
    7.  
    8. })
    9.  
    Example 3. Or this way, if you think it will be more readable with more that 1 call inside of function.
    Code (javascript):
    1.  
    2. ({
    3.  
    4. serverStartUp : function() {
    5.     sys.delayedCall(
    6.         function (){
    7.             sys.sendAll("1st!");
    8.         },
    9.         4
    10.     );
    11. }
    12.  
    13. })
    14.  
    If you need to have a separate function to call with parameters you need to wrap your call in anonymous function, that will call another.

    Separate functions (as in 1st example) will not have access to variables from where are you calling delayedCall().

    Anonymous functions (2nd and 3rd examples) will but there are "resolved" at the time they are run.

    Code (javascript):
    1.  
    2. function do_something_2(something)
    3. {
    4.     sys.sendAll(something);
    5. }
    6.  
    7. ({
    8.  
    9. serverStartUp : function() {
    10.     var x = "Scrappy";
    11.     sys.delayedCall(function(){ do_something_2(x); }, 6);
    12. }
    13.  
    14. })
    15.  
    seems to work.

    However… if you do
    Code (javascript):
    1.  
    2. function do_something_2(something)
    3. {
    4.     sys.sendAll(something);
    5. }
    6.  
    7. ({
    8.  
    9. serverStartUp : function() {
    10.     var x = "Scrappy";
    11.     sys.delayedCall(function(){ do_something_2(x); }, 6);
    12.     x = "Woops";
    13. }
    14.  
    15. })
    16.  
    do_something_2() will use "Woops" (new value) instead of "Scrappy" as at the time do_something_2() will be called that x is "Woops". If that's what you want — good. If you wanted it to be value of x at the time you call sys.delayedCall() you'll need to write a bit more:

    Code (javascript):
    1.  
    2. function do_something_2(something)
    3. {
    4.     sys.sendAll(something);
    5. }
    6.  
    7. ({
    8.  
    9. serverStartUp : function() {
    10.     var x = "Scrappy";
    11.     sys.delayedCall(
    12.         // Temporary function that will run now and not at the later time.
    13.         // It has as many parameters as you need to pass.
    14.         function(t) {
    15.             // This will return simple function without arguments
    16.             // that will be passed to sys.delayedCall().
    17.             return function(){
    18.                 // Your code goes here.
    19.                 do_something_2(t);
    20.             };
    21.         // Function declaration ends at next "}".
    22.         // Then it's being called with actual variable(s) as parameter(s).
    23.         }(x),
    24.         6
    25.     );
    26.     x = "Woops";
    27. }
    28.  
    29. })
    30.  
    This will print "Scrappy" in chat window.

    system(command)

    This function is inaccessible if PO was compiled with either safeonlyscript or nosysteminscript option.
     
    Last edited: Jun 9, 2011
  9. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.5. Files

    Functions in this category are inaccessible if PO is compiled with safeonlyscript option.
     
    Last edited: Jun 9, 2011
  10. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.6. Web

    Functions in this category are inaccessible if PO is compiled with safeonlyscript option.
     
    Last edited: Jun 9, 2011
  11. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.7. Information

    (placeholder)
     
  12. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.8. Team

    (placeholder)
     
  13. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.9. Server management and configuration

    (placeholder)
     
  14. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.10. Helpers

    (placeholder)
     
  15. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.11. Channels

    (placeholder)
     
  16. Mystra

    Mystra Active Member

    Joined:
    Jul 12, 2010
    Messages:
    1,389
    Likes Received:
    4
    4.12. Battle setup

    (placeholder)
     
    Alipio likes this.
Thread Status:
Not open for further replies.