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.

Do not edit the file 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

  1. Copy the folder of the script you want to run into Data\LuaAPI\Includes\, for example Data\LuaAPI\Includes\MyOldScript\Main.lua.
  2. Open Data\LuaAPI\Main.lua, find the sample comment line (next to the module loading part) and add one line:
    LoadCompatScript("Includes\\MyOldScript\\Main.lua")
    The path is counted from Data\LuaAPI\; a full path also works. In a Lua string you must write two \\ characters.
  3. 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, then Data\LuaAPI\, then Data\LuaAPI\Includes\; the prefix Plugins\LuaAPI\ is dropped. The files Helpers.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 with BridgeFunctionAttach; 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: ... and LoadCompatScript returns false; 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 server once and returns nil; the script keeps running.

Important differences in behavior

TopicBehavior in the compatibility layer
MoneyPlayer.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.
TimersTime 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 eventsFunctions 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 timingNotification events still follow TSWMU timing (queued, run in the next loop). For example onPlayerLogin runs one loop late.
Character statsStats.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 scriptTSWMU eventNotes
onGameServerStartonGameServerStartA script loaded after the server is already running is called immediately on load.
onCharacterSelectEnteronCharacterSelect
onPlayerConnect, onPlayerLoginsame nameonPlayerLogin runs one loop late.
onPlayerDisconnectonPlayerLogoutCharacter data can still be read.
onLogOutAllPlayers, onDisconnectAllPlayersonServerShutdown(0), onDisconnectAllPlayersCalled when the server starts shutting down.
onOpenWarehouse, onCloseWarehouseonWarehouseOpen, onWarehouseClose
onTradeRequestSend, onTradeResponseReceive, onTradeAcceptonTradeRequest, onTradeAnswer, onTradeAcceptBlocking (non-zero = block).
onTradeCancelonTradeCancelNotification only, it cannot prevent the cancel.
onBloodCastleEnter, onDevilSquareEnter, onChaosCastleEnteronEventEnter (event 0 / 1 / 2)The level parameter is always 0.
onPlayerLevelUp, onPlayerMasterLevelUponPlayerLevelUp (level type 0 / 1)The majestic level is not forwarded.
onUseCommandonUseCommandBlocking. The command string always starts with / (a . is converted).
onNpcTalk, onCloseWindowsame nameonNpcTalk is blocking; onCloseWindow is notification only.
onItemUseonItemUseBlocking; oItem is a snapshot of the source slot.
onInventoryMoveItemonItemMoveRuns after the move.
onItemGet, onEventItemGet, onMuunItemGetonItemGet (inventory 0 / 1 / 2)
onInventoryInsertItem, onEventInventoryInsertItem, onMuunInventoryInsertItemsame name (new events)
onItemEquip, onItemUnEquip, onItemRepairsame name
onCharacterJoinMap, onTeleportsame name
onMapTeleportonGateEnterCannot be blocked.
onMoveMaponMoveMap (new event)
onMapMoveRequestonMapMoveRequestBlocking; oWarp is built from the event, the money / level fields are 0.
onTeleportMagicUseonTeleportMagic
onPlayerKill, onPlayerDie, onPlayerRespawnsame name
onMonsterDie, onMonsterKillonMonsterDieonMonsterKill only runs when the killer is a player.
onMonsterSpawnonMonsterSpawn (new event)The compatibility layer automatically tracks all monster classes when a script uses this function.
onMonsterRespawnonMonsterRespawnOnly monster classes that have had Monster.WatchRespawn.
onCheckUserTargetonCheckUserTargetBlocking; PvP only.
onUseNormalSkillonUseSkill (without coordinates)Blocking. The compatibility layer turns on tracking of all skills, so the event runs on every skill use (costs resources).
onUseDurationSkillonUseSkill (with coordinates)Runs only when the server sends coordinates and direction along with it.
onShopBuyItem, onShopSellItemonShopItemBought, onShopSellonShopSellItem is blocking.
onMossMerchantUsesame nameBlocking.
onCashShopItemBuy, onCashShopPackageBuyonCashShopBuyBlocking. The list / information carry only the package code and options.
onCashShopItemGift, onCashShopPackageGiftonCashShopGiftBlocking. The message is empty if the server does not supply one.
onCashShopItemUsesame nameBlocking.
onDSDBQueryReceive, onJSDBQueryReceiveonDBQueryResultCalled once per column per row; an empty result calls once with a nil row.
onTimerProcessSecond, Minute, Hour, DayChangesame 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.

