### doWeaponStuffAtStartOf2pGame() Source: https://wiki.blast.hk/moonloader/scripting-api Performs weapon-related setup at the start of a two-player game. ```APIDOC ## doWeaponStuffAtStartOf2pGame() ### Description Performs weapon-related setup at the start of a two-player game. ### Parameters None. ### Return Value None. ``` -------------------------------- ### Lua example using getCharHeightAboveGround Source: https://wiki.blast.hk/moonloader/lua/getCharHeightAboveGround Example usage in a MoonLoader Lua script. Waits for SAMP to be available, then continuously gets the height of the player ped and prints it on screen. ```lua function main() while not isSampAvailable() do wait(100) end while true do wait(0) local height = getCharHeightAboveGround(PLAYER_PED) printStringNow(height) end end ``` -------------------------------- ### Example usage of startCharFire Source: https://wiki.blast.hk/moonloader/lua/startCharFire Example usage of startCharFire. Registers a chat command 'fire' that makes the player character burn. Requires SAMP to be available. ```lua function main() while not isSampAvailable() do wait(100) end sampRegisterChatCommand("fire", function() startCharFire(playerPed) end) wait(-1) end ``` -------------------------------- ### createPlayer usage example Source: https://wiki.blast.hk/moonloader/lua/createPlayer Example call to createPlayer with a model ID of 1 and coordinates. Returns a player handle. ```lua playerHandle = createPlayer(1, -2540.6995, -21.8837, -2.1360) ``` -------------------------------- ### Example usage of testCheat Source: https://wiki.blast.hk/moonloader/lua/testCheat A script example demonstrating how to use testCheat within a main loop to detect the input of the string 'TEST'. ```lua script_name("Example script") function main() if not isSampLoaded() or not isSampfuncsLoaded() then return end while not isSampAvailable() do wait(100) end while true do wait(0) if testCheat("TEST") then print("Чит-код активирован") end end end ``` -------------------------------- ### onQuitGame usage example Source: https://wiki.blast.hk/moonloader/lua/onQuitGame Example implementation of the onQuitGame event. It prints a message, calls saveSettings(), and prints a completion message before the game exits. ```lua -- ... function onQuitGame() print("Saving settings...") saveSettings() print("Done.") end -- ... ``` -------------------------------- ### getCarSpeed usage example Source: https://wiki.blast.hk/moonloader/lua/getCarSpeed An example demonstrating how to retrieve the speed of the vehicle the player is currently in and display it on the screen. ```lua function main() while not isSampAvailable() do wait(100) end while true do wait(0) car = storeCarCharIsInNoSave(PLAYER_PED) if isCharInCar(PLAYER_PED,car) then speed = getCarSpeed(car) local carSpeed = math.ceil(speed) printStyledString(carSpeed, 500, 7) end end end ``` -------------------------------- ### Usage example: setPlay3dAudioStreamAtCoordinates Source: https://wiki.blast.hk/moonloader/lua/setPlay3dAudioStreamAtCoordinates Example usage that loads a 3D audio stream, gets the player character's coordinates, sets the stream position, and plays it. ```lua local as_action = require('moonloader').audiostream_state local as = load3dAudioStream('moonloader/resource/audio/sound.mp3') local x, y, z = getCharCoordinates(PLAYER_PED) setPlay3dAudioStreamAtCoordinates(as, x, y, z) setAudioStreamState(audio, as_action.PLAY) ``` -------------------------------- ### startCutscene Source: https://wiki.blast.hk/moonloader/scripting-api Starts a cutscene. ```APIDOC ## startCutscene ### Description Starts a cutscene. ### Method Function ### Signature void startCutscene() ``` -------------------------------- ### setCarProofs usage example Source: https://wiki.blast.hk/moonloader/lua/setCarProofs Example usage: stores the car the player is in and sets all immunity flags to true. ```lua car = storeCarCharIsInNoSave(playerPed) setCarProofs(car, true, true, true, true, true) ``` -------------------------------- ### Example usage: display current game time Source: https://wiki.blast.hk/moonloader/lua/useRenderCommands Example loop that enables render commands and displays the current game time using setGxtEntry and displayText. Requires the 'lib.game.globals' module. ```lua local glob = require "lib.game.globals" function main() while true do wait(0) useRenderCommands(true) setGxtEntry("IGTIME", string.format("Time: %02d:%02d", getGameGlobal(glob.Time_Hours), getGameGlobal(glob.Time_Mins))) displayText(10, 10, "IGTIME") end end ``` -------------------------------- ### setAudioStreamState usage example Source: https://wiki.blast.hk/moonloader/lua/setAudioStreamState Example of using setAudioStreamState with the audiostream_state constant PLAY from the moonloader module. ```lua local as_action = require('moonloader').audiostream_state setAudioStreamState(audio, as_action.PLAY) ``` -------------------------------- ### script_version usage example Source: https://wiki.blast.hk/moonloader/lua/script_version Example of calling script_version with a version string, followed by a main function. The version is set to "0.2.3-beta". ```lua script_version("0.2.3-beta") function main() -- ... end ``` -------------------------------- ### Example: create font and draw text Source: https://wiki.blast.hk/moonloader/lua/renderCreateFont Example usage of renderCreateFont. It requires the 'moonloader' module for font_flag. Creates a font with BOLD and SHADOW flags, then in a main loop draws text with color codes. ```lua local font_flag = require('moonloader').font_flag local my_font = renderCreateFont('Verdana', 12, font_flag.BOLD + font_flag.SHADOW) function main() while true do wait(0) renderFontDrawText(my_font, 'Colors:\n{FF0000}Red\n{00FF00}Green\n{0000FF}Blue\n{80FFFFFF}Transparent white', 10, 400, 0xFFFFFFFF) end end ``` -------------------------------- ### Implement main function with infinite loop in Lua Source: https://wiki.blast.hk/moonloader/lua/main Example implementation of the main function for a MoonLoader script. Starts a while-true loop that uses wait(0) each iteration to avoid freezing the game, checks player status and key 0x31 (digit 1), increments and prints a counter, and calls doCoolStuff(). ```lua function main() -- загрузим что-нибудь перед тем, как запустить бесконечный цикл loadStuff() key1_timesPressed = 0 -- бесконечный цикл - в данном примере именно в нём реализована основная часть скрипта while true do -- в нём обязательно должна присутствовать хотя-бы нулевая задержка, иначе игра попросту зависнет -- объясняется это тем, что весь процесс игры выполняется последовательно, в том числе и скрипты MoonLoader-а -- и поэтому периодически игре нужно давать возможность обработаться, делая паузу в каждом бесконечном цикле любого скрипта -- нулевая задержка приостановит выполнение скрипта ровно на один кадр (задержка в main не оказывает влияния на выполнение остальных событий) wait(0) if isPlayerPlaying(playerHandle) then if isKeyDown(0x31) then key1_timesPressed = key1_timesPressed + 1 print("Key 1 pressed " .. key1_timesPressed .. " times.") wait(500) end doCoolStuff() end end end ``` -------------------------------- ### Example usage of setTaxiLights Source: https://wiki.blast.hk/moonloader/lua/setTaxiLights Example usage in a main loop. It checks if the player is in a taxi and turns on the taxi lights using the vehicle handle from storeCarCharIsInNoSave. ```lua function main() while true do wait(0) if isCharInTaxi(PLAYER_PED) then setTaxiLights(storeCarCharIsInNoSave(PLAYER_PED), true) end end end ``` -------------------------------- ### Example usage of getFreeGxtKey Source: https://wiki.blast.hk/moonloader/lua/getFreeGxtKey Example usage of getFreeGxtKey. It generates two unique keys and uses them with setGxtEntry inside the main function. ```lua gxt1 = getFreeGxtKey() gxt2 = getFreeGxtKey() function main() -- ... setGxtEntry(gxt1, "GXT #1 key is " .. gxt1) setGxtEntry(gxt1, "GXT #2 key is " .. gxt2) -- ... end ``` -------------------------------- ### taskDie usage example Source: https://wiki.blast.hk/moonloader/lua/taskDie Example usage of taskDie with the PLAYER_PED handle. ```lua taskDie(PLAYER_PED) ``` -------------------------------- ### printText usage example Source: https://wiki.blast.hk/moonloader/lua/printText Example call that displays the GXT string "IE23" for 3000 milliseconds with flag 1. ```lua printText("IE23", 3000, 1) ``` -------------------------------- ### sampGetCurrentServerAddress usage example Source: https://wiki.blast.hk/moonloader/lua/sampGetCurrentServerAddress Example usage of sampGetCurrentServerAddress to retrieve the server address and display it in chat. ```lua ip, port = sampGetCurrentServerAddress() sampAddChatMessage("Адрес сервера: "..ip..":"..port.."!", -1) ``` -------------------------------- ### Example usage of sampGetDialogText() Source: https://wiki.blast.hk/moonloader/lua/sampGetDialogText Example script that prints the dialog text when the key with virtual code 49 (key '1') is pressed. It waits for SA:MP and SAMPFUNCS to load before running. ```lua script_name("Example script") function main() if not isSampLoaded() or not isSampfuncsLoaded() then return end while not isSampAvailable() do wait(100) end while true do wait(0) if isKeyDown(49) then while isKeyDown(49) do wait(80) end print(sampGetDialogText()) end end end ``` -------------------------------- ### Example usage of addOneOffSound Source: https://wiki.blast.hk/moonloader/lua/addOneOffSound Example usage of addOneOffSound in a MoonLoader script. It waits for the player to be playing, then plays sound ID 1076 at coordinates (0.0, 0.0, 0.0). ```lua script_name("Sound Example") function main() while not isPlayerPlaying(playerHandle) do wait(100) end addOneOffSound(0.0, 0.0, 0.0, 1076) wait(-1) end ``` -------------------------------- ### printTextNow usage example Source: https://wiki.blast.hk/moonloader/lua/printTextNow Example call to printTextNow using GXT key "IE23", a duration of 3000 milliseconds, and flag 1. ```lua printTextNow("IE23", 3000, 1) ``` -------------------------------- ### 0434 startCredits Source: https://wiki.blast.hk/moonloader/opcodes Starts the credits. ```APIDOC ## startCredits() ### Description Starts the credits. ``` -------------------------------- ### renderColor usage example Source: https://wiki.blast.hk/moonloader/lua/renderColor Example usage: sets red color, adds a vertex, sets blue color, adds another vertex. The color is specified in ARGB format. ```lua renderColor(0xFFFF0000) renderVertex(10, 100) renderColor(0xFF0000FF) renderVertex(200, 100) ``` -------------------------------- ### Example usage of startCarFire Source: https://wiki.blast.hk/moonloader/lua/startCarFire Example usage of startCarFire. Registers a chat command 'fire' that checks if the player is in a car and then ignites it using the car handle obtained from storeCarCharIsInNoSave. ```lua function main() while not isSampAvailable() do wait(100) end sampRegisterChatCommand("fire", function() if isCharInAnyCar(playerPed) then startCarFire(storeCarCharIsInNoSave(playerPed)) end end) wait(-1) end ``` -------------------------------- ### setCameraZoom usage example Source: https://wiki.blast.hk/moonloader/lua/setCameraZoom Example of using setCameraZoom inside a main function. It waits until SAMP is available, then calls setCameraZoom(2) to zoom the camera out. ```lua function main() while not isSampAvailable() do wait(0) end setCameraZoom(2) -- отдалит камеру end ``` -------------------------------- ### getCharModel usage example Source: https://wiki.blast.hk/moonloader/lua/getCharModel Example usage of getCharModel with PLAYER_PED to get the player's skin ID and print it. ```lua id = getCharModel(PLAYER_PED) print("My skin is "..id) ``` -------------------------------- ### Example usage of inicfg.load and inicfg.save Source: https://wiki.blast.hk/moonloader/lua/inicfg Complete example (example.lua) showing how to load a config with defaults, load another config without defaults (returns nil if missing), modify values, and save both configs. The first load uses the default path ./moonloader/config/example.lua.ini; the second uses the explicit file 'example_another_config'. Saving with inicfg.save returns true on success. ```lua local inicfg = require 'inicfg' -- производить загрузку кофигов можно и вне 'main' local mainIni = inicfg.load({ settings = { title = "text", text_color = "0xAABBCC" }, location = { width = 100, height = 200, pos_x = 20, pos_y = 50 } }) -- загрузим основной конфиг. путь к файлу не указан, а значит будет загружен файл по пути ./moonloader/config/example.lua.ini function main() -- таблица со значениями по умолчаниями не указана, поэтому если файл не удастся прочитать, будет возвращён nil local anotherIni = inicfg.load(nil, "example_another_config") -- если файл был успешно загружен if anotherIni ~= nil then -- выводим прочитанные значения print("Old value 1 = " .. anotherIni.main.value1) print("Old value 2 = " .. anotherIni.main.value2) -- просто сгенерируем 2 случайных значения local newV1, newV2 = math.random(100, 1000), math.random(100, 1000) -- теперь создадим таблицу с новыми значениями local newData = { main = { value1 = newV1, value2 = newV2, -- и добавим к ним сумму этих двух значений sum = newV1 + newV2 } } -- можно сохранять if inicfg.save(newData, "example_another_config") then print("Success.") end end -- выведем основной конфиг print(mainIni.settings.title .. ", color = " .. mainIni.settings.text_color) print("Position: ", mainIni.location.pos_x, mainIni.location.pos_y, "Size: ", mainIni.location.width, mainIni.location.height) -- отредактируем и сохраним его mainIni.settings.title = "Hello" mainIni.location.pos_x = 100 mainIni.location.pos_y = 75 inicfg.save(mainIni) end ``` -------------------------------- ### Example usage of sampSendChat Source: https://wiki.blast.hk/moonloader/lua/sampSendChat Example usage: sends a formatted chat message when key 0x31 (1) is pressed. Checks that SA:MP and SAMPFUNCS are loaded and available before running. ```lua function main() if not isSampLoaded() or not isSampfuncsLoaded() then return end while not isSampAvailable() wait(100) end while true do wait(0) if isKeyDown(0x31) then sampSendChat(string.format("Hello! My name is %s.", sampGetPlayerNickname(select(2, sampGetPlayerIdByCharHandle(playerPed))))) wait(500) end end end ``` -------------------------------- ### Example usage of script_moonloader Source: https://wiki.blast.hk/moonloader/lua/script_moonloader Example usage of script_moonloader. Sets the minimum required MoonLoader version to 16. If the version does not match, an error message is displayed but the script continues to run. ```lua script_author("Example") script_moonloader(16) function main() -- ... end ``` -------------------------------- ### setUpSkipForVehicleFinishedByScript(float posX, float posY, float posZ, float angle, Vehicle car) Source: https://wiki.blast.hk/moonloader/scripting-api Sets up a skip for a vehicle finished by script. ```APIDOC ## setUpSkipForVehicleFinishedByScript(float posX, float posY, float posZ, float angle, Vehicle car) ### Description Sets up a skip for a vehicle finished by script. ### Parameters - **posX** (float) - Required - X coordinate. - **posY** (float) - Required - Y coordinate. - **posZ** (float) - Required - Z coordinate. - **angle** (float) - Required - Angle. - **car** (Vehicle) - Required - The vehicle. ### Return Value None. ``` -------------------------------- ### onStartNewGame(int mpackNumber) Source: https://wiki.blast.hk/moonloader/lua/onStartNewGame Событие onStartNewGame вызывается при старте новой игры в одиночном режиме. Принимает номер пакета миссий. ```APIDOC ## onStartNewGame(int mpackNumber) ### Description Событие срабатывает при старте новой игры, предназначено только для одиночной игры. Параметр `mpackNumber` - это номер пакета миссий. Система пакетов миссий не используется в оригинальной игре, но используется различными модами (например, DYOM). В оригинальной линии игры это значение равно нулю. ### Parameters - **mpackNumber** (int) - Required - Номер пакета миссий. ### See Also - onLoadGame - onSaveGame ``` -------------------------------- ### Example usage of setCharAnimSpeed Source: https://wiki.blast.hk/moonloader/lua/setCharAnimSpeed Example usage that sets the animation speed of the player character to 2 for the 'RUN_CIVI' animation in a loop. It waits for SAMP to be available before starting the loop. ```lua function main() while not isSampAvailable() do wait(100) end while true do wait(0) setCharAnimSpeed(PLAYER_PED, 'RUN_CIVI', 2) end end ``` -------------------------------- ### Example usage of removeCharElegantly Source: https://wiki.blast.hk/moonloader/lua/removeCharElegantly Example usage of removeCharElegantly. Registers a chat command 'removeplayer' that takes a player ID, gets the character handle, and calls removeCharElegantly if the handle is valid. ```lua function main() if not isSampLoaded() then return end while not isSampAvailable() do wait(100) end sampRegisterChatCommand('removeplayer', cmd) wait(-1) end function cmd(arg) local id = tonumber(arg) if not id or not sampIsPlayerConnected(id) then return end local result, ped = sampGetCharHandleBySampPlayerId(id) if result then removeCharElegantly(ped) end end ``` -------------------------------- ### Example usage of getCharActiveInterior in Lua Source: https://wiki.blast.hk/moonloader/lua/getCharActiveInterior Example usage of getCharActiveInterior in a MoonLoader Lua script. It registers a chat command 'test' that gets the interior of the player ped and sends it as a chat message. ```lua function main() while not isSampAvailable() do wait(100) end sampRegisterChatCommand("test",function() interior = getCharActiveInterior(PLAYER_PED) sampAddChatMessage(interior,-1) end) wait(-1) end ``` -------------------------------- ### setUpConversationNodeWithScriptedSpeech(GxtString questionGXT, GxtString answerYesGXT, GxtString answerNoGXT, int questionWAV, int answerYesWAV, int answerNoWAV) Source: https://wiki.blast.hk/moonloader/scripting-api Sets up a conversation node with scripted speech for question and answers. ```APIDOC ## setUpConversationNodeWithScriptedSpeech(GxtString questionGXT, GxtString answerYesGXT, GxtString answerNoGXT, int questionWAV, int answerYesWAV, int answerNoWAV) ### Description Sets up a conversation node with scripted speech for question and answers. ### Parameters - **questionGXT** (GxtString) - Required - GXT string for the question. - **answerYesGXT** (GxtString) - Required - GXT string for the yes answer. - **answerNoGXT** (GxtString) - Required - GXT string for the no answer. - **questionWAV** (int) - Required - WAV file ID for the question. - **answerYesWAV** (int) - Required - WAV file ID for the yes answer. - **answerNoWAV** (int) - Required - WAV file ID for the no answer. ### Return Value None. ``` -------------------------------- ### Example usage of getCarModel Source: https://wiki.blast.hk/moonloader/lua/getCarModel Example usage of getCarModel. It waits for SAMP, then when ALT+5 is pressed and the player is in a car, it gets the car handle, retrieves the model ID, and prints it to the Sampfuncs console. ```lua require "lib.moonloader" function main() while not isSampAvailable() do wait(100) end while true do wait(0) if isKeyDown(VK_MENU) and isKeyJustPressed(VK_5) then -- Если нажать ALT + 5, то.. if isCharInAnyCar(PLAYER_PED) then -- Проверка на транспорт local carhandle = storeCarCharIsInNoSave(PLAYER_PED) -- Получения handle транспорта local idcar = getCarModel(carhandle) -- Получение ID транспорта print(idcar) -- Выводим ID транспорта в консоль Sampfuncs. end end end end ``` -------------------------------- ### startCredits() - вызов титров Source: https://wiki.blast.hk/moonloader/lua/startCredits Вызывает титры после прохождения игры на экран. Функция не принимает аргументов. ```lua startCredits() ``` -------------------------------- ### Example usage of addExplosion in Lua Source: https://wiki.blast.hk/moonloader/lua/addExplosion Example usage of addExplosion in a MoonLoader Lua script. It registers a chat command 'test' that gets the player's coordinates and calls addExplosion with radius 35. ```lua function main() while not isSampAvailable() do wait(100) end sampRegisterChatCommand("test",function() positionX, positionY, positionZ = getCharCoordinates(PLAYER_PED) addExplosion(positionX, positionY, positionZ, 35) end) wait(-1) end ``` -------------------------------- ### bool result = startNewCustomScript(zstring filepath, table args) Source: https://wiki.blast.hk/moonloader/scripting-api Starts a new custom script with the given file path and arguments. ```APIDOC ## bool result = startNewCustomScript(zstring filepath, table args) ### Description Starts a new custom script with the given file path and arguments. ### Parameters - **filepath** (zstring) - Required - The path to the script file. - **args** (table) - Required - A table of arguments to pass. ### Return Value - **result** (bool) - True if started successfully, false otherwise. ``` -------------------------------- ### Example usage of getActiveInterior Source: https://wiki.blast.hk/moonloader/lua/getActiveInterior Example usage of getActiveInterior in a MoonLoader script. It waits for SAMP to be available, registers a chat command 'test', and when invoked, gets the current interior ID and sends it as a chat message. ```lua function main() while not isSampAvailable() do wait(100) end sampRegisterChatCommand("test",function() interior = getActiveInterior() sampAddChatMessage(interior,-1) end) wait(-1) end ``` -------------------------------- ### Example: Get and Print Targeted Player's Nickname Source: https://wiki.blast.hk/moonloader/lua/sampGetPlayerNickname Example usage of sampGetPlayerNickname. It waits for SA:MP to be available, then when the player targets another character and presses VK_1, it retrieves the target's player ID and prints their nickname. ```lua script_name("Example script") function main() while not isSampAvailable() do wait(100) end while true do wait(0) local result, target = getCharPlayerIsTargeting(playerHandle) if result then result, playerid = sampGetPlayerIdByCharHandle(target) end if result and isKeyDown(VK_1) then name = sampGetPlayerNickname(playerid) print(name) end end end ``` -------------------------------- ### Example usage of deleteChar in a chat command Source: https://wiki.blast.hk/moonloader/lua/deleteChar Example Lua script that registers a chat command 'deletechar' to delete a player character. It uses sampGetCharHandleBySampPlayerId to get the character handle and deleteChar to remove it. If the player is not in the stream zone, it shows an error message. ```lua -- В функцию main sampRegisterChatCommand('deletechar', function(id) local result, ped = sampGetCharHandleBySampPlayerId(id) if result then deleteChar(ped) sampAddChatMessage('вы удалили игрока: ' .. id, -1) else sampAddChatMessage('игрок не в зоне стрима!', -1) end end) ``` -------------------------------- ### Download file with downloadUrlToFile and cancel on key press Source: https://wiki.blast.hk/moonloader/lua/downloadUrlToFile Example usage of downloadUrlToFile in a MoonLoader Lua script. It defines a download handler that prints progress and allows cancellation, and a main loop that starts the download on F1 and cancels it on F2. The handler returns false to abort the download when stop_downloading is set. ```lua local dlstatus = require('moonloader').download_status local vk = require 'vkeys' function download_handler(id, status, p1, p2) if stop_downloading then stop_downloading = false download_id = nil print('Загрузка отменена.') return false -- прервать загрузку end if status == dlstatus.STATUS_DOWNLOADINGDATA then print(string.format('Загружено %d из %d.', p1, p2)) elseif status == dlstatus.STATUS_ENDDOWNLOADDATA then print('Загрузка завершена.') end end function main() print('Нажмите F1, чтобы начать загрузку файла.') while true do wait(0) if wasKeyPressed(vk.VK_F1) and not download_id then local url = 'http://nonexistentfilehosting.com/nonexistentfile.dat' local file_path = getWorkingDirectory() .. '/downloads/file.dat' download_id = downloadUrlToFile(url, file_path, download_handler) print('Загрузка начата. Нажмите F2, чтобы отменить её.') elseif wasKeyPressed(vk.VK_F2) and download_id then stop_downloading = true end end end ``` -------------------------------- ### setUpConversationEndNodeWithScriptedSpeech(GxtString dialogueGxt, int wav) Source: https://wiki.blast.hk/moonloader/scripting-api Sets up a conversation end node with scripted speech. ```APIDOC ## setUpConversationEndNodeWithScriptedSpeech(GxtString dialogueGxt, int wav) ### Description Sets up a conversation end node with scripted speech. ### Parameters - **dialogueGxt** (GxtString) - Required - GXT string for the dialogue. - **wav** (int) - Required - WAV file ID. ### Return Value None. ``` -------------------------------- ### setCharCollision usage example Source: https://wiki.blast.hk/moonloader/lua/setCharCollision Example usage of setCharCollision. Enables collision for the player character. ```lua setCharCollision(PLAYER_PED, true) ``` -------------------------------- ### startCredits() Source: https://wiki.blast.hk/moonloader/lua/startCredits Документация функции startCredits, которая вызывает титры после прохождения игры на экран. ```APIDOC ## startCredits() ### Description Вызывает титры после прохождения игры на экран. ### Method Function ### Signature `startCredits()` ### Parameters None ### Return Value None ``` -------------------------------- ### applyBrakesToPlayersCar(Player player, bool apply) Source: https://wiki.blast.hk/moonloader/lua/applyBrakesToPlayersCar Устанавливает или снимает тормоза у автомобиля игрока. Если тормоза установлены, игрок не сможет двигаться в автомобиле. ```APIDOC ## applyBrakesToPlayersCar(Player player, bool apply) ### Description Установить/Снять тормоза(невозможность двигаться) у авто. Если "тормоза" установить, то как бы игрок не пытался двигаться в авто он будет стоять на месте. ### Arguments - **player** (Player) - хендл игрока - **apply** (bool) - статус ### Return Value - **result** (bool) - статус ### Example ```lua bool result = applyBrakesToPlayersCar(Player player, bool apply) ``` ``` -------------------------------- ### Example usage of taskCarDriveToCoord Source: https://wiki.blast.hk/moonloader/lua/taskCarDriveToCoord Example usage: if the player is in a car, it drives to coordinates (0,0,0) at speed 15 with rideType 2 and driveType 7, waits until the X key is pressed, then clears tasks and warps the player back into the car as driver. ```lua function main() if isCharInAnyCar(PLAYER_PED) then taskCarDriveToCoord(PLAYER_PED, storeCarCharIsInNoSave(PLAYER_PED), 0, 0, 0, 15, 2, nil, 7) --начинает ехать на координаты 0, 0, 0 и останавливается если нажата кнопка X while not isKeyJustPressed(VK_X) do wait(0) end --когда игрок нажимает X останавливает движение clearCharTasks(PLAYER_PED) taskWarpCharIntoCarAsDriver(PLAYER_PED, storeCarCharIsInNoSave(PLAYER_PED)) end end ``` -------------------------------- ### hasDeatharrestBeenExecuted usage example Source: https://wiki.blast.hk/moonloader/lua/hasDeatharrestBeenExecuted Example usage: checks if the character is dead or arrested and prints a message if so. ```lua if hasDeatharrestBeenExecuted() then -- если персонаж мертв, то print('Вы умерли!') -- вывести "Вы умерли!" end ``` -------------------------------- ### Generated example_another_config.ini content Source: https://wiki.blast.hk/moonloader/lua/inicfg Example output of the example_another_config.ini file after the script processes it: new random values for value1 and value2, and their sum, written to the main section. ```ini [main] value1=312 value2=591 sum=903 ``` -------------------------------- ### Example usage of renderDrawBox Source: https://wiki.blast.hk/moonloader/lua/renderDrawBoxWithBorder Example call to renderDrawBoxWithBorder (note: the example uses renderDrawBox, not renderDrawBoxWithBorder). Draws a rectangle at (10,15) with size 200x80, fill color 0xAA00CC00, border thickness 3, and border color 0x90000000. ```lua renderDrawBox(10, 15, 200, 80, 0xAA00CC00, 3, 0x90000000) ``` -------------------------------- ### taskPlayAnim(Ped ped, string animation, string IFP, float framedelta, bool loop, bool lockX, bool lockY, bool lockF, int time) Source: https://wiki.blast.hk/moonloader/lua/taskPlayAnim Заставляет актёра воспроизвести или сбить анимацию. Принимает параметры для управления анимацией, включая имя анимации, файл IFP, скорость, повторение, блокировку позиций и время. ```APIDOC ## taskPlayAnim(Ped ped, string animation, string IFP, float framedelta, bool loop, bool lockX, bool lockY, bool lockF, int time) ### Description Заставляет актёра воспроизвести / сбить анимацию. ### Parameters - **ped** (Ped) - хендл персонажа - **animation** (string) - имя анимации - **IFP** (string) - файл анимации - **framedelta** (float) - скорость анимации - **loop** (bool) - повторение анимации (true - да, false - нет) - **lockX** (bool) - блокировка позиции по X (true - да, false - нет) - **lockY** (bool) - блокировка позиции по Y (true - да, false - нет) - **lockF** (bool) - возврат в исходное положение (true - возвращать, false - не возвращать) - **time** (int) - время воспроизведения ### Example ```lua require 'moonloader' function main() while true do wait(0) if isKeyJustPressed(VK_X) then taskPlayAnim(PLAYER_PED, "WF_FWD", "WAYFARER", 9, false, false, false, false, -1) end end end ``` ``` -------------------------------- ### onStartNewGame(int mpack) Source: https://wiki.blast.hk/moonloader/events The onStartNewGame event is called when a new game starts. It receives the mission pack ID. ```APIDOC ## onStartNewGame(int mpack) ### Description Called when a new game starts. The mission pack ID is passed. ### Method N/A (Lua event) ### Endpoint N/A ### Parameters - **mpack** (int) - Required - The mission pack ID. ### Request Example ```lua function onStartNewGame(mpack) -- handle new game end ``` ### Response No return value. ``` -------------------------------- ### setCarCruiseSpeed usage example Source: https://wiki.blast.hk/moonloader/lua/setCarCruiseSpeed Example usage of setCarCruiseSpeed, setting the cruise speed of the vehicle 'mycar' to 120.0. ```lua setCarCruiseSpeed(mycar, 120.0) ``` -------------------------------- ### setBoatCruiseSpeed usage example Source: https://wiki.blast.hk/moonloader/lua/setBoatCruiseSpeed Example call to setBoatCruiseSpeed, setting the maximum speed of the boat 'myboat' to 35.0. ```lua setBoatCruiseSpeed(myboat, 35.0) ``` -------------------------------- ### sampSetChatInputEnabled usage examples Source: https://wiki.blast.hk/moonloader/lua/sampSetChatInputEnabled Example calls: passing true opens the chat, passing false closes it. ```lua sampSetChatInputEnabled(true) - открывает чат sampSetChatInputEnabled(false) - закрывает чат ``` -------------------------------- ### onSystemInitialized() Source: https://wiki.blast.hk/moonloader/lua/onSystemInitialized Документация события onSystemInitialized, которое вызывается один раз после загрузки всех скриптов, но до полной загрузки игры и выполнения функции main. ```APIDOC ## onSystemInitialized() ### Description Выполняется единожды после загрузки всех скриптов, но перед полной загрузкой игры и выполнением функции main. ### Method Событие (callback) ### Endpoint onSystemInitialized ### Parameters Нет параметров. ### Request Example ```lua onSystemInitialized() ``` ### Response Нет возвращаемого значения. ``` -------------------------------- ### onD3DDeviceReset usage example Source: https://wiki.blast.hk/moonloader/lua/onD3DDeviceReset Example handler that reinitializes a D3DX font by calling OnResetDevice after the device reset. ```lua -- ... function onD3DDeviceReset() d3dxfont.vtbl.OnResetDevice(d3dxfont) end -- ... ``` -------------------------------- ### Пример использования doesDirectoryExist Source: https://wiki.blast.hk/moonloader/lua/doesDirectoryExist Проверяет существование папки по пути, полученному из getWorkingDirectory() и константы "resource". Выводит сообщение в зависимости от результата. ```lua local path = getWorkingDirectory() .. "\\resource" if doesDirectoryExist(path) then print("The folder exist") else print("The folder does not exist") end ``` -------------------------------- ### setGameKeyState(int key, int state) Source: https://wiki.blast.hk/moonloader/lua/setGameKeyState Устанавливает статус нажатия игровой клавиши. Принимает индекс клавиши и статус в диапазоне от -32768 до 32767. Отрицательные статусы предназначены для клавиш с двумя действиями. ```APIDOC ## setGameKeyState(int key, int state) ### Description Устанавливает статус нажатия игровой клавиши. ### Parameters - **key** (int) - Required - индекс клавиши (также указаны в библиотеке `game.keys`) - **state** (int) - Required - статус (-32768 до 32767). Статусы отрицательного значения (-32768, -256, -128 и т.п.) предназначены только для тех клавиш, которые имеют два действия: `GOLEFT_GORIGHT`, `GOFORWARD_GOBACK`, `ANSWERPHONE_FIREWEAPONALT`, `LOOKBEHIND_LOOKRIGHT` и подобных. ### Example ```lua setGameKeyState(0, 255) ``` ``` -------------------------------- ### Example usage of setTargetBlipCoordinates Source: https://wiki.blast.hk/moonloader/lua/setTargetBlipCoordinates Example usage: registers a chat command 'setmarker' that calls setTargetBlipCoordinates with the provided arguments. ```lua function main() while not isSampAvailable() do wait (100) end sampRegisterChatCommand("setmarker", marker) wait(-1) end function marker(x, y, z) setTargetBlipCoordinates(x, y, z) end ``` -------------------------------- ### script_author usage example Source: https://wiki.blast.hk/moonloader/lua/script_author Example of setting a script author and printing it in the main function using thisScript().author. ```lua script_author("Example") function main() print(unpack(thisScript().author)) -- Example end ``` -------------------------------- ### isOpcodesAvailable: проверка доступности функций опкодов Source: https://wiki.blast.hk/moonloader/lua/isOpcodesAvailable Проверяет, доступны ли функции опкодов для использования. Возвращает статус в переменную status. На этапе выполнения подпрограммы main они гарантированно доступны, поэтому проверка не требуется. ```lua bool status = isOpcodesAvailable() ``` -------------------------------- ### Example usage of deleteCheckpoint Source: https://wiki.blast.hk/moonloader/lua/deleteCheckpoint Example usage that registers a chat command 'delCheckpoint' which calls deleteCheckpoint with the provided argument. ```lua function main() sampRegisterChatCommand("delCheckpoint", function(arg1) deleteCheckpoint(arg1) end) end ``` -------------------------------- ### createDirectory Source: https://wiki.blast.hk/moonloader/scripting-api Creates a directory. ```APIDOC ## createDirectory ### Description Creates a directory. ### Parameters - **directory** (string) - Directory path ### Returns - **result** (bool) - Whether the directory was created successfully ``` -------------------------------- ### setGameGlobalFloat usage example Source: https://wiki.blast.hk/moonloader/lua/setGameGlobalFloat Example usage of setGameGlobalFloat. It requires the 'game.globals' module and sets the global variable HJ_Stoppie_Distance_Float to 123.45. ```lua local globals = require 'game.globals' setGameGlobalFloat(globals.HJ_Stoppie_Distance_Float, 123.45) ``` -------------------------------- ### runSampfuncsConsoleCommand(zstring cmd) Source: https://wiki.blast.hk/moonloader/lua/runSampfuncsConsoleCommand Executes the specified SAMPFUNCS console command. The command is passed as a string. ```APIDOC ## runSampfuncsConsoleCommand(zstring cmd) ### Description Executes the specified SAMPFUNCS console command. ### Function Signature `runSampfuncsConsoleCommand(zstring cmd)` ### Parameters - **cmd** (zstring) - Required - The console command to execute. ### Return Value No return value is documented. ### Example ```lua runSampfuncsConsoleCommand("some command") ``` ``` -------------------------------- ### setCharProofs usage example Source: https://wiki.blast.hk/moonloader/lua/setCharProofs Example call that grants the player character immunity to bullets, fire, explosions, collisions, and melee weapons. ```lua setCharProofs(playerPed, true, true, true, true, true) ``` -------------------------------- ### 0417 loadAndLaunchMissionInternal Source: https://wiki.blast.hk/moonloader/opcodes Loads and launches a mission internally. ```APIDOC ## loadAndLaunchMissionInternal(int mission) ### Description Loads and launches a mission internally. ### Parameters - **mission** (int) - Required - Mission ID. ``` -------------------------------- ### script_authors usage example Source: https://wiki.blast.hk/moonloader/lua/script_authors Example usage of script_authors to set multiple authors and then print them in the main function using thisScript().authors. ```lua script_authors("FYP", "hnnssy", "EvgeN 1137") function main() print(unpack(thisScript().authors)) end ``` -------------------------------- ### main() Source: https://wiki.blast.hk/moonloader/events The main() event is the entry point for a MoonLoader script. It is called when the script starts. ```APIDOC ## main() ### Description Called when the script starts. This is the entry point for the script. ### Method N/A (Lua event) ### Endpoint N/A ### Parameters None ### Request Example ```lua function main() -- script logic end ``` ### Response No return value. ``` -------------------------------- ### Example usage of onD3DPresent Source: https://wiki.blast.hk/moonloader/lua/onD3DPresent Example of using the onD3DPresent event to draw text on the screen with DirectX. The function is called before IDirect3DDevice9::Present. ```lua -- ... function onD3DPresent() d3dxfont.vtbl.DrawTextA(d3dxfont, nil, 'text', -1, prect, 0, 0xFFFFFFFF) end -- ... ``` -------------------------------- ### getGameGlobalFloat usage example Source: https://wiki.blast.hk/moonloader/lua/getGameGlobalFloat Example usage of getGameGlobalFloat in Lua. It requires the 'game.globals' module and retrieves the global float variable HJ_Stoppie_Distance_Float. ```lua local globals = require 'game.globals' local fval = getGameGlobalFloat(globals.HJ_Stoppie_Distance_Float) ``` -------------------------------- ### setRadioToPlayersFavouriteStation() Source: https://wiki.blast.hk/moonloader/lua/setRadioToPlayersFavouriteStation Документация функции setRadioToPlayersFavouriteStation, которая устанавливает радиостанцию транспортного средства игрока на его любимую станцию. ```APIDOC ## setRadioToPlayersFavouriteStation() ### Description Устанавливает радиостанцию транспортного средства, на котором игрок находится в настоящее время, на любимую станцию, полученную из статистики. ### Method Function call ### Signature `setRadioToPlayersFavouriteStation()` ### Parameters None ### Return Value None ``` -------------------------------- ### Example usage of doesFileExist Source: https://wiki.blast.hk/moonloader/lua/doesFileExist Example usage of doesFileExist. It constructs a path using getWorkingDirectory() and checks if the file exists, printing a message accordingly. ```lua local path = getWorkingDirectory() .. "\\test.lua" if doesFileExist(path) then print("The file exist") else print("The file does not exist") end ```