Вопросы по 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
 
Последнее редактирование:

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
У меня такая проблема что если у меня сзади стоит игрок то renderDrawLine показывает его спереди
(в бх я фотку загрузить не могу и на это есть причина но загрузил в imgur)
Скрин с игры где я вперед смотрю
Скрин с игры где я назад смотрю

Код
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    while true do
        wait(0)
        for k, v in pairs(getAllChars()) do
            if v ~= PLAYER_PED then
                local c = getCharModelCornersIn2d(getCharModel(v), v)
                local X, Y = getScreenResolution()
                renderFigure2D(X/2, Y/2, 100, 250, 0xFF4682B4) -- нарисует круг с белой
                local x, y, z = getCharCoordinates(PLAYER_PED)
                local possaX, possaY, possaZ = getScreenResolution()
                local posX, posY = convert3DCoordsToScreen(x, y, z)
                local player = getNearCharToCenter(200)
                local color = tonumber("0xFF"..(("%X"):format(sampGetPlayerColor(id))):gsub(".*(......)", "%1"))--sampGetPlayerColor(id)
                local result, id = sampGetPlayerIdByCharHandle(v)
            end
            if player then
                local playerId = select(2, sampGetPlayerIdByCharHandle(player))
                local playerNick = sampGetPlayerNickname(playerId)
                local x2, y2, z2 = getCharCoordinates(player)
                local isScreen = isPointOnScreen(x2, y2, z2, 200)
            end  
            if isScreen then
                renderDrawLine(c[1][1], c[1][2], c[2][1], c[2][2], 2, 0xFF4682B4)
                renderDrawLine(c[2][1], c[2][2], c[3][1], c[3][2], 2, 0xFF4682B4)
                renderDrawLine(c[3][1], c[3][2], c[4][1], c[4][2], 2, 0xFF4682B4)
                renderDrawLine(c[4][1], c[4][2], c[1][1], c[1][2], 2, 0xFF4682B4)
                renderDrawLine(c[5][1], c[5][2], c[6][1], c[6][2], 2, 0xFF4682B4)
                renderDrawLine(c[6][1], c[6][2], c[7][1], c[7][2], 2, 0xFF4682B4)
                renderDrawLine(c[7][1], c[7][2], c[8][1], c[8][2], 2, 0xFF4682B4)
                renderDrawLine(c[8][1], c[8][2], c[5][1], c[5][2], 2, 0xFF4682B4)
                renderDrawLine(c[1][1], c[1][2], c[5][1], c[5][2], 2, 0xFF4682B4)
                renderDrawLine(c[2][1], c[2][2], c[8][1], c[8][2], 2, 0xFF4682B4)
                renderDrawLine(c[3][1], c[3][2], c[7][1], c[7][2], 2, 0xFF4682B4)
                renderDrawLine(c[4][1], c[4][2], c[6][1], c[6][2], 2, 0xFF4682B4)
                renderDrawPolygon(X/2, Y/2, 10, 10, 7, 5, 0xFF4682B4)
                local posX2, posY2 = convert3DCoordsToScreen(x2, y2, z2)
                renderDrawLine(X/2, Y/2, posX2, posY2, 2.0, 0xFF4682B4)
                renderDrawPolygon(posX2, posY2, 10, 10, 40, 0, 0xFF4682B4)
                local distance = math.floor(getDistanceBetweenCoords3d(x, y, z, x2, y2, z2))
                renderFontDrawTextAlign(font, string.format('%s[%d]', playerNick, playerId),posX2, posY2-30, 0xFF4682B4, 2)
                renderFontDrawTextAlign(font, string.format('Дистанция: %s', distance),X/2, Y/2+210, 0xFF4682B4, 2)
                renderFontDrawTextAlign(font, 'R - OnFoot Rvanka\nX - Incar Rvanka',X/2+300, Y/2-30, 0xFF4682B4, 1)
                if isKeyJustPressed(VK_1) then
                    sampSendChat('/re '..playerId)
                end
                if isKeyJustPressed(VK_2) then
                    sampSendChat('/frem '..playerId)
                end
                if isKeyJustPressed(VK_3) then
                    sampSendChat('/spawn '..playerId)
                end
                if isKeyJustPressed(VK_4) then
                    sampSendChat('/sethp '..playerId..' 100')
                end
                if isKeyJustPressed(VK_5) then
                    sampSendChat('/gethere '..playerId)
                end
            end
        end  
    end
