Вопросы по Lua скриптингу

Общая тема для вопросов по разработке скриптов на языке программирования Lua, в частности под MoonLoader.
  • Задавая вопрос, убедитесь, что его нет в списке частых вопросов и что на него ещё не отвечали (воспользуйтесь поиском).
  • Поищите ответ в теме посвященной разработке Lua скриптов в MoonLoader
  • Отвечая, убедитесь, что ваш ответ корректен.
  • Старайтесь как можно точнее выразить мысль, а если проблема связана с кодом, то обязательно прикрепите его к сообщению, используя блок [code=lua]здесь мог бы быть ваш код[/code].
  • Если вопрос связан с MoonLoader-ом первым делом желательно поискать решение на wiki.

Частые вопросы

Как научиться писать скрипты? С чего начать?
Информация - Гайд - Всё о Lua скриптинге для MoonLoader(https://blast.hk/threads/22707/)
Как вывести текст на русском? Вместо русского текста у меня какие-то каракули.
Изменить кодировку файла скрипта на Windows-1251. В Atom: комбинация клавиш Ctrl+Shift+U, в Notepad++: меню Кодировки -> Кодировки -> Кириллица -> Windows-1251.
Как получить транспорт, в котором сидит игрок?
Lua:
local veh = storeCarCharIsInNoSave(PLAYER_PED)
Как получить свой id или id другого игрока?
Lua:
local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED) -- получить свой ид
local _, id = sampGetPlayerIdByCharHandle(ped) -- получить ид другого игрока. ped - это хендл персонажа
Как проверить, что строка содержит какой-то текст?
Lua:
if string.find(str, 'текст', 1, true) then
-- строка str содержит "текст"
end
Как эмулировать нажатие игровой клавиши?
Lua:
local game_keys = require 'game.keys' -- где-нибудь в начале скрипта вне функции main

setGameKeyState(game_keys.player.FIREWEAPON, -1) -- будет сэмулировано нажатие клавиши атаки
Все иды клавиш находятся в файле moonloader/lib/game/keys.lua.
Подробнее о функции setGameKeyState здесь: lua - setgamekeystate | BlastHack — DEV_WIKI(https://www.blast.hk/wiki/lua:setgamekeystate)
Как получить id другого игрока, в которого целюсь я?
Lua:
local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
  local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
  if result then -- проверить, прошло ли получение ида успешно
    -- здесь любые действия с полученным идом игрока
  end
end
Как зарегистрировать команду чата SAMP?
Lua:
-- До бесконечного цикла/задержки
sampRegisterChatCommand("mycommand", function (param)
     -- param будет содержать весь текст введенный после команды, чтобы разделить его на аргументы используйте string.match()
    sampAddChatMessage("MyCMD", -1)
end)
Крашит игру при вызове sampSendChat. Как это исправить?
Это происходит из-за бага в SAMPFUNCS, когда производится попытка отправки пакета определенными функциями изнутри события исходящих RPC и пакетов. Исправления для этого бага нет, но есть способ не провоцировать его. Вызов sampSendChat изнутри обработчика исходящих RPC/пакетов нужно обернуть в скриптовый поток с нулевой задержкой:
Lua:
function onSendRpc(id)
  -- крашит:
  -- sampSendChat('Send RPC: ' .. id)

  -- норм:
  lua_thread.create(function()
    wait(0)
    sampSendChat('Send RPC: ' .. id)
  end)
end
 
Последнее редактирование:

lorgon

Известный
657
265
Как получить ближайшую машину с водителем?(Получить именно машину с человеком в водительском месте)
 

Leo_Mendes

Известный
52
3
Подскажите как исправить чтобы была проверка на Polic Car и добавлялась строка Strobe, и как сделать проверку на определенный вид транспорта к примеру (515)???

Lua:
    if CarYou.v and isCharInAnyCar(PLAYER_PED) and sampTextdrawIsExists(2054) then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 1.7, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0, 0))
        imgui.Begin('dbg##12', CarYou, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoBringToFrontOnFocus + imgui.WindowFlags.AlwaysAutoResize)
        imgui.RenderInMenu = false
        imgui.ShowCursor = false
        local width = imgui.GetWindowWidth()
        local hight = imgui.GetWindowHeight()
        local calc = imgui.CalcTextSize('Car | Speedometer')
        local vehHandle = storeCarCharIsInNoSave(PLAYER_PED)
        local vehid = getCarModel(vehHandle)
        local res, vehSid = sampGetVehicleIdByCarHandle(vehHandle)
        local vehName = getGxtText(getNameOfVehicleModel(vehid))
        local Strobe = (isCarSirenOn(vehHandle) == true and "ON" or "OFF")
        imgui.SetCursorPosX(width / 2 - calc.x / 2)
         imgui.Text('Car | Speedometer')
        imgui.Separator()
         imgui.Text("Car:")
        imgui.SameLine()
        imgui.SetCursorPosX(width / 3.2)
        imgui.Text(string.format("[%d] %s [Server: %d]", vehid, vehName, vehSid))

        if isCharInAnyPoliceVehicle(PLAYER_PED) then
         imgui.Text("Strobe:")
        imgui.SameLine()
        imgui.SetCursorPosX(width / 3.2)
        imgui.Text(string.format("%s", Strobe))
            imgui.End()
    end