GroupFunction in the old scriptHow it is done on TSWMU
Server / ObjectServer.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.DelMonsterMonster.Create at a random cell inside the area; Monster.Delete. The element is not set.
PlayerPlayer.GetObjByIndex, GetObjByNameReturn a proxy (nil if the slot is empty / the name is not online).
Player.SetMoney, SetRuudAdd (see the differences section).
Player.SendTradeOkButton, SendTradeCancel, TradeOkButton, TradeCancel, SendPKLevel, SetExp (EXP packet)The functions in Additional functions and events.
Coin / StatsCoin.Get, Check, Charge, AddCoin.GetByType, Check, Charge, Give
Stats.Get, Stats.Set, Stats.LevelUpRead base + extra stats; Stats.Set adds to the stat, recalculates and sends; Stats.LevelUp = Player.GiveExperience.
Inventory / ItemInventory.SendUpdate, SendDelete, SendList, Delete, RectCheckInventory.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.GetRandomLevelGranted 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 / SkillBuff.Add, Buff.Remove, Buff.CheckUsedThe parameter order of Buff.Add is changed; Buff.CheckUsed = Buff.Has.
Skill.UseNormal, Skill.UseDurationSkill.UseNormal (see the additional functions page); UseDuration uses the same function because the client has only one skill packet.
MovementMove.Gate, Move.ToMap, Move.Warp, Viewport.Create / DestroyPlayer.MoveGate; Player.MoveTo (players) or Object.Warp (monsters, same map); Object.Warp; Object.ViewportCreate / ViewportDestroy
DB / Message / LogDB.QueryDS, QueryJSDB.Query with its own tag; the result is delivered to onDSDBQueryReceive / onJSDBQueryReceive.
Message.Send, Log.Add, Log.AddCMessage.SendAll when the target is -1, otherwise Message.Send; Log.Add; Log.AddC with the color converted by color code.
TimersTimer.Create, CreateRepeating, RepeatNTimes, Remove, Exists, Start, Stop, GetRemainingImplemented 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 functionsLogAdd, gObjTeleport, GCServerMsgStringSend, FireCrackerOpen, CreateItem...Log.Add, Move.ToMap, Message.Send, Player.Fireworks; CreateItem grants into the inventory or drops on the ground.
ConstantsConstants.*, 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.

KindName
FunctionPlayer.DoReset, Player.SetShopSkin, NPC.SendDialog, Inventory.SetSlot, ItemBag.Add, Monster.IsGroupRegenLiveBossState, UI.SendWindowUse, Net.SendPacket, LoadEncryptedScript
EventonDisconnectAllPlayersWithReconnect, onPlayerReset, onEventInventoryMoveItem, onMuunInventoryMoveItem, onShopSellEventItem, onShieldEffectSend, onLuaWindowOpen, onLuaWindowUse, onLuaPacket
Other old functionsgUserFindDevilSquareKeyEyes, 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 to bit32 functions, for example bit32.band(a, b), bit32.lshift(a, n).
  • Minimum timer of 1 second (rounded up, see the differences section).
  • onShieldEffectSend of 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.
  • onUseNormalSkill turns 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.
The compatibility layer helps run existing scripts quickly, but running through a translation layer always costs extra resources. For scripts you will use long term, rewrite them with the native TSWMU API (see Overview).