end
Может потому, что ты в isPointOnScreen выставил радиус 200?
Попробуй лучше заменить эту функцию на эту.
 

lasttrain

Новичок
14
0
проблема. при достижении 15 хп, два раза прописывает /heal и один раз только принимает предложение, а вторая остается висеть

Lua:
local last_hp = nil
local key = require "vkeys"

function main()
    repeat wait(0) until isSampAvailable()
    while true do wait(0)
        local hp = getCharHealth(PLAYER_PED)
        if last_hp ~= hp then
            if hp < 15 then
                sampSendChat(string.format("/heal %s 5000", select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))))
                last_hp = hp
                setVirtualKeyDown(13, true)
                wait(10)
                setVirtualKeyDown(13, false)
            end
        end
    end
end
 

Marat Krutoi

Участник
56
9
Может потому, что ты в isPointOnScreen выставил радиус 200?
Попробуй лучше заменить эту функцию на эту.
1693251615029.png
Поможешь умешьить дистанцию показа игроков
 

Marat Krutoi

Участник
56
9
код дай, бедолажкин 😁
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    while true do
        wait(0)
        for k, v in pairs(getAllChars()) do
            if v ~= PLAYER_PED then
                local c = getCharModelCornersIn2d(getCharModel(v), v)
                local X, Y = getScreenResolution()
                renderFigure2D(X/2, Y/2, 100, 250, 0xFF4682B4) -- нарисует круг с белой
                local x, y, z = getCharCoordinates(PLAYER_PED)
                local possaX, possaY, possaZ = getScreenResolution()
                local posX, posY = convert3DCoordsToScreen(x, y, z)
                local player = getNearCharToCenter(200)
                local color = tonumber("0xFF"..(("%X"):format(sampGetPlayerColor(id))):gsub(".*(......)", "%1"))--sampGetPlayerColor(id)
                local result, id = sampGetPlayerIdByCharHandle(v)
            end
            if player then
                local playerId = select(2, sampGetPlayerIdByCharHandle(player))
                local playerNick = sampGetPlayerNickname(playerId)
                local x2, y2, z2 = getCharCoordinates(player)
                local isScreen = isPointOnScreen(x2, y2, z2, 200)
            end  
            if isScreen then
                renderDrawLine(c[1][1], c[1][2], c[2][1], c[2][2], 2, 0xFF4682B4)
                renderDrawLine(c[2][1], c[2][2], c[3][1], c[3][2], 2, 0xFF4682B4)
                renderDrawLine(c[3][1], c[3][2], c[4][1], c[4][2], 2, 0xFF4682B4)
                renderDrawLine(c[4][1], c[4][2], c[1][1], c[1][2], 2, 0xFF4682B4)
                renderDrawLine(c[5][1], c[5][2], c[6][1], c[6][2], 2, 0xFF4682B4)
                renderDrawLine(c[6][1], c[6][2], c[7][1], c[7][2], 2, 0xFF4682B4)
                renderDrawLine(c[7][1], c[7][2], c[8][1], c[8][2], 2, 0xFF4682B4)
                renderDrawLine(c[8][1], c[8][2], c[5][1], c[5][2], 2, 0xFF4682B4)
                renderDrawLine(c[1][1], c[1][2], c[5][1], c[5][2], 2, 0xFF4682B4)
                renderDrawLine(c[2][1], c[2][2], c[8][1], c[8][2], 2, 0xFF4682B4)
                renderDrawLine(c[3][1], c[3][2], c[7][1], c[7][2], 2, 0xFF4682B4)
                renderDrawLine(c[4][1], c[4][2], c[6][1], c[6][2], 2, 0xFF4682B4)
                renderDrawPolygon(X/2, Y/2, 10, 10, 7, 5, 0xFF4682B4)
                local posX2, posY2 = convert3DCoordsToScreen(x2, y2, z2)
                renderDrawLine(X/2, Y/2, posX2, posY2, 2.0, 0xFF4682B4)
                renderDrawPolygon(posX2, posY2, 10, 10, 40, 0, 0xFF4682B4)
                local distance = math.floor(getDistanceBetweenCoords3d(x, y, z, x2, y2, z2))
                renderFontDrawTextAlign(font, string.format('%s[%d]', playerNick, playerId),posX2, posY2-30, 0xFF4682B4, 2)
                renderFontDrawTextAlign(font, string.format('Дистанция: %s', distance),X/2, Y/2+210, 0xFF4682B4, 2)
                renderFontDrawTextAlign(font, 'R - OnFoot Rvanka\nX - Incar Rvanka',X/2+300, Y/2-30, 0xFF4682B4, 1)
                if isKeyJustPressed(VK_1) then
                    sampSendChat('/re '..playerId)
                end
                if isKeyJustPressed(VK_2) then
                    sampSendChat('/frem '..playerId)
                end
                if isKeyJustPressed(VK_3) then
                    sampSendChat('/spawn '..playerId)
                end
                if isKeyJustPressed(VK_4) then
                    sampSendChat('/sethp '..playerId..' 100')
                end
                if isKeyJustPressed(VK_5) then
                    sampSendChat('/gethere '..playerId)
                end
            end
        end  
    end