end
 

штейн

Известный
Проверенный
1,001
687
Lua:
local response, err = httpRequest('POST', {'http://f0320362.xsph.ru/add.php', data = 'id='..random..'sum=1000'})
if err then error(err) end
requests.lua:153: No url specified for request
ЧЕ ЕМУ НАДО ОТ МЕНЯЯЯЯЯЯЯЯ


ещё попробовал:
Lua:
httpRequest("http://f0320362.xsph.ru/add.php", 'id='..random..'&sum=1000', function(response, code, headers, status)
    if response then
        print('OK', status)
    else
        print('Error', code)
    end
end)
Error Параметр задан неверно.

@#Northn @imring @FYP че это мб я тупой или как хелп
помогите эксперты вам не трудно мне приятно 2
 

astynk

Известный
Проверенный
744
531
Как получить ближайшую машину с водителем?(Получить именно машину с человеком в водительском месте)
Не проверял.
Lua:
function getClosestCarWithDriver()
    local x, y, z = getCharCoordinates(1)
    local mindist = 9999
    local closest = -1
    for i, car in pairs(getAllVehicles()) do
        if getDriverOfCar(car) ~= -1 then
            local dist = getDistanceBetweenCoords3d(getCarCoordinates(car), getCharCoordinates(1))
            if dist < mindist then
                mindist = dist
                closest = car
            end
        end
    end
    return closest
end
 
Последнее редактирование:

P0M61K

Активный
266
57
При взаимодействии с любым из элементов окна - игра крашит. Что тут не так?

Lua:
require "lib.sampfuncs"
require "lib.moonloader"
local inicfg = require 'inicfg'
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
local encoding = require 'encoding'

encoding.default = 'CP1251'
u8 = encoding.UTF8

-- Стиль окна имгуи --

imgui.SwitchContext()
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4

