The new LuaAPI functions (Server, Object, trade, Stats, Inventory, Item, Formula, Skill) and 8 new events: signatures, return values, access rights, limits and examples.
Overview
This page lists the functions and events added to LuaAPI. The functions are in the familiar tables (Server, Object, Player, Inventory, Item, Skill) plus two new tables, Stats and Formula. All functions follow the common parameter-checking rule of LuaAPI: wrong parameters (not a number, NaN, infinity, a non-existent object index) do not raise a Lua error but return false, nil or -1 as stated for each function.
The Access column in the tables below has 3 kinds:
| Access | Meaning |
| read | Only reads data; usable in every event, including restricted mode. |
| send packet (cost N units) | Only sends a packet to the player's client, counted against the SendRate limit (see Limits configuration). The cost N is the number of units deducted per call. |
| write data | Changes the character's real data. It only works on a character that is playing, not restricted and not yet exited. In a blocking event in restricted mode the function does nothing and returns false. |
The Server table
| Function | Returns | Access | Description |
Server.GetVIPLevel() | integer | read | The minimum VIP level required to enter this server; -1 = the server is open to everyone. It returns only the access type, not the minimum / maximum VIP range. |
Server.GetMaxLevel(levelType) | integer or nil | read | The maximum level of a level type: 0 normal, 1 master, 2 majestic. Any other type returns nil. |
The Object table
| Function | Returns | Access | Description |
Object.Distance(indexA, indexB) | integer | read | The distance in grid cells between two objects (players or monsters). -1 if either does not exist. |
Object.GetElementalAttribute(index) | integer | read | The main element of the object; 0 = none (or the object does not exist). |
The Player table: sending packets
This group only sends packets to the client and does not change data on the server. Each call costs 1 SendRate unit. Wrong parameters or an invalid player return false; success returns true.
| Function | Access | Description and notes |
Player.SendPKLevel(aIndex) | send packet (1) | Resends the current PK level to the client. |
Player.SendExp(aIndex, exp, damage, flag) | send packet (1) | Only sends the packet that displays EXP, does not add EXP. exp must be greater than 0 (maximum 9e15); damage 0..65535, flag 0..255 (default 0). To add real EXP, use Player.GiveExperience. |
Player.SendTradeOkButton(aIndex, state) | send packet (1) | The state of the OK button of the trade window: 0 none, 1 green, 2 an item was removed. Any other value returns false. It is only a packet. |
Player.SendTradeCancel(aIndex, result) | send packet (1) | Sends the trade result packet, result 0..7. It only sends a packet and does not change the trade state on the server: sending a fake cancel can make the client window differ from the server. To really cancel, use Player.TradeCancel. |
Player.SendTradeResponse(aIndex, accepted, name, level, guildId) | send packet (1) | Sends the packet that answers a trade request. accepted is a boolean or a number (any other type returns false); name is the name of the person answering (automatically truncated to fit the packet); level 0..65535; guildId a non-negative integer. |
The Player table: trade and traded items
| Function | Returns | Access | Description and notes |
Player.TradeOkButton(aIndex) | boolean | write data + packet (2) | Presses the OK button on behalf of a player who is in the trade window. When both sides have pressed OK the exchange really takes place and the onTradeAccept event is called. Both players must be in the trade window with each other. It cannot be called from onTradeAccept itself (restricted mode). |
Player.TradeCancel(aIndex) | boolean | write data + packet (10) | Really cancels the trade: cancels both sides, returns the items / zen, sends the cancel result and queues the onTradeCancel event. Returns false if the character is not in a trade. |
Player.GetTradeItem(aIndex, slot) | table or nil | read | The item in trade slot slot (0..31); the table has the same structure as Player.GetItem. nil if the slot is empty or the parameters are wrong. |
Player.GetCurseSpell(aIndex) | number | read | The Curse power of the book / staff being held: takes the larger value of the two hand slots (slots 0 and 1). 0 if nothing is held. |
The Stats table (new)
Stats.Add(aIndex, stat, amount, usedPoints) -> boolean
| Parameter | Type | Description |
aIndex | integer | Player index |
stat | integer | 0 Strength, 1 Agility, 2 Vitality, 3 Energy, 4 Command (Dark Lord only) |
amount | integer | The amount added to the base stat; a negative number subtracts. Must be an integer. |
usedPoints | integer | The number of Level Up Points deducted; default 0, may not exceed the points currently available |
- Access: write data + packet (5 units).
- The stat after adding is clamped between 0 and the maximum configured for that stat. The server then recalculates the character and sends the stats and points back to the client.
- Returns
false when: stat is outside 0..4, amount is not an integer, the Command stat is used with a class other than Dark Lord, or the packet quota is used up.
- It only affects the base stat. The "extra stats" mode is not available in this function.
The Inventory table
| Function | Returns | Access | Description and notes |
Inventory.SendDelete(aIndex, slot) | boolean | send packet (1) | Tells the client to delete inventory slot slot. It does not delete the item on the server side. To really delete, use Inventory.DeleteSlot. slot must be inside the inventory, otherwise it returns false. |
Inventory.RectCheck(aIndex, x, y, width, height) | integer or false | read | Checks whether a rectangle in the main inventory is empty. Returns the first slot number (12 + y * 8 + x) if empty; 255 if it overlaps another item or goes past the right edge; 254 if it goes past the bottom of the usable inventory area. Returns false for wrong parameters: x 0..7, y from 0, width and height 1..8. |
The Item table
| Function | Returns | Access | Description and notes |
Item.GetAttr(itemCode) | table or nil | read | A read-only copy of the item template stats (see the list of fields below). nil if the code does not exist. Each call creates a new table: if you use it a lot, store it in a variable. |
Item.RandomExcOption(maxOptions) | integer | read | A random Excellent option bit mask, number of lines 1..6 (values outside the range are clamped). |
Item.RandomExcOptionForItem(itemCode, count, base) | integer or nil | read | A random Excellent option mask valid for that exact item. count 0..6 (default 1), base 0..255 (default 0). nil if the item code is wrong. |
Item.RandomSetPart(setIndex) | itemCode or nil | read | A random piece of a normal set (armor, helm...). nil if there is no such set. Use together with Item.Give. |
Item.RandomAncientSetPart(ancientSetId) | itemCode, ancientType or nil | read | A random piece of an Ancient set, returning two values: the item code and the Ancient type (1 / 2 / 3). Give the item with Item.Give(aIndex, {Index = code, Ancient = ancientType}) so that it still goes through the safety checks of Item.Give. |
Fields of Item.GetAttr
The returned table contains: Name, Index, Slot, Width, Height, Option (flag bits), Level, Serial, TwoHands, QuestItem, ExpensiveItem, NonValue, SetAttribute, DamageMin, DamageMax, AttackRate, DefenseRate, Defense, MagicDefense, MagicPower, CombatPower, AttackSpeed, WalkSpeed, Durability, MagicDurability, DurabilityReduction, ReqLevel, ReqStrength, ReqAgility, ReqVitality, ReqEnergy, ReqCommand, Value, BuyMoney, ItemKindA, ItemKindB, ItemKindC, ItemSlot, SkillType, MasteryGrade, LegendaryGrade, PentagramType, MasteryPentagram, ElementalDamage, ElementalDefense, ItemOverlap, plus the two arrays RequireClass[1..] and Resistance[1..] (numbered from 1).
Formula.GetValue(type, id, ...) -> number | nil
Calculates a formula in FormulaData with up to 10 numeric parameters. Access: read (no player needed). type 0..255, id 0..65535. Returns nil when there is no such formula, the result is not finite, or more than 10 parameters are passed.
The Skill table
Skill.UseNormal(aIndex, targetIndex, skill) -> boolean
- Access: write data + packet (2 units). Cannot be used in restricted mode.
- The server runs exactly the same processing path as when the client sends a skill-use packet. Therefore all the normal checks still apply: the character must have the skill, range, timing, safe zone and the anti-hack checks.
true means the request was forwarded, not a guarantee that the skill hit. Returns false if the skill is missing, the target does not exist or the parameters are wrong.
New events
Attach functions to events with BridgeFunctionAttach like the other events (see Attaching modules and Events). Notification type: the function's result is ignored, and the function is called at the start of the next loop (only onDisconnectAllPlayers is called immediately). Blocking type: called immediately in place; return 0 / false to block.
| Event | Parameters | Type | When it is called |
onDisconnectAllPlayers() | none | notification | At the start of disconnecting all players when GameServer shuts down. Called immediately (not queued) because the event queue is no longer processed at shutdown. |
onInventoryInsertItem(aIndex, slot, itemCode) | player, slot, item code | notification | An item is added to the main inventory while playing. Not called when loading from the database on entering the game. |
onEventInventoryInsertItem(aIndex, slot, itemCode) | as above | notification | As above, for the event inventory. |
onMuunInventoryInsertItem(aIndex, slot, itemCode) | as above | notification | As above, for the Muun inventory. |
onMoveMap(aIndex, map, x, y, gate) | player, map, coordinates, gate code | notification | After the teleport has been accepted and the character starts appearing at the new place. gate is the gate code, 0 if the move did not go through a gate. |
onMonsterKill(aIndex, monsterIndex, class) | killer, monster, monster class | notification | A monster dies and the killer (the player who dealt the most damage, or the owner of a summoned monster) is a player. A monster killed by another monster does not call this event; use onMonsterDie. |
onMonsterSpawn(monsterIndex, class) | monster, monster class | notification | A monster appears on the map. Called only for monster classes registered with Monster.WatchRespawn(class): otherwise there would be thousands of events at startup. |
onShieldEffectSend(attackerIndex, victimIndex) | attacker, victim | blocking (restricted) | Right before the shield (SD) break effect is sent to the client. Return 0 / false to not send the effect. onShieldBreak is still called. This is a hot path of combat: it is only called when a function is listening; the script should only read data and return a result very quickly. |
The onMonsterSpawn event must be enabled with Monster.WatchRespawn for each monster class you care about. The registration list is lost when LuaAPI is reloaded, so register again in onGameServerStart.
Examples
1. Show the maximum level and the distance
function MyModule_Info(aIndex, targetIndex)
local maxLv = Server.GetMaxLevel(0)
local dist = Object.Distance(aIndex, targetIndex)
Message.Send(aIndex, 1, "Max level " .. tostring(maxLv) .. ", target is " .. dist .. " cells away")
end
2. Add stat points with a command
-- Add 10 Strength, deduct 10 available points
if Stats.Add(aIndex, 0, 10, 10) then
Message.Send(aIndex, 1, "Added 10 Strength")
end
3. Really cancel a trade (not just send a packet)
-- If the player is trading while it is forbidden, cancel both sides and return the items
if Player.TradeCancel(aIndex) then
Message.Send(aIndex, 1, "The trade has been cancelled")
end
4. Give a random piece of an Ancient set
local code, ancient = Item.RandomAncientSetPart(1)
if code ~= nil then
Item.Give(aIndex, { Index = code, Ancient = ancient })
end
5. Reward when a player kills the right monster class
function MyModule_OnKill(aIndex, monsterIndex, class)
if class == 78 then
Message.Send(aIndex, 1, "You defeated the target monster")
end
end
BridgeFunctionAttach("onMonsterKill", "MyModule_OnKill")
6. Track monster spawns
function MyModule_Start()
Monster.WatchRespawn(78) -- enable reporting for monster class 78
end
BridgeFunctionAttach("onGameServerStart", "MyModule_Start")
function MyModule_OnSpawn(monsterIndex, class)
Log.Add("Monster " .. class .. " spawned at index " .. monsterIndex)
end
BridgeFunctionAttach("onMonsterSpawn", "MyModule_OnSpawn")
Monster.WatchRespawn(class, watch): class = the monster class number in Data\Monster (78 is only an example), watch = true on / false off (default true).
What has not been added and why
Some functions of the Lua API of another MU server are deliberately missing here because they are unsafe or the server has no corresponding feature. When running scripts written for another API (see Running scripts written for another Lua API), these functions log once and return nil.
| Feature | Why it is not available |
Character reset (Player.DoReset, event onPlayerReset) | GameServer has no reset procedure (only a counter of the number of resets). The server owner must decide the rules: level, stats, zen. |
Creating an NPC with an NPC type (Object.AddNPC, Object.NPCType) | NPC behavior is the name of a function as text, and there is no table that maps NPC types to functions. |
Sending an NPC dialog result (NPC.SendTalkResult) | Sending this packet without the server knowing the UI state would make the client open a window the server does not know about. Use Player.OpenWarehouse for the warehouse. |
Buying a Cash Shop item (CashShop.ItemBuy) | It needs the whole procedure of deducting money and creating the product; there is a risk of giving free items or charging twice. |
Inserting an item directly into a slot (Inventory.Insert, Inventory.InsertAt) | Inserting without going through the database would duplicate serial numbers and duplicate items. Item.Give (which issues serials asynchronously) already does this job. |
Creating a random set (Item.MakeRandomSet) | Replaced by Item.RandomSetPart / Item.RandomAncientSetPart combined with Item.Give. |
Using a duration skill (Skill.UseDuration) | The client has no separate duration-skill packet (all skills use the same packet), so Skill.UseNormal is enough. |
Selling an event inventory item (onShopSellEventItem) | The server has no sell path for the event inventory (only the normal inventory). |
| Some object fields: combat power, element pattern, duel wins / losses, number of resets per day, VIP mode, fourth-tree points used, crown holding time | The server has no data source or read function for them. |
The "extra stats" mode of Stats.Add | Not supported: it only adds to the base stat. |
See also: Events, Inventory, Items, Limits configuration, Error handling and safety notes.