end
 

Stepaa

Новичок
13
3
#IMGUI
Как можно в обычной imgui.button сделать TEXT более жирнее с рабочим fa.icon
способ реализовать defolt с PushFont тогда не работает fa.icon (?).
 

Stepaa

Новичок
13
3
#IMGUI
Ребята , подскажите как работать с togglebutton
как мне её включить
Screenshot_149.png
 

MLycoris

Режим чтения
Проверенный
1,820
1,859
#IMGUI
Ребята , подскажите как работать с togglebutton
как мне её включить
Посмотреть вложение 213587
Посмотри тут примерчик с radiobutton
 

FixZer

Активный
126
36
Как вывести название сервера в mimgui окно?
Lua:
local imgui = require 'mimgui' -- Подключаем саму библиотеку

local newFrame = imgui.OnFrame( --[[Сама функция создания фрейма, их может быть сколько вашей душе угодно.
                                    Обратите внимание, что в mimgui рекомендуется создавать отдельный
                                    фрейм для каждого окна, однако это не является обязательным.]]
    function() return true end, -- Определяет, выполняется/отображается ли текущий фрейм.
    function(player)            --[[Сама область, в которой уже будем рисовать элементы.
                                    В функцию в качестве первой переменной передаются список функций
                                    для взаимодействия с локальным игроком и рядом нескольких возможностей.]]
        imgui.Begin("Main Window")  -- Создаём новое окно с заголовком 'Main Window'
        imgui.Text("Вы играете на "..sampGetCurrentServerName().."!") -- Добавляем туда текст
        imgui.End()                 -- Объявляем конец данного окна
    end
)
 
Последнее редактирование:
  • Нравится
Реакции: tsunamiqq

tsunamiqq

Участник
428
16
1. Как сделать сохранение темы?
2. Как сделать в ColoredRadioButtonBool выбор цвета самостоятельно, не только тот, который прописал в "local back", а к примеру imgui.ColoredRadioButtonBool('Text', bool, imgui.ImVec(color))
Попытался сделать таким способом сохранение, не получилось.

Lua:
--Библиотеки

--Вне окна
local inicfg = require('inicfg')
local directIni = 'Script.ini'
local mainIni = inicfg.load(inicfg.load({
    settings = {
        radioButtonColorRed = false
    }
}, directIni))
inicfg.save(mainIni, directIni)
--Вне окна
local settings = {
    radioButtonColorRed = new.int(mainIni.settings.radioButtonColorRed)
}

--В окне
if imgui.ColoredRadioButtonBool('##colorRed', settings.radioButtonColorRed[0]) then
    Theme(0)
    mainIni.settings.radioButtonColorRed = not mainIni.settings.radioButtonColorRed
    settings.radioButtonColorRed[0] = mainIni.settings.radioButtonColorRed
end

--Вне окна
function imgui.ColoredRadioButtonBool(label, state, color)
    local back = imgui.ImVec4(1, 0, 0, 1)
    imgui.PushStyleColor(imgui.Col.CheckMark, back)
    imgui.PushStyleColor(imgui.Col.FrameBg, back)
    imgui.PushStyleColor(imgui.Col.FrameBgActive, back)
    imgui.PushStyleColor(imgui.Col.FrameBgHovered, back)
    local radioButton = imgui.RadioButtonBool(label, state)
    imgui.PopStyleColor(4)
    return radioButton