colors[clr.Text]   = ImVec4(0.00, 0.00, 0.00, 0.51)
colors[clr.TextDisabled]   = ImVec4(0.24, 0.24, 0.24, 1.00)
colors[clr.WindowBg]              = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[clr.ChildWindowBg]         = ImVec4(0.96, 0.96, 0.96, 1.00)
colors[clr.PopupBg]               = ImVec4(0.92, 0.92, 0.92, 1.00)
colors[clr.Border]                = ImVec4(0.86, 0.86, 0.86, 1.00)
colors[clr.BorderShadow]          = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.FrameBg]               = ImVec4(0.88, 0.88, 0.88, 1.00)
colors[clr.FrameBgHovered]        = ImVec4(0.82, 0.82, 0.82, 1.00)
colors[clr.FrameBgActive]         = ImVec4(0.76, 0.76, 0.76, 1.00)
colors[clr.TitleBg]               = ImVec4(0.00, 0.45, 1.00, 0.82)
colors[clr.TitleBgCollapsed]      = ImVec4(0.00, 0.45, 1.00, 0.82)
colors[clr.TitleBgActive]         = ImVec4(0.00, 0.45, 1.00, 0.82)
colors[clr.MenuBarBg]             = ImVec4(0.00, 0.37, 0.78, 1.00)
colors[clr.ScrollbarBg]           = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.ScrollbarGrab]         = ImVec4(0.00, 0.35, 1.00, 0.78)
colors[clr.ScrollbarGrabHovered]  = ImVec4(0.00, 0.33, 1.00, 0.84)
colors[clr.ScrollbarGrabActive]   = ImVec4(0.00, 0.31, 1.00, 0.88)
colors[clr.ComboBg]               = ImVec4(0.92, 0.92, 0.92, 1.00)
colors[clr.CheckMark]             = ImVec4(0.00, 0.49, 1.00, 0.59)
colors[clr.SliderGrab]            = ImVec4(0.00, 0.49, 1.00, 0.59)
colors[clr.SliderGrabActive]      = ImVec4(0.00, 0.39, 1.00, 0.71)
colors[clr.Button]                = ImVec4(0.00, 0.49, 1.00, 0.59)
colors[clr.ButtonHovered]         = ImVec4(0.00, 0.49, 1.00, 0.71)
colors[clr.ButtonActive]          = ImVec4(0.00, 0.49, 1.00, 0.78)
colors[clr.Header]                = ImVec4(0.00, 0.49, 1.00, 0.78)
colors[clr.HeaderHovered]         = ImVec4(0.00, 0.49, 1.00, 0.71)
colors[clr.HeaderActive]          = ImVec4(0.00, 0.49, 1.00, 0.78)
colors[clr.ResizeGrip]            = ImVec4(0.00, 0.39, 1.00, 0.59)
colors[clr.ResizeGripHovered]     = ImVec4(0.00, 0.27, 1.00, 0.59)
colors[clr.ResizeGripActive]      = ImVec4(0.00, 0.25, 1.00, 0.63)
colors[clr.CloseButton]           = ImVec4(0.00, 0.35, 0.96, 0.71)
colors[clr.CloseButtonHovered]    = ImVec4(0.00, 0.31, 0.88, 0.69)
colors[clr.CloseButtonActive]     = ImVec4(0.00, 0.25, 0.88, 0.67)
colors[clr.PlotLines]             = ImVec4(0.00, 0.39, 1.00, 0.75)
colors[clr.PlotLinesHovered]      = ImVec4(0.00, 0.39, 1.00, 0.75)
colors[clr.PlotHistogram]         = ImVec4(0.00, 0.39, 1.00, 0.75)
colors[clr.PlotHistogramHovered]  = ImVec4(0.00, 0.35, 0.92, 0.78)
colors[clr.TextSelectedBg]        = ImVec4(0.00, 0.47, 1.00, 0.59)
colors[clr.ModalWindowDarkening]  = ImVec4(0.20, 0.20, 0.20, 0.35)

-- Переменные --
local config_direct = "TR/tr_by_P0M61K_v1.01"
local iniconfig = inicfg.load(nil, config_direct)
if iniconfig == nil then
ini = {
    main = {
        deagle=false,
        m4=false,
        rpg=false,
        shotgun=false,
        rifle=false,
        ak47=false,
        hp=50
     }
}
     inicfg.save(ini, config_direct)
     iniconfig = inicfg.load(nil, config_direct)
end

