Global Scope
The global scope is the main body of the script, i.e., everything that is outside of functions. Primarily, the global scope is used to specify directives, include modules, and declare global variables and functions. It serves as the first stage of script loading; the code within it executes once after the script is loaded (and scripts are loaded almost immediately after the game starts) and cannot be paused. The main work with the script is performed in the main thread.
Example: Loading the VKEYS library, assigning my name to the variable myName, and declaring the main function.
local vkeys = require 'vkeys'
local myName = "Alexander"
function main()
-- In this example, there are no actions with main, so it could be omitted. The script executes the global scope and terminates.
end
main - The Main Thread of Any MoonLoader Script
Unlike the global scope, main is called after the game has loaded, so all interactions with the game are performed within the thread's body. main is called once, after which the script terminates and unloads if there are no active threads and registered events. To keep the script running, the thread must remain active. There are two ways to achieve this: an infinite delay or an infinite loop. Both methods are incompatible with each other and are used under different conditions.
Example #1: main prints text to moonloader.log and terminates the script.
function main()
print("Hello World!") -- Prints text to the log
print("main dead :(")
end
Example #2: main prints text to moonloader.log but does not terminate the script.
function main()
print("Hello World!")
wait(-1) -- wait sets the thread to delay for the specified milliseconds (ms), -1 means indefinite wait.
-- In this example, the main thread will not terminate, and the script will continue running.
end
Example #3: main prints "I'm alive" to the log every second.
function main()
print("Hello World!") -- Executes once at startup
while true do -- Declare an infinite loop
wait(1000) -- Wait for one second, 1000 ms = 1 s
print("I'm alive!") -- Print text to the log
end -- End of the loop body
-- In this example, the main thread will not terminate due to the infinite loop.
end
Delays and Threads
A delay in a script allows pausing code execution for a specified number of milliseconds or for one frame. In ML, the wait(int time) function is used for delays, where the time argument accepts the following values:
-1 - sets an indefinite wait; usage is only allowed in main
0 - delay for one frame
- Any other value specifies a delay in milliseconds
Example: A running script will wait indefinitely.
function main()
wait(-1)
end
Using delays is not allowed in callback functions. To create a delay in such functions, create a thread:
function callback()
lua_thread.create(function ()
doFade(1000, true)
wait(3000) -- Fade the screen for 3 seconds
doFade(1000, false)
end)
end
Threads are coroutines that can be created during script execution for parallel task execution. In MoonLoader, threads are used to offload certain actions from the main thread and to create delays in code where it's not possible to implement them using standard methods.
To start a thread, use the functions lua_thread.create and lua_thread.create_suspended.
Example: Creating two threads for parallel text output to the log.
-- Create a function that prints text with delays
function printText()
print("printText: One")
wait(1000)
print("printText: Two")
wait(1000)
print("printText: Bye!")
end
function secondPrintText()
print("secondPrintText: One")
wait(500)
print("secondPrintText: Two")
wait(1500)
print("secondPrintText: Bye!")
end
-- Create both threads simultaneously
lua_thread.create(printText)
lua_thread.create(secondPrintText)
After running this code, you will see that the messages are not printed in the order the functions were called but based on the completion of the delays.
Like with main, a thread will terminate and be destroyed if it is not kept active. Threads are widely used in practice, but in small scripts, they are often unnecessary. Know about threads, but do not use them without necessity. Real-world use cases for threads include separating script logic from graphics rendering or using delays in console and chat commands.
For more information about threads, visit the wiki: lua - luathread | BlastHack — DEV_WIKI
Directives
Scripts for MoonLoader can contain information about themselves and have certain execution properties—both are set using directives. Directives are ordinary functions designed to specify information about the script and alter its behavior. They are typically placed at the very beginning of the script.
All parameters set by directives can be accessed from any script by referring to the corresponding fields of the LuaScript class.
Example:
script_name("A complete guide to MoonLoader") -- Sets the script name, displayed, for example, in the log
script_authors("DonHomka", "FYP") -- Sets multiple script authors. To specify a single author, use script_author
script_version("0.1.0-beta") -- Specifies the script version
script_description[[
- Example of using directives
- Logging information
- Using multi-line descriptions
]]
-- Now let's print this information. script.this is the current script object
print(script.this.name .. ' v' .. script.this.version) -- Script name and version
print('Authors: ' .. table.concat(script.this.authors, ', ')) -- List of authors stored in a table, even if only one author is specified
print(script.this.description) -- Description
This example does not cover all directives; refer to the corresponding wiki page for a complete list.
Events and Callbacks
Events, or more precisely their handlers, in MoonLoader are functions that are automatically called in scripts when a certain action occurs in the game that requires processing. Event handlers can have input and return parameters: input parameters pass information to the script, and return parameters allow influencing further processing after the event occurs.
You can register an event handler in two ways: either by simply adding a function with the corresponding name to the script or by using the addEventHandler function. Note that the first method allows the handler to be registered only once.
Scripts with registered events do not terminate on their own.
Example: onScriptTerminate is called when any script terminates.
function main()
print("hello world")
end
function onScriptTerminate(script, quitGame)
-- script is a pointer to the LuaScripts class. It has all the previously described script properties, i.e., name, authors, etc.
-- quitGame is a boolean value that returns true if the script was terminated as a result of the game ending.
if script == thisScript() then -- Condition to specify that the current script is terminating
print("bye world")
end
end
Inside event handlers, you cannot use delays because the event call requires an immediate return from the handler function. To work around this limitation, use threads.
For a list of all events and their purposes, refer to the wiki: moonloader - events | BlastHack — DEV_WIKI
Callbacks act as reactions to actions and are conceptually very similar to events, but there are two differences:
- The callback is always explicitly registered, often by calling a function and passing the callback function as an argument.
- It is always associated with a specific entity (command, identifier, etc.), meaning it will only be called if the triggered event pertains to the associated entity (for example, a command callback will be triggered only when that specific command is entered, not every time an event occurs, as would be the case with a general event).
An example of a function with a callback is downloadUrlToFile, which accepts a callback function as its last argument.
In callbacks, as in events, you cannot use delays.
Example:
local fpath = os.getenv('TEMP') .. '\\moonloader-version.json'
downloadUrlToFile('https://blast.hk/moonloader/data/version-info.json', fpath, downloadCallback)
function downloadCallback(id, status, p1, p2) -- Called on each update of the file download status
print(id, status, p1, p2)
end
Using Libraries
Libraries, or modules, extend the standard set of capabilities with new features and allow the use of ready-made tools for developers in scripts. Modules are divided into standard and third-party. Standard modules are included in the MoonLoader distribution and do not require separate installation.
All modules are located in the moonloader/lib/ directory and are installed there as well. To include libraries, use the require function, which takes the file name as an argument. Modules are usually included at the beginning of the script but can be included anywhere. Each module is loaded separately for each script.
Example: Include the "vkeys" module, which allows working with virtual keys.
local vkeys = require 'vkeys'
-- Now the variable vkeys has all the properties obtained from the module. For example, you can get the IDs and names of keys
print(vkeys.VK_RSHIFT, vkeys.id_to_name(vkeys.VK_RSHIFT)) -- Print the ID and name of the right Shift key to the log.
Working with modules is not limited to the standard set; often, you have to deal with third-party modules—these are not bundled with MoonLoader and require manual installation. Examples of such modules include Dear ImGui and SAMP.Lua.
You can create your own module and use it in your scripts. This makes it easier to support them, keeps scripts cleaner and more compact, and significantly reduces repetitive code.
In addition to this capability, MoonLoader has an import system that allows using a running script as a shared module—more on this and creating modules will be discussed later.
Strong Recommendation: Never publish your work along with standard libraries or with modifications to third-party libraries—this can cause problems for users.
Recommendations
Despite the abundance of information in this topic, it's impossible to know everything, so frequently refer to the Wiki and don't forget about the "Questions about Lua scripting" thread, where you can get help when encountering difficulties.
For more information specifically about Lua, it's better to search using search engines; the language is quite simple, and if this topic didn't help you, consider looking for more in-depth tutorials.
Basic Guidelines for Improving Code Quality
To ensure your code is clean and understandable, adhere to the following rules:
- Add script information using directives.
- Maintain a consistent coding style.
- Use proper indentation (tabs).
- Logically separate code blocks: use empty lines between functions and variable blocks, spaces between code blocks that perform logically complete actions, etc.
- Name variables and functions with clear names.
- Comment on non-obvious parts of the code.
Following these simple rules will significantly improve your code quality, but if you need more, here's an excellent code style guide (in English).
Modern Solutions
Since the release of ML, a lot of time has passed, and many things have changed. For example, instead of predefined variables playerPed and playerHandle, you should use PLAYER_PED and PLAYER_HANDLE respectively.
In addition to standard rendering, you can use the Dear ImGui framework to create complex menus. For convenient handling of SA:MP network traffic, there is the SAMP.Lua library. The SA Memory library allows direct interaction with game structures. And MoonAdditions adds many interesting functions.
vkeys is a standard module that stores all IDs and names of virtual keys. Initially, this module was not part of MoonLoader, and instead, all constants were loaded globally from the moonloader module. Over time, it was discovered that this was a poor decision, so key codes were moved to a separate module with a slightly different implementation. However, constants had to be left in the old module for compatibility with old scripts, and their use from there is now considered deprecated. The vkeys library is provided here as an example; besides it, there were other innovations that made old solutions obsolete.
Therefore, if you are actively developing, always pay attention to the changelog in updates and use the latest tools.
Simplifying the Script Installation Process
"Just throw these files into the CORE folder in the SOURCE folder, the one with libs where the IT folder contains SCORE" – Brrr, to prevent such confusion and to avoid making your interlocutor confused, strive to simplify installation to the maximum – make it possible to just copy all the mod components into one folder. In other words, create a single archive so that an inexperienced user can easily install it, or provide instructions if the installation process is more complex than standard. The simpler the installation, the better it is for both you and the user.
Additional Information
Compiling Scripts
In many other programming languages, compiling is necessary to run the application on the target machine, but in Lua, compilation is not required—the scripts are loaded from the source code without additional manipulation. However, Lua script compilation is possible and is mostly used to hide the source code from prying eyes. This is commonly done for sellable scripts where protecting the script is of paramount importance. Do not abuse this capability by locking every your script.
To compile Lua scripts for MoonLoader v.026 and above, download the LuaJIT v2.1.0-beta3 interpreter, extract the archive to any location, and drag the Lua file onto compile.bat. A .luac file will be created nearby—it is the compiled script. To compile scripts for older versions of MoonLoader, you will need LuaJIT 2.0.4.
Advanced Programming
You are now familiar with the basic principles of development and can perform most tasks with this knowledge. However, some tasks require applying special techniques. Let's examine a few of them.
Creating Modules
Modules are divided into two types: Lua and DLL. Lua modules are written, as you might have guessed, in Lua and result in regular Lua scripts with some differences.
Let's look at an example of a simple module, called example:
-- In a module, all variables must be local, including functions
-- Global variables are assigned only in special cases
local mod = {} -- Create an empty table
mod._VERSION = '1.0.0' -- Add the module version to the table (optional)
local function typeAssert(value, t) -- Local function, not accessible externally
assert(type(value) == t)
end
function mod.showTextFormatted(msg, duration, ...) -- This function is added to the module table
typeAssert(msg, 'string')
typeAssert(duration, 'number')
printStringNow(string.format(msg, ...), duration)
end
return mod -- Return the table
Using the Module in a Script:
local example = require 'example' -- Load it
function main()
example.showTextFormatted('My module\'s version is %s.', example._VERSION)
end
What Happens When You Call require?
First, all the module's code is executed up to the return mod line. The returned table is then passed back to the script as a result of the require call, so the variable example now holds the table with the function and the module version. Subsequent require calls to load the same module will not execute the code again; instead, the value obtained during the first call will be used.
As you may have noticed, the structure of a module differs somewhat from a regular script. Modules have two additional distinctive features:
- Events cannot be registered in the usual way—they won't work. To register an event in a module, you must use the
addEventHandler function.
- The
main thread will also not work; in a module, you need to create the thread yourself (using lua_thread.create).
This example demonstrated creating a typical module, and in most cases, nothing more is needed. However, keep in mind that this does not limit the possibilities—you can perform any operations within the module.
Another Example: Demonstrating how to implement events using an internal thread.
Spoiler: Code
DLL Modules
The process of developing a DLL module is fundamentally different from Lua. Such modules are written in other programming languages, specifically C and C++, and their development requires additional knowledge. This topic will not be covered here, as it is extensive and deserves a separate article. If you already program in C++, you can read this guide.
Import and Export
Lua modules are loaded separately for each script and therefore do not allow sharing common data among them. However, sometimes you cannot do without this capability—in such cases, the export system comes to the rescue. Its working principle is as follows: a script acting as a module opens access to certain data for other scripts by assigning a global variable EXPORTS (by default, this variable is an empty table but can be of any type). Other scripts can then access this data using the import function.
For example, to create a script that displays a text notification at the bottom of the screen, name it status_notification.lua:
script_name('status notification')
local fflags = require('moonloader').font_flag
local font = renderCreateFont('Arial', 13, fflags.SHADOW + fflags.BOLD)
local notification = nil
function split(str, delim, plain)
local lines, pos, plain = {}, 1, not (plain == false) --[[ delimiter is plain text by default ]]
repeat
local npos, epos = string.find(str, delim, pos, plain)
table.insert(lines, string.sub(str, pos, npos and npos - 1))
pos = epos and epos + 1
until not pos
return lines
end
function EXPORTS.notify(msg, color) -- Function with shared access
if not msg then return end
local displayDuration = math.max(#msg * 0.065, 1.5) -- Duration in seconds
notification = {
color = bit.band(color or 0xEEEEEE, 0xFFFFFF),
lines = split(msg, '\n'),
duration = displayDuration,
tick = localClock()
}
end
function main()
while true do
wait(0)
if isPlayerPlaying(PLAYER_HANDLE) and not isGamePaused() then
if notification then
if localClock() - notification.tick <= notification.duration then
local sw, sh = getScreenResolution()
local fontH, y = renderGetFontDrawHeight(font), sh - 50
local alpha = 255 * math.min(1, notification.duration - (localClock() - notification.tick)) -- Fade out in the last second
local color = bit.bor(notification.color, bit.lshift(alpha, 24))
for k = #notification.lines, 1, -1 do
local text = notification.lines[k]
if #text > 0 then
local dlen = renderGetFontDrawTextLength(font, text)
renderFontDrawText(font, text, sw / 2 - dlen / 2, y, color)
end
y = y - fontH
end
else
notification = nil
end
end
end
end
end
Usage in a Script:
local notification = import 'status_notification'
function main()
while true do
wait(0)
if wasKeyPressed(0x31) then
notification.notify(script.this.name .. ' says hello!')
end
end
end
Why All This for a Simple Task? Because if the notification output is implemented in a library or simply as a function, and if several scripts display notifications simultaneously, the notification texts will overlap and become illegible. Therefore, you need to use a shared notification system.
How It Works:
As seen, the exporting script looks much like a regular script because it is essentially an ordinary script. It can be placed in the moonloader folder, where it will be loaded automatically, or located in another directory—in this case, it will be loaded when import is called. The process of importing a script involves fully copying the contents of the EXPORTS variable into the importing script, but this copying occurs only during the first call. Subsequent calls will return the saved value, so updating data this way is impossible. To update data and in most other cases, you need to use functions. Imported functions have a distinctive feature: instead of copying, an interface is created that allows the function to be called as if it were invoked in the exporting script, returning results to the calling script. Thus, calling notification.notify in this example will invoke EXPORTS.notify in the status_notification.lua script, and all changes made in this function will be executed on behalf of the exporting script. As a result, the notification status will be updated, the text will be overwritten, and the notification will be displayed correctly on the screen.
The export/import system allows not only calling functions from another script but also passing functions as arguments, thereby enabling the implementation of callbacks and events.
Conclusion
The knowledge acquired should be sufficient to start developing Lua scripts independently. All aspects of development under MoonLoader have been covered here, except for the principles of game modding itself and the use of FFI. This is because these are too extensive topics that should be addressed separately and in more detail.
There is plenty of information about GTA San Andreas modding on the internet, but it does not directly relate to MoonLoader, is highly fragmented, and mainly in English; therefore, links are not provided here. Information about LuaJIT FFI in Russian is practically nonexistent, but there is the official guide in English, which covers FFI almost entirely, assuming an understanding of process memory architecture and familiarity with the C programming language. These topics remain unexplored in this guide, but when articles on them for MoonLoader become available, links to them will be added.
Periodically, changes and additions will be introduced to the guide with new MoonLoader versions. However, timely updates may not always be possible, so remember to check the changelog to stay informed about all updates in MoonLoader.
Don't forget to return to this guide and use the wiki when in doubt, and remember that you can always seek help on the forum.
Current MoonLoader Version at the Time of the Last Article Update: .026