Script errors do not break GameServer

Every call from GameServer into Lua goes through pcall (error catching):

  • A script reports an error: GameServer writes it to the log with a traceback, then continues running normally.
  • An API function called with wrong parameters usually does not raise a Lua error: the wrong parameters are ignored and the function returns a default value (0, false, an empty string, nil, depending on the function). A C++ error inside a function is caught and converted into a Lua error.
  • A blocking event that has an error or no function: treated as allowed, a script error does not block the player.
  • Functions attached with BridgeFunctionAttach each run in their own pcall: if module A fails, module B still runs. Each function logs only its first 5 errors.
  • On each load, each distinct error is logged only once, up to 200 distinct errors, so an error repeating every second does not fill the log.
  • A module that fails to load (LoadModule) only breaks itself.
  • Notification events are queued and called at the start of the next loop, so scripts are not inserted in the middle of the game's combat code.

No script can take over the system

After the System\ files have been loaded (the SystemLock() line at the end of Library.lua, and for Lua UI the end of UI.lua), the system locks itself. A faulty or badly written script cannot kill the other scripts:

The script doesResult
Redefines an event function, e.g. function onPlayerLogin(aIndex) ... end, function onLuaCommand(...), function Ui_onNpcTalk(...)The system function is not replaced. The new function is added and runs after the system function, in its own pcall. The log writes a notice line.
Overwrites / deletes an API function: Player.GetName = nil, Item = {}, string.format = nil, print = nil, GetObjectLevel = ..., BridgeFunctionAttach = ...Rejected, the old value is kept. The log writes once per name.
Adds a new function to an API table: function Player.MyHelper() ... endAllowed.
The script's own global variables / functions: MyConfig = {...}, function MyModule_OnLogin()Normal, can be reassigned freely.
A function has an errorOnly that function stops; the other functions of the same event still run.
A function runs too long (infinite loop) / uses too much memoryStopped after 2 seconds; the next function of the same event is timed again from the start. A function stopped 3 times in a row switches itself off until LuaAPI is reloaded (the log states the function name).
A command function forgets return / a DB function returns 1 for every resultIt cannot swallow the commands or DB results of other modules (see the page attaching modules).

Under heavy load (thousands of players at once), the following default numbers can be adjusted in LuaAPI.ini (Limits configuration):

  • Queued notification events are processed for at most 50 ms per loop; the rest moves to the next loop, so the server does not stall.
  • Functions that send packets to a player: at most 30 units / second / player (normal packet 1, Player.ReCalc / Player.SendLevels 3, Player.SendInfo 5, Inventory.SendList / Object.ViewportCreate 10). Server-wide notices (Message.SendAll, SendGlobal, BoxAll, Post, Map.Fireworks) at most 20 times / second. If exceeded the call is ignored and logged once: a client that receives hundreds of packets at once will crash.
  • Each player can call at most 5 Lua commands / second (LuaCommands.xml); command spam is ignored and the script is not called.
  • An event that no function listens to costs nothing (GameServer does not call into Lua).
  • DB.Query runs on its own DB thread and does not block the game loop.

Resource limits

The values below are defaults. All limits of LuaAPI and Lua UI can be adjusted in the file Data\LuaAPI\LuaAPI.ini, see Limits configuration (LuaAPI.ini).
Lua machineMaximum time per GameServer call into a scriptMaximum memory
LuaAPI2 seconds / per function (while loading scripts: 10 seconds)256 MB
UI Lua5 seconds / per function128 MB
Skill formulas100 ms per function call64 MB
  • An infinite loop or a script that runs over time is interrupted midway (checked every 100000 Lua instructions; for skills every 1000 instructions) and logged as script ran longer than 2000 ms (endless loop?) -> stopped.
  • The memory limit is checked at allocation time: a script that tries to allocate beyond the limit (LuaAPI 256 MB, UI Lua 128 MB, skill 64 MB) immediately gets the error not enough memory. Avoid stuffing data into unbounded global tables.
  • The character stat script (CalcCharacter.lua) is limited to 200 ms per call and 64 MB of memory; the item bag script (ItemBagScript.lua) is limited to 10 seconds for loading. An infinite loop is stopped and logged and does not hang the server.
  • Nested script calls (a script calls an API function, the API function triggers an event, the event calls a script...) are allowed up to 8 levels; deeper than that the event is dropped and logged as too many nested script calls, event skipped.
  • The notification event queue holds at most 20000; pending DB queries at most 5000. Beyond that they are dropped and logged.
  • The state of each Lua machine is per GameServer: several GameServers have separate Lua machines and do not share variables. To share data, store it through the DB.
  • All scripts run on the main thread of GameServer: heavy work slows the whole server. Use DB.Query (which runs on the DB thread) for reading the DB, and avoid large loops.

