Skip to content

LuaAPI Library

itvnnnd87 edited this page Oct 24, 2026 · 2 revisions

Library

System\Library.lua adds 48 ready-made functions written in Lua on top of the GameServer functions (with the 9 Timer functions of System\Timers.lua: 57). They are loaded before your modules, so every module can use them.

Helpers

Small helpers for item codes and colours. An item code is group * 512 + index.

Helpers.MakeItemId

Helpers.MakeItemId(group, index) → number

Builds an item code from its group and its index inside the group (group * 512 + index).

local JEWEL_OF_BLESS = Helpers.MakeItemId(14, 13)    -- 7181
if Inventory.CountItem(aIndex, JEWEL_OF_BLESS, -1) >= 10 then
    Message.Send(aIndex, 1, "You have 10 Jewels of Bless")
end

Helpers.GetItemType

Helpers.GetItemType(itemCode) → number

Returns the group of an item code (math.floor(itemCode / 512)).

local group = Helpers.GetItemType(7181)    -- 14
if group == 14 then
    Log.Add("Item 7181 is in group 14 (jewels and potions)")
end

Helpers.GetItemIndex

Helpers.GetItemIndex(itemCode) → number

Returns the index of an item code inside its group (itemCode % 512).

local code = Helpers.MakeItemId(14, 13)
Log.Add("group " .. Helpers.GetItemType(code) .. ", index " .. Helpers.GetItemIndex(code))    -- group 14, index 13

Helpers.RGB

Helpers.RGB(r, g, b) → number

Returns a colour value: r + g * 256 + b * 65536. A missing or non-number part counts as 0.

local GOLD = Helpers.RGB(255, 200, 0)    -- 51455
Log.Add("Gold colour value: " .. GOLD)

Item.RandomLevel

Item.RandomLevel(min, max) → number

Returns a random item level between min and max (both included), using Util.Random.

Item.Give(aIndex, {
    Index = Helpers.MakeItemId(0, 0),    -- Kris
    Level = Item.RandomLevel(7, 11),
})

Coins by type

One set of functions for every currency. coinType: COIN_ZEN (0), COIN_WCOIN (1), COIN_GOBLIN_POINT (2), COIN_RUUD (3). These constants are defined in Library.lua. COIN_WCOIN uses the WCoinC value of Coin.Get.

Coin.IsValidType

Coin.IsValidType(coinType) → boolean

true if coinType is 0, 1, 2 or 3.

function Shop_SetPrice(coinType, amount)
    if not Coin.IsValidType(coinType) then
        Log.AddC(1, "[Shop] unknown coin type " .. tostring(coinType))
        return false
    end
    return true
end

Coin.GetName

Coin.GetName(coinType) → string

Returns "Zen", "WCoin", "Goblin Point" or "Ruud", and "" for an unknown type.

local PRICE_TYPE, PRICE = COIN_RUUD, 500
Message.Send(aIndex, 1, "Price: " .. PRICE .. " " .. Coin.GetName(PRICE_TYPE))

Coin.GetByType

Coin.GetByType(aIndex, coinType) → number

Returns how much of that currency the character has. Unknown type: 0.

local wcoin = Coin.GetByType(aIndex, COIN_WCOIN)
local ruud = Coin.GetByType(aIndex, COIN_RUUD)
Message.Send(aIndex, 1, "WCoin: " .. wcoin .. ", Ruud: " .. ruud)

Coin.Check

Coin.Check(aIndex, coinType, amount) → boolean

true if the character has at least amount. A negative amount returns false.

if not Coin.Check(aIndex, COIN_ZEN, 10000000) then
    Message.Send(aIndex, 1, "You need 10,000,000 Zen")
    return 1
end

Coin.Charge

Coin.Charge(aIndex, coinType, amount) → boolean

Takes amount if the character has enough. Returns false (and takes nothing) when there is not enough, amount is negative or the type is unknown.