end

--Вне окна
function Theme(id, color, chroma_multiplier, accurate_shades)
    local vec2, vec4 = imgui.ImVec2, imgui.ImVec4
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local flags = imgui.Col
 
    do -- style
        --==[ STYLE ]==--
        imgui.GetStyle().WindowPadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().FramePadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemSpacing = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(2, 2)
        imgui.GetStyle().TouchExtraPadding = imgui.ImVec2(0, 0)
        imgui.GetStyle().IndentSpacing = 0
        imgui.GetStyle().ScrollbarSize = 10
        imgui.GetStyle().GrabMinSize = 10
        --==[ ROUNDING ]==--
        imgui.GetStyle().WindowRounding = 8
        imgui.GetStyle().ChildRounding = 8
        imgui.GetStyle().FrameRounding = 5
        imgui.GetStyle().PopupRounding = 8
        imgui.GetStyle().ScrollbarRounding = 8
        imgui.GetStyle().GrabRounding = 8
        imgui.GetStyle().TabRounding = 8
        --==[ ALIGN ]==--
        imgui.GetStyle().WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().SelectableTextAlign = imgui.ImVec2(0.5, 0.5)
    end
    local palette = monet.buildColors(id, color, chroma_multiplier, accurate_shades)
    if id == 0 then -- colors
        colors[imgui.Col.WindowBg] = imgui.ImVec4(0.14, 0.12, 0.16, 1.00)
        colors[imgui.Col.ChildBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.00)
        colors[imgui.Col.PopupBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.Border] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.BorderShadow] = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
        colors[imgui.Col.FrameBg] = imgui.ImVec4(0.28, 0.27, 0.27, 0.28)
        colors[imgui.Col.FrameBgHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 0.68)
        colors[imgui.Col.FrameBgActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.TitleBg] = imgui.ImVec4(0.41, 0.19, 0.63, 0.45)
        colors[imgui.Col.TitleBgCollapsed] = imgui.ImVec4(0.41, 0.19, 0.63, 0.35)
        colors[imgui.Col.TitleBgActive] = imgui.ImVec4(0.41, 0.19, 0.63, 0.78)
        colors[imgui.Col.MenuBarBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.57)
        colors[imgui.Col.ScrollbarBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrab] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.CheckMark] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.SliderGrab] = imgui.ImVec4(0.41, 0.19, 0.63, 0.24)
        colors[imgui.Col.SliderGrabActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.Button] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ButtonHovered] = imgui.ImVec4(1, 0, 0.07, 1)
        colors[imgui.Col.ButtonActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.8)
        colors[imgui.Col.Header] = imgui.ImVec4(0.41, 0.19, 0.63, 0.76)
        colors[imgui.Col.HeaderHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 0.86)
        colors[imgui.Col.HeaderActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.ResizeGrip] = imgui.ImVec4(0.41, 0.19, 0.63, 0.20)
        colors[imgui.Col.ResizeGripHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 0.78)
        colors[imgui.Col.ResizeGripActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.PlotLines] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotLinesHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.PlotHistogram] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotHistogramHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.TextSelectedBg] = imgui.ImVec4(0.41, 0.19, 0.63, 0.43)
      
       COLOR_SELECT = palette.accent1.color_100
    end
 end
 
  • Bug
Реакции: Лебiгович

Yans

Активный
190
32
Как сделать так чтобы парсер останавливался при повторном нажатии?

Парсер:
require "lib.moonloader"
local delay = 1500

function main()
    while not isSampAvailable() do wait (0) end
    while true do
        wait (0)
        if wasKeyPressed(VK_DECIMAL) then
            for i = 0, 300 do wait(delay)
                sampSendPickedUpPickup(i)
            end
        end
    end
end
 
  • Bug
Реакции: Лебiгович

Лебiгович

Известный
877
239
1. Как сделать сохранение темы?
2. Как сделать в ColoredRadioButtonBool выбор цвета самостоятельно, не только тот, который прописал в "local back", а к примеру imgui.ColoredRadioButtonBool('Text', bool, imgui.ImVec(color))
Попытался сделать таким способом сохранение, не получилось.

Lua:
--Библиотеки