local deagle_state = imgui.ImBool(iniconfig["main"]["deagle"])
local m4_state = imgui.ImBool(iniconfig["main"]["m4"])
local rpg_state = imgui.ImBool(iniconfig["main"]["rpg"])
local shotgun_state = imgui.ImBool(iniconfig["main"]["shotgun"])
local rifle_state = imgui.ImBool(iniconfig["main"]["rifle"])
local ak47_state = imgui.ImBool(iniconfig["main"]["ak47"])

local slider_hp = imgui.ImInt(iniconfig["main"]["hp"])

local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

local doHide = true
local working = false

imgui.Process = false

-- Основной код --

function cmd_imgui(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(200, 250), imgui.Cond.FirstUseEver)
    imgui.Begin(u8"TR - Настройки" , main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoScrollbar)
    imgui.Text(u8"Выбор оружия")
    if imgui.Checkbox("Deagle", deagle_state) then
        iniconfig["main"]["deagle"] = deagle_state.v
        inicfg.save(ini, config_direct)
    end
    imgui.SetCursorPos(imgui.ImVec2(80, 47))
    if imgui.Checkbox("M4", m4_state) then
        iniconfig["main"]["m4"] = m4_state.v
        inicfg.save(ini, config_direct)
    end
    if imgui.Checkbox("Ak47", ak47_state) then
        iniconfig["main"]["ak47"] = ak47_state.v
        inicfg.save(ini, config_direct)
    end
    imgui.SetCursorPos(imgui.ImVec2(80, 72))
    if imgui.Checkbox("Shotgun", shotgun_state) then
        iniconfig["main"]["shotgun"] = shotgun_state.v
        inicfg.save(ini, config_direct)
    end
    if imgui.Checkbox("Rpg", rpg_state) then
        iniconfig["main"]["rpg"] = rpg_state.v
        inicfg.save(ini, config_direct)
    end
    imgui.SetCursorPos(imgui.ImVec2(80, 97))
    if imgui.Checkbox("Rifle", rifle_state) then
        iniconfig["main"]["rifle"] = rifle_state.v
        inicfg.save(ini, config_direct)
    end
    imgui.Text(u8" ")
    imgui.Text(u8"Выбор хп")
    if imgui.SliderInt(" ", slider_hp, 5, 100) then
      if slider_hp.v < 40 then
        imgui.Text(u8"Скрипт не прячет на ноль хп.")
        imgui.Text(u8"Рекомендованое значение - 50!")
      else
        iniconfig["main"]["hp"] = slider_hp.v
        inicfg.save(ini, config_direct)
        imgui.Text(u8" ")
        imgui.Text(u8" ")
      end
    end
    imgui.End()
end

function main()
    while not isSampAvailable() do wait(0) end
    main_window_stat = false
    sampAddChatMessage("Скрипт tr запущен. Автор P0M61KxMUERTOS. Активация - /tr. Меню скрипта - /trmenu", -1)
    sampRegisterChatCommand("tr", function()
        Active = not Active
        if Active then
            whielka = 1
            sampAddChatMessage("tr by P0M61K - ON", -1)
        else
            whielka = 0
            sampAddChatMessage("tr by P0M61K - OFF", -1)
        end
    end)

    sampRegisterChatCommand("trmenu", cmd_imgui)

    function sampev.onSendSpawn()
        doHide = true
    end

    while true do wait(0)
        if main_window_state.v == false then
            imgui.Process = false
        end

        if whielka == 1 then     
            if doHide and getCharHealth(PLAYER_PED) < slider_hp.v then
                if deagle_state.v then
                    sampSendChat("/hide eag")
                end
            
                if m4_state.v then
                    sampSendChat("/hide m4")
                end
            
                if shotgun_state.v then
                    sampSendChat("/hide shotgun")
                end
            
                if rpg_state.v then
                    sampSendChat("/hide rpg")
                end
            
                if rifle_state.v then
                    sampSendChat("/hide rifle")
                end
            
                if ak47_state.v then
                    sampSendChat("/hide ak47")
                end
            
                doHide = false
            end
        end
    end