local PRICE_TYPE, PRICE = COIN_WCOIN, 50

if Coin.Charge(aIndex, PRICE_TYPE, PRICE) then
    Item.GiveBag(aIndex, "LuckyBox")
else
    Message.Send(aIndex, 3, "You need " .. PRICE .. " " .. Coin.GetName(PRICE_TYPE))
end

Coin.Give

Coin.Give(aIndex, coinType, amount) → boolean

Gives amount. Returns false when amount is 0 or less or the type is unknown.

function DailyReward_OnLogin(aIndex)
    Coin.Give(aIndex, COIN_GOBLIN_POINT, 10)
    Message.Send(aIndex, 1, "You received 10 " .. Coin.GetName(COIN_GOBLIN_POINT))
end

BridgeFunctionAttach("OnCharacterEntry", "DailyReward_OnLogin")

ActionTick

3 slots (0, 1, 2) per character to store a time and a short name, for example cooldowns. Cleared when the character leaves the game. Any other slot number is ignored.

ActionTick.Set

ActionTick.Set(aIndex, slot, tick, name) → boolean

Stores a value in slot 0, 1 or 2 of the character (name up to 15 characters). Returns false for a wrong slot or when aIndex is not a character in game.

ActionTick.Set(aIndex, 0, Util.GetTick(), "reward")

ActionTick.Get

ActionTick.Get(aIndex, slot) → number

Returns the stored value, 0 if nothing is stored.

-- /reward can be used once every 60 seconds
if Util.GetTick() - ActionTick.Get(aIndex, 0) < 60000 then
    Message.Send(aIndex, 3, "Please wait")
    return 1
end
ActionTick.Set(aIndex, 0, Util.GetTick(), "reward")

ActionTick.GetName

ActionTick.GetName(aIndex, slot) → string

Returns the stored name, "" if nothing is stored.

local last = ActionTick.GetName(aIndex, 1)
if last ~= "" then
    Message.Send(aIndex, 1, "Last action: " .. last)
end

ActionTick.Clear

ActionTick.Clear(aIndex, slot) → boolean

Empties the slot. Returns false for a wrong slot or when the character has never stored anything.

-- a GM resets the cooldown of a player
local target = Player.GetIndexByName("PlayerName")
if target and target >= 0 then
    ActionTick.Clear(target, 0)
end

Scheduler

Starts and ends your own events from an XML schedule.

<EventScheduler>
    <Event Type="1" Name="Boss Hunt" NoticePeriod="300" Duration="1800">
        <Start Year="-1" Month="-1" Day="-1" DayOfWeek="-1" Hour="20" Minute="0" Second="0"/>
        <Start DayOfWeek="6" Hour="14" Minute="30"/>
    </Event>
</EventScheduler>
Attribute Meaning
Type Your event number, passed to the schedule events.
Name Display name (Scheduler.GetEventName).
NoticePeriod Seconds before the start to send onScheduleNotice. 0 = no notice.
Duration Seconds after the start to send onScheduleEnd. 0 = end it yourself with Scheduler.StopEvent.
Start One line per start time. Missing or -1 = any. DayOfWeek 0 = Sunday. Without Second, the schedule is checked once per minute.

An event that is still active is not started again. The scheduler runs by itself every second (System\Timers.lua). Receive its events with a module:

Scheduler.LoadFromXML("Includes\\BossHunt\\Schedule.xml")

function BossHunt_Notice(eventType, secondsLeft)
    Message.SendAll(0, Scheduler.GetEventName(eventType) .. " starts in " .. math.floor(secondsLeft / 60) .. " minutes")
end

function BossHunt_Start(eventType)
    EventMonsterTracker.SpawnWaveAndRegister(eventType, 275, 10, MAP_DEVIAS, 180, 80, 220, 120)
end

function BossHunt_End(eventType)
    EventMonsterTracker.CleanupEvent(eventType)
end