--Вне окна
local inicfg = require('inicfg')
local directIni = 'Script.ini'
local mainIni = inicfg.load(inicfg.load({
    settings = {
        radioButtonColorRed = false
    }
}, directIni))
inicfg.save(mainIni, directIni)
--Вне окна
local settings = {
    radioButtonColorRed = new.int(mainIni.settings.radioButtonColorRed)
}

--В окне
if imgui.ColoredRadioButtonBool('##colorRed', settings.radioButtonColorRed[0]) then
    Theme(0)
    mainIni.settings.radioButtonColorRed = not mainIni.settings.radioButtonColorRed
    settings.radioButtonColorRed[0] = mainIni.settings.radioButtonColorRed
end

--Вне окна
function imgui.ColoredRadioButtonBool(label, state, color)
    local back = imgui.ImVec4(1, 0, 0, 1)
    imgui.PushStyleColor(imgui.Col.CheckMark, back)
    imgui.PushStyleColor(imgui.Col.FrameBg, back)
    imgui.PushStyleColor(imgui.Col.FrameBgActive, back)
    imgui.PushStyleColor(imgui.Col.FrameBgHovered, back)
    local radioButton = imgui.RadioButtonBool(label, state)
    imgui.PopStyleColor(4)
    return radioButton
end

--Вне окна
function Theme(id, color, chroma_multiplier, accurate_shades)
    local vec2, vec4 = imgui.ImVec2, imgui.ImVec4
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local flags = imgui.Col
 
    do -- style
        --==[ STYLE ]==--
        imgui.GetStyle().WindowPadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().FramePadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemSpacing = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(2, 2)
        imgui.GetStyle().TouchExtraPadding = imgui.ImVec2(0, 0)
        imgui.GetStyle().IndentSpacing = 0
        imgui.GetStyle().ScrollbarSize = 10
        imgui.GetStyle().GrabMinSize = 10
        --==[ ROUNDING ]==--
        imgui.GetStyle().WindowRounding = 8
        imgui.GetStyle().ChildRounding = 8
        imgui.GetStyle().FrameRounding = 5
        imgui.GetStyle().PopupRounding = 8
        imgui.GetStyle().ScrollbarRounding = 8
        imgui.GetStyle().GrabRounding = 8
        imgui.GetStyle().TabRounding = 8
        --==[ ALIGN ]==--
        imgui.GetStyle().WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().SelectableTextAlign = imgui.ImVec2(0.5, 0.5)
    end
    local palette = monet.buildColors(id, color, chroma_multiplier, accurate_shades)
    if id == 0 then -- colors
        colors[imgui.Col.WindowBg] = imgui.ImVec4(0.14, 0.12, 0.16, 1.00)
        colors[imgui.Col.ChildBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.00)
        colors[imgui.Col.PopupBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.Border] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.BorderShadow] = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
        colors[imgui.Col.FrameBg] = imgui.ImVec4(0.28, 0.27, 0.27, 0.28)
        colors[imgui.Col.FrameBgHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 0.68)
        colors[imgui.Col.FrameBgActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.TitleBg] = imgui.ImVec4(0.41, 0.19, 0.63, 0.45)
        colors[imgui.Col.TitleBgCollapsed] = imgui.ImVec4(0.41, 0.19, 0.63, 0.35)
        colors[imgui.Col.TitleBgActive] = imgui.ImVec4(0.41, 0.19, 0.63, 0.78)
        colors[imgui.Col.MenuBarBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.57)
        colors[imgui.Col.ScrollbarBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrab] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.CheckMark] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.SliderGrab] = imgui.ImVec4(0.41, 0.19, 0.63, 0.24)
        colors[imgui.Col.SliderGrabActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.Button] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ButtonHovered] = imgui.ImVec4(1, 0, 0.07, 1)
        colors[imgui.Col.ButtonActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.8)
        colors[imgui.Col.Header] = imgui.ImVec4(0.41, 0.19, 0.63, 0.76)
        colors[imgui.Col.HeaderHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 0.86)
        colors[imgui.Col.HeaderActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.ResizeGrip] = imgui.ImVec4(0.41, 0.19, 0.63, 0.20)
        colors[imgui.Col.ResizeGripHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 0.78)
        colors[imgui.Col.ResizeGripActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.PlotLines] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotLinesHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.PlotHistogram] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotHistogramHovered] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.TextSelectedBg] = imgui.ImVec4(0.41, 0.19, 0.63, 0.43)
     
       COLOR_SELECT = palette.accent1.color_100
    end
 end
