What the compatibility layer is
Many Lua scripts for MU servers were written for a different Lua API (for example Player.GetObjByIndex, Object.ForEachPlayer(function(oPlayer) ... end), Timer.Create(ms, name, callback), function onPlayerLogin(oPlayer)). The file Data\LuaAPI\System\Compat.lua lets you run those scripts on a TSWMU server without editing them, by translating function names, parameters, results and events into the TSWMU API.
System\Compat.lua. It is loaded by Main.lua before System\Library, so its names are locked and protected by the system.How to use
- Copy the folder of the script you want to run into
Data\LuaAPI\Includes\, for exampleData\LuaAPI\Includes\MyOldScript\Main.lua. - Open
Data\LuaAPI\Main.lua, find the sample comment line (next to the module loading part) and add one line:
The path is counted fromLoadCompatScript("Includes\\MyOldScript\\Main.lua")Data\LuaAPI\; a full path also works. In a Lua string you must write two\\characters. - Press Reload LuaAPI in START (no GameServer restart needed) and then look at the GameServer log.
A typical folder layout:
Data\LuaAPI\
Main.lua (has the LoadCompatScript line)
System\Compat.lua (the compatibility layer, do not edit)
Includes\
MyOldScript\
Main.lua (script written for another API)
Config.lua (the script calls LoadScript("Config.lua"))
What happens on load
- The script runs in its own environment. When the script calls a name, the lookup order is: (1) the script's own global variables / functions; (2) the compatibility layer (the tables
Player,Object,Timer... the way the script expects them); (3) the normal global tables of TSWMU (string,math,File,Map...). - The script cannot change the TSWMU API: the real tables are never modified. Your other scripts are not affected.
LoadScript("file.lua")in that script loads the file into the same environment. The file is searched for in the folder of the running script, thenData\LuaAPI\, thenData\LuaAPI\Includes\; the prefixPlugins\LuaAPI\is dropped. The filesHelpers.lua,Constants.lua,Enums.lua,UIProtocol.lua,TimerHelpers.lua,Callbacks.lua,CallbacksDB.lua,CallbacksUI.lua, if not found, are treated as built in and no error is reported.- After loading, every event function the script defined (
onPlayerLogin,onUseCommand...) is attached to the matching TSWMU event withBridgeFunctionAttach; parameters and results are translated automatically. If two scripts have functions with the same name, both run (each script has its own wrapper function). - A syntax error or an error while loading writes the log
[Compat] path: ...andLoadCompatScriptreturnsfalse; the other scripts keep running. An error inside an event function is logged by the common error-catching mechanism and does not break other scripts. - A server function that cannot be done logs
name is not supported on this serveronce and returnsnil; the script keeps running.
Important differences in behavior
| Topic | Behavior in the compatibility layer |
|---|---|
| Money | Player.SetMoney(idx, amount, reset) of the other API adds (or resets and then adds if reset), whereas the original TSWMU Player.SetMoney sets an absolute value. The compatibility layer converts automatically so old scripts work correctly. Writing userData.Money on the object is an absolute assignment. |
| Timers | Time is in milliseconds and has an id number, but the base is the 1-second timer of TSWMU: milliseconds are rounded up to seconds (minimum 1 second). A 100 ms timer runs every 1 second; 1500 ms runs every 2 seconds. |
| Blocking events | Functions of the other API return non-zero to block; TSWMU blocks when it returns 0 / false. The compatibility layer inverts this automatically: a function that returns non-zero blocks, one that returns 0 / nil / false allows. For events that cannot be blocked the result is ignored. |
Objects (oPlayer, oMonster) | They are representative tables (proxies): every read or write of a field such as oPlayer.Level, oPlayer.Life, oPlayer.X goes straight to the server at that moment. An unknown field returns nil without an error. The proxy remembers the character ID: after the character exits, reads return nil and writes do nothing. Every function of the layer accepts a proxy or an index. |
Items (ItemInfo) | Only a snapshot of the item: editing a field on the snapshot does not change the real item. |
| Event timing | Notification events still follow TSWMU timing (queued, run in the next loop). For example onPlayerLogin runs one loop late. |
| Character stats | Stats.Set of the other API adds the value to the stat (it does not set an absolute value); the extra stats mode is not supported (logged). |
Supported events
The left column is the function name in the old script, the right column is the TSWMU event it is attached to. See each event in detail on the pages Events and Additional functions and events.
| Function in the old script | TSWMU event | Notes |
|---|---|---|
onGameServerStart | onGameServerStart | A script loaded after the server is already running is called immediately on load. |
onCharacterSelectEnter | onCharacterSelect | |
onPlayerConnect, onPlayerLogin | same name | onPlayerLogin runs one loop late. |
onPlayerDisconnect | onPlayerLogout | Character data can still be read. |
onLogOutAllPlayers, onDisconnectAllPlayers | onServerShutdown(0), onDisconnectAllPlayers | Called when the server starts shutting down. |
onOpenWarehouse, onCloseWarehouse | onWarehouseOpen, onWarehouseClose | |
onTradeRequestSend, onTradeResponseReceive, onTradeAccept | onTradeRequest, onTradeAnswer, onTradeAccept | Blocking (non-zero = block). |
onTradeCancel | onTradeCancel | Notification only, it cannot prevent the cancel. |
onBloodCastleEnter, onDevilSquareEnter, onChaosCastleEnter | onEventEnter (event 0 / 1 / 2) | The level parameter is always 0. |
onPlayerLevelUp, onPlayerMasterLevelUp | onPlayerLevelUp (level type 0 / 1) | The majestic level is not forwarded. |
onUseCommand | onUseCommand | Blocking. The command string always starts with / (a . is converted). |
onNpcTalk, onCloseWindow | same name | onNpcTalk is blocking; onCloseWindow is notification only. |
onItemUse | onItemUse | Blocking; oItem is a snapshot of the source slot. |
onInventoryMoveItem | onItemMove | Runs after the move. |
onItemGet, onEventItemGet, onMuunItemGet | onItemGet (inventory 0 / 1 / 2) | |
onInventoryInsertItem, onEventInventoryInsertItem, onMuunInventoryInsertItem | same name (new events) | |
onItemEquip, onItemUnEquip, onItemRepair | same name | |
onCharacterJoinMap, onTeleport | same name | |
onMapTeleport | onGateEnter | Cannot be blocked. |
onMoveMap | onMoveMap (new event) | |
onMapMoveRequest | onMapMoveRequest | Blocking; oWarp is built from the event, the money / level fields are 0. |
onTeleportMagicUse | onTeleportMagic | |
onPlayerKill, onPlayerDie, onPlayerRespawn | same name | |
onMonsterDie, onMonsterKill | onMonsterDie | onMonsterKill only runs when the killer is a player. |
onMonsterSpawn | onMonsterSpawn (new event) | The compatibility layer automatically tracks all monster classes when a script uses this function. |
onMonsterRespawn | onMonsterRespawn | Only monster classes that have had Monster.WatchRespawn. |
onCheckUserTarget | onCheckUserTarget | Blocking; PvP only. |
onUseNormalSkill | onUseSkill (without coordinates) | Blocking. The compatibility layer turns on tracking of all skills, so the event runs on every skill use (costs resources). |
onUseDurationSkill | onUseSkill (with coordinates) | Runs only when the server sends coordinates and direction along with it. |
onShopBuyItem, onShopSellItem | onShopItemBought, onShopSell | onShopSellItem is blocking. |
onMossMerchantUse | same name | Blocking. |
onCashShopItemBuy, onCashShopPackageBuy | onCashShopBuy | Blocking. The list / information carry only the package code and options. |
onCashShopItemGift, onCashShopPackageGift | onCashShopGift | Blocking. The message is empty if the server does not supply one. |
onCashShopItemUse | same name | Blocking. |
onDSDBQueryReceive, onJSDBQueryReceive | onDBQueryResult | Called once per column per row; an empty result calls once with a nil row. |
onTimerProcessSecond, Minute, Hour, DayChange | same name |
Main function mapping
The full list is in the file System\Compat.lua itself. The table below shows the most commonly used groups. The sign "=" means the function of the same name in TSWMU is used, only the object (proxy) is converted to an index.
| Group | Function in the old script | How it is done on TSWMU |
|---|---|---|
| Server / Object | Server.GetCode, GetName, IsNonPvP | = |
Object.ForEach, ForEachPlayer, ForEachMonster, ForEachPlayerOnMap, ForEachNearby... | The same iteration functions of TSWMU, the callback receives a proxy. Return false to stop. | |
Object.AddMonster, Object.DelMonster | Monster.Create at a random cell inside the area; Monster.Delete. The element is not set. | |
| Player | Player.GetObjByIndex, GetObjByName | Return a proxy (nil if the slot is empty / the name is not online). |
Player.SetMoney, SetRuud | Add (see the differences section). | |
Player.SendTradeOkButton, SendTradeCancel, TradeOkButton, TradeCancel, SendPKLevel, SetExp (EXP packet) | The functions in Additional functions and events. | |
| Coin / Stats | Coin.Get, Check, Charge, Add | Coin.GetByType, Check, Charge, Give |
Stats.Get, Stats.Set, Stats.LevelUp | Read base + extra stats; Stats.Set adds to the stat, recalculates and sends; Stats.LevelUp = Player.GiveExperience. | |
| Inventory / Item | Inventory.SendUpdate, SendDelete, SendList, Delete, RectCheck | Inventory.SendSlot, SendDelete, SendList, DeleteSlot, RectCheck |
Inventory.HasSpace(obj, HEIGHT, WIDTH) | Inventory.HasSpace(obj, WIDTH, HEIGHT): the parameter order is swapped. | |
Item.Create, Item.IsValid, Item.GetAttr, Item.GetRandomLevel | Granted into the inventory (Item.Give) or dropped on the ground (Item.Drop) depending on the map; the others correspond to Item.IsValid, Item.GetAttr, Item.RandomLevel. | |
| Buff / Skill | Buff.Add, Buff.Remove, Buff.CheckUsed | The parameter order of Buff.Add is changed; Buff.CheckUsed = Buff.Has. |
Skill.UseNormal, Skill.UseDuration | Skill.UseNormal (see the additional functions page); UseDuration uses the same function because the client has only one skill packet. | |
| Movement | Move.Gate, Move.ToMap, Move.Warp, Viewport.Create / Destroy | Player.MoveGate; Player.MoveTo (players) or Object.Warp (monsters, same map); Object.Warp; Object.ViewportCreate / ViewportDestroy |
| DB / Message / Log | DB.QueryDS, QueryJS | DB.Query with its own tag; the result is delivered to onDSDBQueryReceive / onJSDBQueryReceive. |
Message.Send, Log.Add, Log.AddC | Message.SendAll when the target is -1, otherwise Message.Send; Log.Add; Log.AddC with the color converted by color code. | |
| Timers | Timer.Create, CreateRepeating, RepeatNTimes, Remove, Exists, Start, Stop, GetRemaining | Implemented by the compatibility layer itself on the 1-second timer (see the rounding above). TimerHelpers (Delay, Repeat, Countdown, Debounce, Throttle...) is also available. |
| Old global functions | LogAdd, gObjTeleport, GCServerMsgStringSend, FireCrackerOpen, CreateItem... | Log.Add, Move.ToMap, Message.Send, Player.Fireworks; CreateItem grants into the inventory or drops on the ground. |
| Constants | Constants.*, Enums.* | The values of the other API; places where TSWMU numbers things differently (such as item types) are not translated. |
Unsupported functions and events
An unsupported function logs once in the form name is not supported on this server and returns nil. An unsupported event logs once in the form callback name is not supported on this server and is not attached.
| Kind | Name |
|---|---|
| Function | Player.DoReset, Player.SetShopSkin, NPC.SendDialog, Inventory.SetSlot, ItemBag.Add, Monster.IsGroupRegenLiveBossState, UI.SendWindowUse, Net.SendPacket, LoadEncryptedScript |
| Event | onDisconnectAllPlayersWithReconnect, onPlayerReset, onEventInventoryMoveItem, onMuunInventoryMoveItem, onShopSellEventItem, onShieldEffectSend, onLuaWindowOpen, onLuaWindowUse, onLuaPacket |
| Other old functions | gUserFindDevilSquareKeyEyes, gQeustNpcTeleport_TalkRefAdd, gParty_GetPKPartyPenalty, gObjGuildMasterCapacityTest, AddItemBag, GetExcellentOptByKind |
Some "optional" functions (Server.GetVIPLevel, Skill.UseNormal, Formula.GetValue, Item.GetAttr, Inventory.RectCheck...) use the function of the same name in TSWMU if it exists; if it is missing, the compatibility layer uses a fallback or reports "not supported". The functions on the page Additional functions and events are available.
Limits to know
- Lua 5.2 syntax. The Lua machine of GameServer is Lua 5.2. A script that uses Lua 5.3 syntax (
&,|,~,<<,>>,//) will fail to compile and be logged. Change it tobit32functions, for examplebit32.band(a, b),bit32.lshift(a, n). - Minimum timer of 1 second (rounded up, see the differences section).
onShieldEffectSendof old scripts is not supported through the compatibility layer (use the TSWMU event of the same name directly if needed).onMonsterSpawn: the compatibility layer automatically tracks all monster classes when a script uses it, so it can generate many events at startup. Define this function only when really needed.onUseNormalSkillturns on tracking of all skills (costs resources).- Items are snapshots; writing to item fields does not change the real item.
- A script that adds or replaces a function inside a table of the compatibility layer (for example
Player.MyHelper = function ... end) changes that table for all other compatibility scripts (the real TSWMU API tables are not touched). - All time, memory and packet-sending limits of LuaAPI still apply to scripts run through this layer, see Limits configuration and Error handling and safety notes.