BridgeFunctionAttach("OnScheduleNotice", "BossHunt_Notice")
BridgeFunctionAttach("OnScheduleStart", "BossHunt_Start")
BridgeFunctionAttach("OnScheduleEnd", "BossHunt_End")

The scheduler state is cleared on Lua API reload: an event that was running is not ended by onScheduleEnd.

Scheduler.LoadFromXML

Scheduler.LoadFromXML(path) → boolean

Loads the schedule (path like File.ReadXml). Replaces the events loaded before and forgets which events were active. Returns false and writes the error to the log if the file cannot be read.

if not Scheduler.LoadFromXML("Includes\\BossHunt\\Schedule.xml") then
    Log.AddC(1, "[BossHunt] schedule not loaded")
end

Scheduler.GetEventCount

Scheduler.GetEventCount() → number

Number of Event lines loaded.

Scheduler.LoadFromXML("Includes\\BossHunt\\Schedule.xml")
Log.Add("[BossHunt] " .. Scheduler.GetEventCount() .. " events loaded")

Scheduler.HasSecondPrecisionEvents

Scheduler.HasSecondPrecisionEvents() → boolean

true if a Start line uses Second (the schedule is then checked every second instead of once per minute).

if Scheduler.HasSecondPrecisionEvents() then
    Log.Add("[BossHunt] schedule checked every second")
end

Scheduler.GetEventName

Scheduler.GetEventName(type) → string

Returns the Name of the event, "" if no event has this type.

function BossHunt_Start(eventType)
    Message.SendAll(0, Scheduler.GetEventName(eventType) .. " has started!")
end

BridgeFunctionAttach("OnScheduleStart", "BossHunt_Start")

Scheduler.CheckEventNotices

Scheduler.CheckEventNotices() → table

Events whose start is exactly NoticePeriod seconds away now: { { type = ..., secondsRemaining = ... }, ... }. Changes nothing. Used by the scheduler itself; call it only if you run your own loop.

for _, notice in ipairs(Scheduler.CheckEventNotices()) do
    Log.Add("Event " .. notice.type .. " starts in " .. notice.secondsRemaining .. " seconds")
end

Scheduler.CheckEventStarts

Scheduler.CheckEventStarts() → table

Events starting now that are not active yet: { type, ... }. Marks them active. The built-in scheduler calls it every check: an event you take with this function is not sent as onScheduleStart.

for _, eventType in ipairs(Scheduler.CheckEventStarts()) do
    Log.Add("Event " .. eventType .. " started")
end

Scheduler.CheckEventEnds

Scheduler.CheckEventEnds() → table

Active events whose Duration has passed: { type, ... }. Marks them ended. Events with Duration="0" are never returned. Same note as Scheduler.CheckEventStarts: an event you take here is not sent as onScheduleEnd.

for _, eventType in ipairs(Scheduler.CheckEventEnds()) do
    EventMonsterTracker.CleanupEvent(eventType)
end

Scheduler.IsEventActive

Scheduler.IsEventActive(type) → boolean

true between the start and the end of the event.

if not Scheduler.IsEventActive(1) then
    Message.Send(aIndex, 1, "Boss Hunt is not running now")
    return 1
end

Scheduler.GetElapsedTime

Scheduler.GetElapsedTime(type) → number

Seconds since the start, -1 if the event is not active.

local elapsed = Scheduler.GetElapsedTime(1)
if elapsed >= 0 then
    Message.Send(aIndex, 1, "Boss Hunt started " .. math.floor(elapsed / 60) .. " minutes ago")
end

Scheduler.GetRemainingTime

Scheduler.GetRemainingTime(type) → number

Seconds until the end, -1 if the event is not active or has no Duration.

local left = Scheduler.GetRemainingTime(1)
if left > 0 then
    Message.Send(aIndex, 1, "Boss Hunt ends in " .. left .. " seconds")
end

Scheduler.GetProgress

Scheduler.GetProgress(type) → number