Lua:
-- Библиотеки
local inicfg = require('inicfg')
local directIni = 'Script.ini'
local mainIni = inicfg.load(nil, directIni)
mainIni.settings = mainIni.settings or {}
mainIni.settings.radioButtonColorRed = mainIni.settings.radioButtonColorRed or false
mainIni.settings.selectedTheme = mainIni.settings.selectedTheme or 0
inicfg.save(mainIni, directIni)

-- В окне
local COLOR_SELECT = imgui.ImVec4(1, 0, 0, 1) -- Задай начальный цвет
if imgui.ColoredRadioButtonBool('##colorRed', settings.radioButtonColorRed[0], COLOR_SELECT) then
    Theme(settings.selectedTheme[0], COLOR_SELECT)
    mainIni.settings.radioButtonColorRed = not mainIni.settings.radioButtonColorRed
    settings.radioButtonColorRed[0] = mainIni.settings.radioButtonColorRed
end

-- Вне окна
function Theme(id, color, chroma_multiplier, accurate_shades)
    -- ... твой текущий код для изменения стиля и цветов ...

    if id == 0 then -- colors
        -- ... твой текущий код для установки цветов ...

        COLOR_SELECT = color
    end
end

-- Вне окна
function imgui.ColoredRadioButtonBool(label, state, color)
    imgui.PushStyleColor(imgui.Col.CheckMark, color)
    imgui.PushStyleColor(imgui.Col.FrameBg, color)
    imgui.PushStyleColor(imgui.Col.FrameBgActive, color)
    imgui.PushStyleColor(imgui.Col.FrameBgHovered, color)
    local radioButton = imgui.RadioButtonBool(label, state)
    imgui.PopStyleColor(4)
    return radioButton
end

-- Вне окна
function imgui.Combo(label, current_item, items)
    local changed, item = imgui.Combo(label, current_item[0], items)
    if changed then
        current_item[0] = item
    end
    return changed
end

-- Вне окна
local settings = {
    radioButtonColorRed = new.int(mainIni.settings.radioButtonColorRed),
    selectedTheme = new.int(mainIni.settings.selectedTheme)
}

попробуй

Как сделать так чтобы парсер останавливался при повторном нажатии?

Парсер:
require "lib.moonloader"
local delay = 1500

function main()
    while not isSampAvailable() do wait (0) end
    while true do
        wait (0)
        if wasKeyPressed(VK_DECIMAL) then
            for i = 0, 300 do wait(delay)
                sampSendPickedUpPickup(i)
            end
        end
    end
end
Lua:
require "lib.moonloader"
local delay = 1500
local isParsing = false

function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        if wasKeyPressed(VK_DECIMAL) then
            isParsing = not isParsing -- Переключаем состояние парсера при нажатии клавиши
            if isParsing then
                print("Parser started")
                while isParsing do
                    wait(delay)
                    for i = 0, 300 do
                        sampSendPickedUpPickup(i)
                    end
                end
                print("Parser stopped")
            end
        end
    end
end

был добавлен флаг isParsing, который контролирует, активен ли парсер или нет. При нажатии клавиши десятичной точки (VK_DECIMAL), флаг будет переключаться между состояниями "парсер активен" и "парсер неактивен". Если парсер активен, он будет выполнять цикл, отправляющий данные. Когда флаг isParsing становится false, парсер остановится.
 

Yans

Активный
190
32
попробуй


Lua:
require "lib.moonloader"
local delay = 1500
local isParsing = false

function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        if wasKeyPressed(VK_DECIMAL) then
            isParsing = not isParsing -- Переключаем состояние парсера при нажатии клавиши
            if isParsing then
                print("Parser started")
                while isParsing do
                    wait(delay)
                    for i = 0, 300 do
                        sampSendPickedUpPickup(i)
                    end
                end
                print("Parser stopped")
            end
        end
    end
end

был добавлен флаг isParsing, который контролирует, активен ли парсер или нет. При нажатии клавиши десятичной точки (VK_DECIMAL), флаг будет переключаться между состояниями "парсер активен" и "парсер неактивен". Если парсер активен, он будет выполнять цикл, отправляющий данные. Когда флаг isParsing становится false, парсер остановится.

Не реагирует на нажатие после старта и поднимает только 0 пикап