What is blocked / forbidden

  • A restricted run environment (sandbox) in every Lua machine of GameServer (LuaAPI, UI Lua, skill formulas, the ItemBag item bag script, the character stat script). Removed: the whole debug table, os.execute, os.remove, os.rename, os.tmpname, os.exit, io.popen, package.loadlib. The functions load, loadstring, loadfile, dofile accept only Lua source text and do not accept precompiled code (bytecode). Still usable: io.open, os.time, os.date, os.clock, string, table, math, coroutine.
  • The INI file writing functions of Config (for example Config.SaveString) accept only files with the .ini extension located in the Data folder.
  • DB.Query returns at most 10000 rows to Lua; extra rows are dropped and GameServer writes a warning to the log. Limit the number of rows in the query itself.
  • Dynamic libraries cannot be loaded (cpath is left empty); require only looks for .lua files in the folder of that Lua machine.
  • In restricted mode (many blocking events, see Events) and in onPlayerLogout: scripts may only read data and send notices; functions that write character data, teleport, create / delete items and monsters have no effect.
  • In UI Lua: data may only be written while handling a player's button press; some LuaAPI functions are not available (see UI Lua). Ui_DB.Execute outside button handling is ignored and returns false.
  • SQL statements built by string concatenation must go through DB.Escape; never put a string typed by a player directly into SQL.
  • Do not trust data sent up by the client (especially UI window messages): re-check it against server data.

What is lost when LuaAPI is reloaded

LostNotes
All script variables and tablesA completely new Lua machine. Data that must be kept has to be saved to the DB or a file.
The Timer.* timersCreate them again in onGameServerStart.
The list of registered events (Skill.Watch, Monster.WatchRespawn)Register them again when the script starts.
Temporary per-character data: blocked actions (Player.BlockAction), the table of extra stats, OptionBonus, ActionTick, the last place of deathNot saved to the DB. The stats of characters currently playing are recalculated; onPlayerLogin is called again for them so modules can grant things again.
DB.Query queries still waiting for resultsThe query still runs in the DB but Lua does not receive the result.
Monsters and NPCs created by modulesThe sample modules delete them when they receive onScriptUnload and create them again on onGameServerStart; EventMonsterTracker automatically deletes the monsters it tracks. Your own module must do the same to avoid duplicates.
Event state kept in memory (for example a RandomQuestSystem that is running)The event ends.

Data written to the DB (such as the tables of the sample modules) is not lost. Temporary per-character data is also cleared when the character exits.

Reading Lua error logs

  • LuaAPI errors have the prefix [LuaAPI], for example [LuaAPI] onPlayerLogin: ... (traceback). The first line tells you the name of the event function that failed, followed by the file and line number.
  • UI Lua errors have the prefix [LuaUi]; skill errors have [SkillLua]; item bag errors have [ ITEM BAG ]; web function errors have [WebAPI].
  • Errors from modules have the form [event name] function name: message; timer errors [Timer] name: message; module load errors [Main.lua] Failed to load module ....
  • The commands Log.Add(text) and Log.AddC(color, text) in a script write your own log lines for checking.

Recommendations when writing scripts

  1. Test on a test server first, and press Reload LuaAPI instead of restarting.
  2. Give global function names a module-name prefix so you do not overwrite another module's functions.
  3. Always check return values (nil, 0) before using them, especially the result of a DB query (it can be the number 0 instead of a table).
  4. Do not hold on to aIndex for long: the index can be reused by another player after they exit. Store the character ID with it (Player.GetCharacterID) and re-check when the result arrives.
  5. When using money / items: deduct first, grant after (as in the CustomItemExchange module), and write to the DB before granting the reward (as in CumulativeRecharge, RechargeGift).
  6. Keep SKILL_DEBUG = false and Logskill off on the main server.