0..100 (percent of Duration already passed), -1 if the event is not active or has no Duration.

local progress = Scheduler.GetProgress(1)
if progress >= 50 then
    Message.SendAll(0, "Boss Hunt is " .. progress .. "% done")
end

Scheduler.StopEvent

Scheduler.StopEvent(type) → boolean

Ends an active event now and sends onScheduleEnd to the modules. Returns false if the event is not active.

function BossHunt_MonsterDie(monsterIndex, killerIndex, class, map, x, y)
    if class == 275 and EventMonsterTracker.GetCount(1) == 0 then
        Scheduler.StopEvent(1)
    end
end

BridgeFunctionAttach("OnMonsterDie", "BossHunt_MonsterDie")

EventMonsterTracker

Remembers which monsters and NPCs belong to each event so they can be counted and removed together. filter: OBJECT_TYPE_MONSTER (2), OBJECT_TYPE_NPC (3), or nothing (or -1) for both. These constants are defined in Library.lua and have the same values as OBJECT_MONSTER / OBJECT_NPC.

Object indexes are reused after a monster is removed. Before deleting, the tracker checks that the index still holds the same class and object type, so it never deletes a monster that took the index later.

Tracked monsters are removed automatically when the Lua API is reloaded or the server shuts down.

EventMonsterTracker.SpawnAndRegister

EventMonsterTracker.SpawnAndRegister(eventType, class, map, x1, y1, x2, y2, element, dir) → number

Spawns one monster at a random point of the area x1, y1 .. x2, y2 and tracks it. Returns its index or -1. dir is the direction (-1 or nothing = default). element is accepted but not used.

local index = EventMonsterTracker.SpawnAndRegister(1, 275, MAP_LORENCIA, 130, 120, 140, 130)
if index >= 0 then
    Message.SendAll(0, "Illusion of Kundun appeared in Lorencia!")
end

EventMonsterTracker.SpawnWaveAndRegister

EventMonsterTracker.SpawnWaveAndRegister(eventType, class, count, map, x1, y1, x2, y2, element, dir) → table

Spawns count monsters (up to 500), each at a random point of the area, and tracks them. Returns the list of indexes that were created.