end

Посмотрите пж. Я не знаю почему так
 

Ness

Новичок
4
1
Why does this error occur?

Lua:
function sampev.onBulletSync(playerId, data)
    bool, handle = sampGetCharHandleBySampPlayerId(playerId)
    X, Y, Z = getCharCoordinates(handle)
    data.target.x = X
    data.target.y = Y
    data.target.z = Z
    print('playerId: ['..playerId..'] X: ['..data.target.x..'] Y: ['..data.target.y..'] Z: ['..data.target.z..']')
    return {playerId, data}
end

Error:
cannot convert 'struct BulletSyncData' to 'int'
 

r4nx

Известный
Друг
202
260
Есть инструкция байткода: 32 00 0D 80
Первый байт - опкод JMP, второй - некий base, третий - на сколько шагов прыгать, а что с четвертым? Он всегда равен 80, но почему? Был бы ещё благодарен, если б вкратце объяснили ещё предназначение base
 

Thief

Участник
108
12
Lua:
local memory = require("memory")
local key = require 'vkeys'
local events = require 'lib.samp.events'

function main()
end

function events.onTextDrawSetString(id, text)
if tonumber(text) ~= nil then
if id == 2062 and tonumber(text) < 50 then
print('on')
end
end
if tonumber(text) ~= nil then
if id == 2062 and tonumber(text) > 50 then
print('off')
end
end
print(id, text)
end
id = 2062 это кислородный балон. Скрипт должен выдавать офф или он, взависимости от того сколько кислорода осталось в балоне, но он вообще ничего не выдаёт и ошибки нету!
Стандартные проверки на загрузку сампа и т. п. с бесконечным циклом в main поставь
 

rakzo

Известный
99
3
Не работает скрипт написан на луа
function main()
sampRegisterChatCommand("CursorMode_0", CursorMode_0)
sampRegisterChatCommand("CursorMode_1", CursorMode_1)
sampRegisterChatCommand("CursorMode_2", CursorMode_2)
sampRegisterChatCommand("CursorMode_3", CursorMode_3)
sampRegisterChatCommand("CursorMode_4", CursorMode_4)
while true do
wait(0)
end
end
function CursorMode_0()
if sampSetCursorMode(0) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_1()
if sampSetCursorMode(1) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_2()
if sampSetCursorMode(2) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_3()
if sampSetCursorMode(3) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_4()
if sampSetCursorMode(4) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
end
 

Dmitriy Makarov

25.05.2021
Проверенный
2,479
1,113
Lua:
local sampev = require 'lib.samp.events'


function sampev.onServerMessage(color, text)
    if text:find("SMS: %a+ | Отправитель: %a+_%a+ [т.%d+]", 1, true) then
    sampAddChatMessage("Пришло сообщение", -1)
    end
end
не реагирует чет, впервые юзаю эти символы прост
 

astynk

Известный
Проверенный
744
531
Не работает скрипт написан на луа
function main()
sampRegisterChatCommand("CursorMode_0", CursorMode_0)
sampRegisterChatCommand("CursorMode_1", CursorMode_1)
sampRegisterChatCommand("CursorMode_2", CursorMode_2)
sampRegisterChatCommand("CursorMode_3", CursorMode_3)
sampRegisterChatCommand("CursorMode_4", CursorMode_4)
while true do
wait(0)
end
end
function CursorMode_0()
if sampSetCursorMode(0) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_1()
if sampSetCursorMode(1) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_2()
if sampSetCursorMode(2) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_3()
if sampSetCursorMode(3) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
function CursorMode_4()
if sampSetCursorMode(4) then
sampAddChatMessage(Ваш Курсор Успешно Изменён, 0x7FFFD4)
end
end
После каждого объявления функции не хватает end.
Строки должны быть в кавычках.
sampSetCursorMode не возвращает значения, использовать ее в if бессмысленно.