How it works
GameServer looks up a global function in Lua by name (for example onPlayerLogin) and calls it when the event happens. If the function does not exist, GameServer skips it without using any resources: only events that have a handler function are called.
There are 2 ways to write the handler for an event:
- Write the
onXxxfunction directly (for example inSystem\Callbacks.lua). - Write the function in a module and attach it to the event with
BridgeFunctionAttach(see Attaching a module to events). This allows multiple modules to listen to the same event, and each module is protected from errors separately.
The aIndex parameter is the player's object index, used for every function in the Player group.
Two kinds of events: blocking and notification
| Kind | How GameServer calls it | Return value |
|---|---|---|
| Blocking | Called immediately in place, before the game performs the action. | Return 0 or false = block the action. Return any other value, or return nothing (nil) = allow. A function that errors or does not exist also = allow (a script error must not block the player). |
| Notification | Queued and called at the start of the next loop of GameServer, not interleaved in the middle of combat code. If the event is tied to a character who has already left (or whose index now belongs to someone else), it is skipped. | Ignored. |
event queue full, event dropped is written.Restricted mode
Many blocking events are called right in the middle of game logic (during combat, moving items, trading...). For the events marked Restricted = yes in the tables below, the script may only read data and send notifications. Functions that write player data, teleport, or create / delete items or monsters do nothing (they return failure). If you need to change data, block the action and then use Timer.Create(1, ...) to do it afterwards.
In onPlayerLogout, the character that is leaving may only be read and sent notifications; no data may be written.
System events (predefined in Callbacks.lua)
| Function | When it is called | Parameters | Returns |
|---|---|---|---|
onGameServerStart() | The script has just finished loading (GameServer startup or LuaAPI reload). Should only read configuration / create NPCs and monsters. | none | ignored |
onScriptUnload() | Before LuaAPI is reloaded or GameServer is shut down. | none | ignored |
onPlayerLogin(aIndex) | The character has finished entering the game. Called once per entry (changing maps does not call it again). Called at the start of the next loop (notification event). After LuaAPI is reloaded, it is called again for every character currently playing. | aIndex | ignored |
onPlayerLogout(aIndex) | The character leaves the game (exits or returns to the character selection screen). Called immediately so that the character data can still be read. If onPlayerLogin for this character has not been called yet, onPlayerLogout is not called either. | aIndex | ignored |
onPlayerDie(aIndex, killerIndex) | The character dies (notification event). | aIndex; killerIndex = index of the player / monster that killed, -1 if unknown | ignored |
onLuaCommand(aIndex, code, name, arg) | A player types a command declared in Data\Commands\LuaCommands.xml (see below). | code = command ID; name = command name; arg = the text after the command name | GameServer does not use the return value |
onDBQueryResult(label, param, result) | The result of a DB.Query is available. See Asynchronous DB queries. | label, param, result | 1 = run the query again |
onTimerProcessSecond(), onTimerProcessMinute(), onTimerProcessHour(), onTimerProcessDayChange() | Every second / at a new minute / new hour / new day (00:00). See Timers. | none | ignored |
Chat commands and onLuaCommand
- Declare the command in
Data\Commands\LuaCommands.xml:<Command ID="2000" name="test" Description="" Authority="0"/>.IDis a number you choose yourself (a separate number for each command),nameis the command name (case-insensitive),Authority=0for everyone; non-0is only for administrator accounts that have the permission enabled. - The player types
/nameor.name(parameters can be added after the name). - GameServer passes it to Lua only if the command is not in the server's built-in command table. A command with the same name as a built-in command will run the built-in command.
onLuaCommand(aIndex, code, name, arg)is called;System\Callbacks.luaforwards it to the modules that attachedOnCommandManagerwithcmdtype = 16.- Read parameters with
Util.ArgNumber(arg, 0),Util.ArgString(arg, 1)(the index starts at 0).
Two notes verified in the source code:
- The return value of
onLuaCommandis ignored by GameServer. A command that is inLuaCommands.xmlis considered handled, whatever Lua returns. - If a command is typed with the
.prefix and the name is in neither the admin command table norLuaCommands.xml, the player receives the message "There is no such command." (the text comes from the language file). Typing with the/prefix does not give this message.
function Commands_OnCommandManager(aIndex, cmdtype, code, arg)
if code ~= 2000 then
return 0
end
local number = math.floor(Util.ArgNumber(arg, 0))
local text = Util.ArgString(arg, 1)
Message.Send(aIndex, 1, string.format("Hello %s! number = %d, text = %s", Player.GetName(aIndex), number, text))
return 1
end
BridgeFunctionAttach("OnCommandManager", "Commands_OnCommandManager")
Blocking events
Return 0 / false to block. Restricted: yes = runs in restricted mode (read only + send notifications).
| Function | When it is called | Parameters | Restricted |
|---|---|---|---|
onUseCommand(aIndex, text) | The player types chat starting with / (normal command) or . (admin command), before GameServer processes it. Not called for // and .., or strings shorter than 2 characters. Block = the command does not run. | text = the whole string typed, including the first character (/ or .) | no |
onNpcTalk(aIndex, npcIndex) | The player clicks an NPC and meets the conditions to talk. Block = the NPC dialog does not open. | npcIndex = NPC index. See the note about parameter order when attaching with OnNpcTalk | no |
onTradeRequest(aIndex, targetIndex) | Trade invitation. | inviter, invitee | no |
onTradeAnswer(aIndex, requesterIndex, accept) | Reply to a trade invitation. | accept = true if agreed | no |
onTradeAccept(aIndex, targetIndex) | Both sides confirm the trade (before the exchange). | the two trading players | yes |
onCanEnterEvent(aIndex, eventId) | The player enters an event (Devil Square uses its own eventId; other events use the event code of the event manager). | eventId = event code | no |
onItemUse(aIndex, sourceSlot, targetSlot, useType) | Using an item. | source slot, target slot, use type | yes |
onItemPick(aIndex, item) | Picking up an item from the ground. | item = item table | yes |
onItemDrop(aIndex, slot, x, y, item) | Throwing an item onto the ground. Not called when items drop because the character died. | slot, drop coordinates, item table | yes |
onItemMove(aIndex, sourceBox, sourceSlot, targetBox, targetSlot, state) | Moving an item between slots / warehouses. state = 0 is the blocking call. | source warehouse and slot, target warehouse and slot, state | yes |
onItemEquip(aIndex, sourceSlot, targetSlot, state) | Equipping an item. state = 0 is the blocking call. | source slot, target slot, state | yes |
onItemUnEquip(aIndex, sourceSlot, targetSlot, state) | Unequipping an item. state = 0 is the blocking call. | as above | yes |
onShopBuy(aIndex, npcIndex, item, price) | Buying an item at an NPC shop. | NPC, item table, total price | yes |
onShopSell(aIndex, npcIndex, item, slot, price) | Selling an item to an NPC. | NPC (-1 if none), item, slot, selling price | yes |
onMossMerchantUse(aIndex, section) | Buying at the Moss Merchant. | the type value in the client's purchase packet (the kind of selected entry) | yes |
onCashShopBuy(aIndex, package, option) | Buying at the Cash Shop. | package, option | yes |
onCashShopGift(aIndex, package, option, targetName) | Gifting at the Cash Shop. | package, option, recipient name | yes |
onCashShopItemUse(aIndex, uniqueCode, authCode) | Using an item in the Cash Shop inventory. | item code, serial number | yes |
onMapMoveRequest(aIndex, map, gate, moveId) | Teleporting via the move list (M key, move command). Block = no teleport (the script should tell the player the reason itself). | destination map (-1 if the gate is not found), gate, move line code | no |
onGateEnter(aIndex, gate) | The character steps into a teleport gate. If blocked, for the next 3 seconds GameServer does not ask the script again for the same gate. | gate = gate number | yes |
onCheckUserKiller(killerIndex, victimIndex) | Checks a player attacking a player (PvP). | attacker, victim | yes |
onCheckUserTarget(attackerIndex, targetIndex) | Checks the target when attacking (PvP only). | attacker, target | yes |
onUseSkill(aIndex, targetIndex, skill) | Using a skill. Only called for skills registered with Skill.Watch(skill, true). | target (-1 if none), skill number | yes |
Notification events
The return value is ignored.
| Function | When it is called | Parameters |
|---|---|---|
onTradeCancel(aIndex, otherIndex) | Trade cancelled. | otherIndex = the other party, -1 if none |
onEventEnter(aIndex, eventId) | The player has entered an event. | eventId |
onEventStart(eventId, duration, notify) | An event starts (not tied to a character). | event code, duration, notification flag |
onItemGet(aIndex, slot, inventoryType, item) | An item was successfully picked up into the inventory. | receiving inventory slot, inventoryType (always 0), item table |
onItemRepair(aIndex, slot, cost, autoRepair) | Repairing an item. | slot, cost, auto-repair flag |
onShopItemBought(aIndex, slot, item) | Finished buying an item at an NPC shop. | receiving inventory slot, item table |
onTeleport(aIndex, map, x, y) | The character has teleported. | map, coordinates |
onCharacterJoinMap(aIndex, map) | The character enters a map. | map |
onTeleportMagic(aIndex, x, y) | Using a teleport skill. | destination coordinates |
onPlayerConnect(aIndex, account, isSubSwitch) | An account logs into GameServer (not tied to a character). | account; isSubSwitch = true if it is a sub-server switch |
onCharacterSelect(aIndex, account) | The account enters the character selection screen (not tied to a character). | account |
onPlayerDisconnect(account, accountId) | The account disconnects. | account name, account ID |
onCloseWindow(aIndex, window) | A UI window is closed (warehouse, trade, shop...). | window = a string code of the window just closed (the same kind as the value returned by Player.GetInterface, not a number) |
onWarehouseOpen(aIndex) | Warehouse opened. | aIndex |
onWarehouseClose(aIndex) | Warehouse closed. | aIndex |
onPlayerLevelUp(aIndex, levelType, level) | Level up. | level type, new level |
onPlayerGiveExp(aIndex, exp) | Receiving experience. EXP is accumulated and reported once per loop (not for each hit). | total EXP received |
onPlayerKill(killerIndex, victimIndex) | A player kills another player. | killer, victim |
onPlayerRespawn(aIndex, killerType) | The character respawns. | killerType: -1 killer unknown, 1 killed by a player, 0 otherwise |
onMonsterDie(monsterIndex, killerIndex, class, map, x, y) | A monster dies (not tied to a character). killerIndex is the object that dealt the most damage, -1 if none. | monster index, killer, monster type, map, coordinates |
onMonsterRespawn(monsterIndex, class) | A monster respawns. Only called for monster types registered with Monster.WatchRespawn(class, true). | monster index, monster type |
onShieldBreak(attackerIndex, victimIndex) | The victim's shield (SD) is broken. | attacker, victim |
onPacketRecv(aIndex, data, size, headcode) | Receiving a packet from the client that GameServer does not know how to handle. | data = packet content (byte string), size, packet head code |
onServerShutdown(secondsLeft) | A timed GameServer shutdown command: called when the countdown starts, when the countdown is cancelled and when the countdown reaches 0 (not called every second). | When the countdown starts: the initial number of seconds left. -1 = shutdown cancelled. 0 = countdown finished, GameServer starts closing. |
The events onScheduleNotice, onScheduleStart, onScheduleEnd are emitted by the Scheduler library in Library.lua, not by GameServer. See the page Ready-made library.
Writing your own onXxx function directly
You can define a global function with the same name as an event (for example function onItemUse(aIndex, s, t, u) ... end). Note: BridgeFunctionAttach only creates the onXxx function by itself when that function does not exist yet. If you write the function yourself, the modules already attached to that event will not be called, unless your function calls BridgeDispatch("onItemUse", aIndex, ...) and returns its result.
System\Timers.lua, the functions onTimerProcessMinute, onTimerProcessHour, onTimerProcessDayChange are already defined (empty) and do not call modules. Therefore BridgeFunctionAttach with these events has no effect unless you add BridgeDispatch to those functions. The per-second event (OnTimerThread) works normally.