local wave = EventMonsterTracker.SpawnWaveAndRegister(2, 1, 30, MAP_LORENCIA, 160, 70, 190, 100)
Message.SendAll(0, #wave .. " Hounds invade Lorencia!")

EventMonsterTracker.Register

EventMonsterTracker.Register(eventType, index, class, type)

Tracks a monster you spawned yourself. type defaults to OBJECT_TYPE_MONSTER; pass the real object type (Object.GetType(index)) so the cleanup functions can recognize it.

local index = Monster.Create(15, MAP_DEVIAS, 200, 100, -1)
if index >= 0 then
    EventMonsterTracker.Register(2, index, 15, Object.GetType(index))
end

EventMonsterTracker.RegisterNPC

EventMonsterTracker.RegisterNPC(eventType, index, class)

Same as Register with type = OBJECT_TYPE_NPC.

local npc = Monster.Create(238, MAP_LORENCIA, 135, 125, 3)    -- Chaos Goblin
if npc >= 0 then
    EventMonsterTracker.RegisterNPC(1, npc, 238)
end

EventMonsterTracker.Unregister

EventMonsterTracker.Unregister(eventType, index) → boolean

Stops tracking the object (does not remove it). Returns false if it was not tracked.

function BossHunt_MonsterDie(monsterIndex, killerIndex, class, map, x, y)
    if EventMonsterTracker.Unregister(1, monsterIndex) and EventMonsterTracker.GetCount(1) == 0 then
        Message.SendAll(0, "All bosses are dead!")
        Scheduler.StopEvent(1)
    end
end

BridgeFunctionAttach("OnMonsterDie", "BossHunt_MonsterDie")

EventMonsterTracker.IsTracked

EventMonsterTracker.IsTracked(eventType, index) → boolean

true if the object is tracked for this event.

function BossHunt_MonsterDie(monsterIndex, killerIndex, class, map, x, y)
    if EventMonsterTracker.IsTracked(1, monsterIndex) then
        Coin.Give(killerIndex, COIN_RUUD, 100)
    end
end

BridgeFunctionAttach("OnMonsterDie", "BossHunt_MonsterDie")

EventMonsterTracker.GetObjectInfo

EventMonsterTracker.GetObjectInfo(eventType, index) → table

Returns { class = ..., type = ... } as registered, or { class = -1, type = -1 } if the object is not tracked.

local info = EventMonsterTracker.GetObjectInfo(1, monsterIndex)
if info.type == OBJECT_TYPE_NPC then
    Log.Add("Tracked NPC, class " .. info.class)
end

EventMonsterTracker.GetMonsterClass

EventMonsterTracker.GetMonsterClass(eventType, index) → number

Returns the registered class, -1 if the object is not tracked.

function BossHunt_MonsterDie(monsterIndex, killerIndex, class, map, x, y)
    if EventMonsterTracker.GetMonsterClass(1, monsterIndex) == 275 then
        Item.GiveBag(killerIndex, "KundunBox")
    end
end

EventMonsterTracker.GetMonsters

EventMonsterTracker.GetMonsters(eventType, filter) → table

Returns the list of tracked indexes of the event, optionally only monsters or only NPCs.

for _, index in ipairs(EventMonsterTracker.GetMonsters(2, OBJECT_TYPE_MONSTER)) do
    Log.Add("Monster " .. index .. " at " .. Object.GetX(index) .. ", " .. Object.GetY(index))
end

EventMonsterTracker.GetCount

EventMonsterTracker.GetCount(eventType, filter) → number

Number of tracked objects of the event (with the same filter as GetMonsters). Dead monsters are counted until they are unregistered or CleanupDead is called.

EventMonsterTracker.CleanupDead(2)
local left = EventMonsterTracker.GetCount(2, OBJECT_TYPE_MONSTER)
Message.SendAll(0, left .. " monsters left")

EventMonsterTracker.CleanupEvent

EventMonsterTracker.CleanupEvent(eventType, filter) → number

Deletes the tracked objects that still exist (Monster.Delete) and stops tracking them. Returns how many entries were removed from the list.

function BossHunt_End(eventType)
    local removed = EventMonsterTracker.CleanupEvent(eventType)
    Log.Add("[BossHunt] " .. removed .. " objects removed")
end

BridgeFunctionAttach("OnScheduleEnd", "BossHunt_End")

EventMonsterTracker.CleanupMonsters

EventMonsterTracker.CleanupMonsters(eventType) → number

Same as CleanupEvent(eventType, OBJECT_TYPE_MONSTER): removes the monsters, keeps the NPCs.

-- the wave is over: remove the remaining monsters, the event NPC stays
EventMonsterTracker.CleanupMonsters(2)
Message.SendAll(0, "Wave cleared. Talk to the Chaos Goblin for your reward")

EventMonsterTracker.CleanupNPCs

EventMonsterTracker.CleanupNPCs(eventType) → number

Same as CleanupEvent(eventType, OBJECT_TYPE_NPC): removes the NPCs, keeps the monsters.

function BossHunt_End(eventType)
    EventMonsterTracker.CleanupNPCs(eventType)
end

BridgeFunctionAttach("OnScheduleEnd", "BossHunt_End")

EventMonsterTracker.CleanupDead

EventMonsterTracker.CleanupDead(eventType, filter) → number

Stops tracking the objects that died or disappeared (removes nothing). Returns how many were dropped from the list.

function Invasion_Tick()
    EventMonsterTracker.CleanupDead(2)
    if EventMonsterTracker.GetCount(2) == 0 then
        Message.SendAll(0, "The invasion is over!")
    end
end

EventMonsterTracker.GetActiveEvents

EventMonsterTracker.GetActiveEvents() → table

List of the events that still have tracked objects.

for _, eventType in ipairs(EventMonsterTracker.GetActiveEvents()) do
    Log.Add("Event " .. eventType .. ": " .. EventMonsterTracker.GetCount(eventType) .. " objects")
end

EventMonsterTracker.ClearAll

EventMonsterTracker.ClearAll() → number

Forgets every event (removes nothing). Returns how many events were forgotten.

local forgotten = EventMonsterTracker.ClearAll()
Log.Add("[Tracker] " .. forgotten .. " events forgotten")

OptionBonus

Several modules can give option table bonuses to the same character without overwriting each other. Each module sets only its own part; the parts are added together, written to the option table and the stats are recalculated.

The bonuses are cleared on logout and on Lua API reload: set them again in onPlayerLogin.

Use OptionBonus instead of Player.SetOptionTable whenever more than one module may give bonuses.

OptionBonus.Set

OptionBonus.Set(aIndex, source, values) → boolean

Sets the bonuses of source (any name, usually the module name). values = { AddDamage = 100, MulMaxHP = 5 }; nil or {} removes them. Only number values other than 0 are kept. Returns true if something changed (nothing is recalculated when the values are the same).

function GuildBonus_OnLogin(aIndex)
    if Player.GetGuildNumber(aIndex) > 0 then
        OptionBonus.Set(aIndex, "GuildBonus", { AddDefense = 50 })
    end
end

BridgeFunctionAttach("OnCharacterEntry", "GuildBonus_OnLogin")

OptionBonus.Get

OptionBonus.Get(aIndex, source) → table

Returns a copy of the bonuses of source, {} if it has none. Changing the copy changes nothing.

local bonus = OptionBonus.Get(aIndex, "GuildBonus")
if bonus.AddDefense then
    Message.Send(aIndex, 1, "Guild bonus: +" .. bonus.AddDefense .. " defense")
end

Player object

Player.GetObject(aIndex) gives field access to a character (p.Level, p.Money = 100 ...). Every access asks the GameServer at that moment, so values are never out of date. When the character leaves the game, reads return nil and writes do nothing, even if another character gets the same index. Writing a read-only or unknown field is an error. See also Player functions.

Fields
Read and write Level MasterLevel MajesticLevel Reset LevelUpPoint MasterPoint MajesticPoint Money Ruud PKLevel PKCount PKTimer Skin Strength Dexterity Vitality Energy Leadership Life MaxLife Mana MaxMana Shield MaxShield BP MaxBP
Read only Index Name Account CharacterID Class Map X Y TotalLevel Evolution Experience NextExperience VIP VIPExpire Authority CodePage PartyNumber GuildNumber GuildName GuildStatus GensFamily GensContribution IsLive IsOffline IsGameMaster

Player.GetObject

Player.GetObject(aIndex) → object or nil

Returns the object of the character, nil if aIndex is not an online character.

local p = Player.GetObject(aIndex)
if p then
    p.Money = p.Money + 10000
    p.Life = p.MaxLife
    Message.Send(p.Index, 1, p.Name .. " level " .. p.Level)
end

Player.GetObjectByName

Player.GetObjectByName(name) → object or nil

Same as Player.GetObject, found by character name. nil if no online character has this name.

local p = Player.GetObjectByName("PlayerName")
if p then
    p.LevelUpPoint = p.LevelUpPoint + 100
    Message.Send(p.Index, 1, "You received 100 points")
end

Player.IsObjectValid

Player.IsObjectValid(object) → boolean

true while the object still points to the same character in game.

local winner = Player.GetObject(aIndex)
Timer.Create(10, "GiveWinnerPrize", function()
    if Player.IsObjectValid(winner) then
        winner.Money = winner.Money + 1000000
    end
end)

Next: Config files

Clone this wiki locally