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

chapo

tg/inst: @moujeek
Всефорумный модератор
9,240
12,659
Спасибо большое. А как убрать кнопочки + и - у inputInt?
хз, можешь сам поискать:
Lua:
-- imgui enums
imgui.WindowFlags = {
    NoTitleBar = 1,
    NoResize = 2,
    NoMove = 4,
    NoScrollbar = 8,
    NoScrollWithMouse = 16,
    NoCollapse = 32,
    AlwaysAutoResize = 64,
    ShowBorders = 128,
    NoSavedSettings = 256,
    NoInputs = 512,
    MenuBar = 1024,
    HorizontalScrollbar = 2048,
    NoFocusOnAppearing = 4096,
    NoBringToFrontOnFocus = 8192,
    AlwaysVerticalScrollbar = 16384,
    AlwaysHorizontalScrollbar = 32768,
    AlwaysUseWindowPadding = 65536,
}

imgui.InputTextFlags = {
    CharsDecimal = 1,
    CharsHexadecimal = 2,
    CharsUppercase = 4,
    CharsNoBlank = 8,
    AutoSelectAll = 16,
    EnterReturnsTrue = 32,
    CallbackCompletion = 64,
    CallbackHistory = 128,
    CallbackAlways = 256,
    CallbackCharFilter = 512,
    AllowTabInput = 1024,
    CtrlEnterForNewLine = 2048,
    NoHorizontalScroll = 4096,
    AlwaysInsertMode = 8192,
    ReadOnly = 16384,
    Password = 32768,
}

imgui.TreeNodeFlags = {
    Selected = 1,
    Framed = 2,
    AllowOverlapMode = 4,
    NoTreePushOnOpen = 8,
    NoAutoOpenOnLog = 16,
    DefaultOpen = 32,
    OpenOnDoubleClick = 64,
    OpenOnArrow = 128,
    Leaf = 256,
    Bullet = 512,
    FramePadding = 1024,
    CollapsingHeader = 18,
}

imgui.SelectableFlags = {
    DontClosePopups = 1,
    SpanAllColumns = 2,
    AllowDoubleClick = 4,
}

imgui.HoveredFlags = {
    Default = 0,
    AllowWhenBlockedByPopup = 1,
    AllowWhenBlockedByActiveItem = 4,
    AllowWhenOverlapped = 8,
    RectOnly = 13,
}

imgui.Key = {
    Tab        = 0 + 1,
    LeftArrow  = 1 + 1,
    RightArrow = 2 + 1,
    UpArrow    = 3 + 1,
    DownArrow  = 4 + 1,
    PageUp     = 5 + 1,
    PageDown   = 6 + 1,
    Home       = 7 + 1,
    End        = 8 + 1,
    Delete     = 9 + 1,
    Backspace  = 10 + 1,
    Enter      = 11 + 1,
    Escape     = 12 + 1,
    A          = 13 + 1,
    C          = 14 + 1,
    V          = 15 + 1,
    X          = 16 + 1,
    Y          = 17 + 1,
    Z          = 18 + 1,
}

imgui.Col = {
    Text                    = 0 + 1,
    TextDisabled            = 1 + 1,
    WindowBg                = 2 + 1,
    ChildWindowBg           = 3 + 1,
    PopupBg                 = 4 + 1,
    Border                  = 5 + 1,
    BorderShadow            = 6 + 1,
    FrameBg                 = 7 + 1,
    FrameBgHovered          = 8 + 1,
    FrameBgActive           = 9 + 1,
    TitleBg                 = 10 + 1,
    TitleBgActive           = 11 + 1,
    TitleBgCollapsed        = 12 + 1,
    MenuBarBg               = 13 + 1,
    ScrollbarBg             = 14 + 1,
    ScrollbarGrab           = 15 + 1,
    ScrollbarGrabHovered    = 16 + 1,
    ScrollbarGrabActive     = 17 + 1,
    ComboBg                 = 18 + 1,
    CheckMark               = 19 + 1,
    SliderGrab              = 20 + 1,
    SliderGrabActive        = 21 + 1,
    Button                  = 22 + 1,
    ButtonHovered           = 23 + 1,
    ButtonActive            = 24 + 1,
    Header                  = 25 + 1,
    HeaderHovered           = 26 + 1,
    HeaderActive            = 27 + 1,
    Separator               = 28 + 1,
    SeparatorHovered        = 29 + 1,
    SeparatorActive         = 30 + 1,
    ResizeGrip              = 31 + 1,
    ResizeGripHovered       = 32 + 1,
    ResizeGripActive        = 33 + 1,
    CloseButton             = 34 + 1,
    CloseButtonHovered      = 35 + 1,
    CloseButtonActive       = 36 + 1,
    PlotLines               = 37 + 1,
    PlotLinesHovered        = 38 + 1,
    PlotHistogram           = 39 + 1,
    PlotHistogramHovered    = 40 + 1,
    TextSelectedBg          = 41 + 1,
    ModalWindowDarkening    = 42 + 1,
}

imgui.StyleVar = {
    Alpha = 0,
    WindowPadding = 1,
    WindowRounding = 2,
    WindowMinSize = 3,
    ChildWindowRounding = 4,
    FramePadding = 5,
    FrameRounding = 6,
    ItemSpacing = 7,
    ItemInnerSpacing = 8,
    IndentSpacing = 9,
    GrabMinSize = 10,
    ButtonTextAlign = 11,
}

imgui.ColorEditFlags = {
    NoAlpha = 2,
    NoPicker = 4,
    NoOptions = 8,
    NoSmallPreview = 16,
    NoInputs = 32,
    NoTooltip = 64,
    NoLabel = 128,
    NoSidePreview = 256,
    AlphaBar = 512,
    AlphaPreview = 1024,
    AlphaPreviewHalf = 2048,
    HDR = 4096,
    RGB = 8192,
    HSV = 16384,
    HEX = 32768,
    Uint8 = 65536,
    Float = 131072,
    PickerHueBar = 262144,
    PickerHueWheel = 524288,
    _InputsMask = 57344,
    _DataTypeMask = 196608,
    _PickerMask = 786432,
    _OptionsDefault = 335872,
}

imgui.MouseCursor = {
    None = -1,
    Arrow = 0,
    TextInput = 1,
    Move = 2,
    ResizeNS = 3,
    ResizeEW = 4,
    ResizeNESW = 5,
    ResizeNWSE = 6,
}

imgui.Cond = {
    Always = 1,
    Once = 2,
    FirstUseEver = 4,
    Appearing = 8,
}
 

W1ll04eison

Известный
330
19
У меня имгуи окно включается по следующей штуке:
Lua:
if imgui.ToggleButton(u8'Инфобар', activeinfobar) then
    infobar.v = not infobar.v
end
Если ToggleButton = true, то и окно imgui показывается, но после перезагрузки скрипта, если ToggleButton = true окно имгуи не включается

Подскажите, как исправить, что бы если ToggleButton = true то даже после перезагрузки скрипта окно имгуи само включалось?
 

Adrian G.

Известный
Проверенный
516
452
У меня имгуи окно включается по следующей штуке:
Lua:
if imgui.ToggleButton(u8'Инфобар', activeinfobar) then
    infobar.v = not infobar.v
end
Если ToggleButton = true, то и окно imgui показывается, но после перезагрузки скрипта, если ToggleButton = true окно имгуи не включается

Подскажите, как исправить, что бы если ToggleButton = true то даже после перезагрузки скрипта окно имгуи само включалось?
Так попробуй
Lua:
if imgui.ToggleButton(u8'Инфобар', activeinfobar) then
    infobar.v = true
else
    infobar.v = false
end
 

Tol4ek

Известный
216
56
У меня имгуи окно включается по следующей штуке:
Lua:
if imgui.ToggleButton(u8'Инфобар', activeinfobar) then
    infobar.v = not infobar.v
end
Если ToggleButton = true, то и окно imgui показывается, но после перезагрузки скрипта, если ToggleButton = true окно имгуи не включается

Подскажите, как исправить, что бы если ToggleButton = true то даже после перезагрузки скрипта окно имгуи само включалось?
Lua:
imgui.ToggleButton(u8'Инфобар', activeinfobar)

infobar.v = activeinfobar.v
Скорее всего, вот так
 

W1ll04eison

Известный
330
19
Lua:
imgui.ToggleButton(u8'Инфобар', activeinfobar)

infobar.v = activeinfobar.v
Скорее всего, вот так
У меня есть основное имгуи окно(оно включается на кнопку F2), при нажатии togglebutton включается второе(инфобар), после перезагрузки скрипта, если togglebutton = true инфобар автоматически не включается, я нажимаю F2 и включаеться

p.s не работает, как ты написал
 

Adrian G.

Известный
Проверенный
516
452
У меня есть основное имгуи окно(оно включается на кнопку F2), при нажатии togglebutton включается второе(инфобар), после перезагрузки скрипта, если togglebutton = true инфобар автоматически не включается, я нажимаю F2 и включаеться

p.s не работает, как ты написал
Код кинь, проще будет
 

W1ll04eison

Известный
330
19
Код кинь, проще будет
Кнопка включения основного imgui окна:

Lua:
        if wasKeyPressed(VK_F2) then

            array.test_window_state.v = not array.test_window_state.v
            imgui.Process = array.test_window_state.v
        end
Команда включения основного imgui окна:
Lua:
function cmd_fhelp(arg)
    array.test_window_state.v = not array.test_window_state.v
    imgui.Process = array.test_window_state.v
end

p.s в основном imgui окне, еще одна кнопка, для включения imgui окна с настройками
Вот кнопка для включения imgui окна " настройки":

Lua:
                imgui.SetCursorPos(imgui.ImVec2(10, 185))
                imgui.PushStyleVar(imgui.StyleVar.ButtonTextAlign , imgui.ImVec2(0.5, 0.5))
                if imgui.Button("" ..fa.ICON_ADDRESS_CARD.. u8"  Домой", imgui.ImVec2(330, 40)) then
                    array.test2_window_state.v = not array.test2_window_state.v
                    imgui.Process = array.test2_window_state.v
                end



Функция, если все imgui окна не активны, то имгуи процесс = false:
Lua:
    if not array.orpo_active_state.v and not array.test_window_state.v and not array.test2_window_state.v and not array.test3_window_state.v and not array.test4_window_state.v and not window.v and not mainMenu.v and not infobar.v then
        imgui.Process = false
    end

Вот togglebutton включения инфобара(находиться в imgui окне "настройки"):

Lua:
                    if imgui.ToggleButton(u8'Инфобар', activeinfobar) then
                        infobar.v = not infobar.v
                    end

Вот непосредственно сам инфобар:

Lua:
    if infobar.v then

        _, myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
        myName = sampGetPlayerNickname(myID)
        namer = string.gsub(sampGetPlayerNickname(myID), '_', ' ')
        lmyping = sampGetPlayerPing(myID)

        imgui.ShowCursor = false
        --local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(posX, posY), imgui.Cond.Always)
        imgui.SetNextWindowSize(imgui.ImVec2(250, 100), imgui.Cond.FirstUseEver)
        imgui.PushStyleColor(imgui.Col.WindowBg, imgui.ImVec4(color_back.v[1], color_back.v[2], color_back.v[3], color_back.v[4]))
        themes.SwitchColorTheme(15)
        --imgui.GetStyle(50.0)
        imgui.Begin(u8"", _, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove)
     
        --+ imgui.WindowFlags.NoResize + imgui.WindowFlags.NoTitleBar

        imgui.Text('' ..fa.ICON_ADDRESS_CARD_O.. ' ' ..myName.. ' [' ..myID.. ']')
        imgui.Text('' ..fa.ICON_WIFI.. u8'Пинг: ' ..lmyping)
        imgui.Text('' ..fa.ICON_MAP_MARKER.. '')
        imgui.SameLine()
        imgui.Text(u8(kvadrat()))
        imgui.Text('' ..os.date('%x | %X').. '')


        imgui.End()
        imgui.PopStyleColor()
     

    end

Проблема тут в двух вещах:

1) когда нажимаю F2 открываться основное imgui окно, затем открываю imgui окно "настройки"(у меня эта кнопка называется домой), открывается окно "настройки", там я с помощьюtogglebutton включаю инфобар, потом если прописать команду /fhelp или нажать F2 закрываеться основное окно, окно настроек и сам итнфобар

2) после перезагрузки скрипта, елси togglebutton = true, инфобар сам по себе не включается, приходится нажимать F2 - активируеться основное меню и инфобар, но если с ново нажать F2 то все выключается



p.s у меня просто более 3.000 строк, скинул то что связанно с этим
 
Последнее редактирование:

Alkoigel

Участник
113
13
Полностью код покажи, в коде выше все верно, они не мешают друг другу.
Проблема с окном которое на Ф4 открывает.
Lua:
require "lib.moonloader" -- подключение библиотеки
local dlstatus = require('moonloader').download_statuslocal
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
local se = require 'lib.samp.events'
local ids = -1
encoding.default = 'CP1251'
u8 = encoding.UTF8

local tag = "[My First Script]:" -- локальная переменная
local label = 0
local main_color = 0x5A90CE
local main_color_text = "{5A90CE}"
local white_color = "{FFFFFF}"
local arr_cheat = {"30 Aimbot", "30 WallHack", "10 Spread", "15 auto+c", "30 Saim", "30 DMG", "10 ews", "10 Provo na SK", "10 Fly", "20 AirBreak", "15 Flycar", "10 Speedhack"}

local main_window_state = imgui.ImBool(false)
local secondary_window_state = imgui.ImBool(false)

local text_buffer = imgui.ImBuffer(256)


latest = "1.0.1"
script_version ("1.0.1")

-- чекбоксы
    local checked_NakNumber        = imgui.ImInt(1)
--

-- радиокнопки
    local checked_band        = imgui.ImInt(1)
    local checked_jail        = imgui.ImInt(1)
--

--комбобоксы
    local combo_select         =imgui.ImInt(0)
--

local sw, sh = getScreenResolution()

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

    imgui.GetStyle().WindowPadding = imgui.ImVec2(8, 8)
    imgui.GetStyle().WindowRounding = 0.5
    imgui.GetStyle().FramePadding = imgui.ImVec2(5, 3)
    imgui.GetStyle().ItemSpacing = imgui.ImVec2(4, 4)
    imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(5, 5)
    imgui.GetStyle().IndentSpacing = 9.0
    imgui.GetStyle().ScrollbarSize = 17.0
    imgui.GetStyle().ScrollbarRounding = 16.0
    imgui.GetStyle().GrabMinSize = 7.0
    imgui.GetStyle().GrabRounding = 15.0
    imgui.GetStyle().ChildWindowRounding = 10.0
    imgui.GetStyle().FrameRounding = 7.0

    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Button]                 = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.ButtonHovered]          = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.06, 0.53, 0.98, 1.00)
    colors[clr.TitleBg]                = ImVec4(0.04, 0.04, 0.04, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.16, 0.29, 0.48, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)-- (0.1, 0.9, 0.1, 1.0)
    colors[clr.CloseButtonHovered]     = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]      = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.26, 0.59, 0.98, 0.35)
    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.FrameBg]                = ImVec4(0.16, 0.29, 0.48, 0.54)
    colors[clr.FrameBgHovered]         = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.FrameBgActive]          = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.MenuBarBg]              = ImVec4(0.14, 0.14, 0.14, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]          = ImVec4(0.31, 0.31, 0.31, 1.00)
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.CheckMark]              = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.Header]                 = ImVec4(0.26, 0.59, 0.98, 0.31)
    colors[clr.HeaderHovered]          = ImVec4(0.26, 0.59, 0.98, 0.80)
    colors[clr.HeaderActive]           = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.24, 0.52, 0.88, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.26, 0.59, 0.98, 1.00)
end
SetStyle()

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand("update", cmd_update)
    sampRegisterChatCommand("imgui", cmd_imgui)
    sampRegisterChatCommand("imgui2", cmd_imgui2)
    sampRegisterChatCommand("1", cmd_1)
    sampRegisterChatCommand("2", cmd_2)
    sampRegisterChatCommand("3", cmd_3)
    sampRegisterChatCommand("clans", cmd_clans)
    sampRegisterChatCommand("grul", cmd_grul)
    sampRegisterChatCommand('testo222', cmd_testo222)
    autoupdate("https://raw.githubusercontent.com/ValeriiVavilin/test/main/update.json", '['..string.upper(thisScript().name)..']: ', "http://vk.com/alkoigel")
    thread = lua_thread.create_suspended(thread_ghetto)

    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(rid)

    imgui.Process = false
    --sampAddChatMessage("Скрипт imgui перезагружен", -1)

    while true do
        wait(0)

        if isKeyJustPressed(VK_F3) then
            cmd_imgui()
        end
        if isKeyJustPressed(VK_F4) then
            cmd_imgui2()
        end

        if main_window_state.v == false then
            imgui.Process = false
        end
        -- Блок выполняющийся бесконечно (пока самп активен)

    end
end

function cmd_testo222(arg)
    sampAddChatMessage("Получилось, версия скрипта: {FFFF00}1.0.7", -1)
end
function se.onTogglePlayerSpectating(state)
    if state then
        specc = true
    else
        specc = false
    end
end

function se.onSpectatePlayer(id, type)
    if specc then
        ids = id
    end
end

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

function cmd_imgui2(arg)
    secondary_window_state.v = not secondary_window_state.v
    imgui.Process = secondary_window_state.v
end

function imgui.OnDrawFrame()
    imgui.SwitchContext()
    local colors = imgui.GetStyle().Colors;
    local icol = imgui.Col
    local ImVec4 = imgui.ImVec4

    imgui.GetStyle().WindowPadding = imgui.ImVec2(10, 10)
    imgui.GetStyle().WindowRounding = 10.0
    imgui.GetStyle().FramePadding = imgui.ImVec2(5, 4)
    imgui.GetStyle().ItemSpacing = imgui.ImVec2(4, 4)
    imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(5, 5)
    imgui.GetStyle().IndentSpacing = 9.0
    imgui.GetStyle().ScrollbarSize = 17.0
    imgui.GetStyle().ScrollbarRounding = 20.0
    imgui.GetStyle().GrabMinSize = 7.0
    imgui.GetStyle().GrabRounding = 20.0
    imgui.GetStyle().ChildWindowRounding = 6.0
    imgui.GetStyle().FrameRounding = 20.0

    colors[icol.Text]                   = ImVec4(0.11, 0.11, 0.11, 1.00);
    colors[icol.TextDisabled]           = ImVec4(0.60, 0.60, 0.60, 1.00);
    colors[icol.WindowBg]               = ImVec4(0.90, 0.90, 0.90, 1.00);
    colors[icol.ChildWindowBg]          = ImVec4(0.13, 0.13, 0.13, 1.00);
    colors[icol.PopupBg]                = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.Border]                 = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.BorderShadow]           = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.FrameBg]                = ImVec4(0.26, 0.46, 0.82, 0.59);
    colors[icol.FrameBgHovered]         = ImVec4(0.26, 0.46, 0.82, 0.88);
    colors[icol.FrameBgActive]          = ImVec4(0.28, 0.53, 1.00, 1.00);
    colors[icol.TitleBg]                = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.TitleBgActive]          = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.TitleBgCollapsed]       = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.MenuBarBg]              = ImVec4(0.26, 0.46, 0.82, 0.75);
    colors[icol.ScrollbarBg]            = ImVec4(0.11, 0.11, 0.11, 1.00);
    colors[icol.ScrollbarGrab]          = ImVec4(0.26, 0.46, 0.82, 0.68);
    colors[icol.ScrollbarGrabHovered]   = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.ScrollbarGrabActive]    = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.ComboBg]                = ImVec4(0.26, 0.46, 0.82, 0.79);
    colors[icol.CheckMark]              = ImVec4(0.000, 0.000, 0.000, 1.000)
    colors[icol.SliderGrab]             = ImVec4(0.263, 0.459, 0.824, 1.000)
    colors[icol.SliderGrabActive]       = ImVec4(0.20, 0.20, 0.20, 1.00);
    colors[icol.Button]                 = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.ButtonHovered]          = ImVec4(0.26, 0.46, 0.82, 0.59);
    colors[icol.ButtonActive]           = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.Header]                 = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.HeaderHovered]          = ImVec4(0.26, 0.46, 0.82, 0.74);
    colors[icol.HeaderActive]           = ImVec4(0.26, 0.46, 0.82, 1.00);
    colors[icol.Separator]              = ImVec4(0.37, 0.37, 0.37, 1.00);
    colors[icol.SeparatorHovered]       = ImVec4(0.60, 0.60, 0.70, 1.00);
    colors[icol.SeparatorActive]        = ImVec4(0.70, 0.70, 0.90, 1.00);
    colors[icol.ResizeGrip]             = ImVec4(1.00, 1.00, 1.00, 0.30);
    colors[icol.ResizeGripHovered]      = ImVec4(1.00, 1.00, 1.00, 0.60);
    colors[icol.ResizeGripActive]       = ImVec4(1.00, 1.00, 1.00, 0.90);
    colors[icol.CloseButton]            = ImVec4(0.90, 0.90, 0.90, 1.00);
    colors[icol.CloseButtonHovered]     = ImVec4(0.50, 0.50, 0.50, 0.60);
    colors[icol.CloseButtonActive]      = ImVec4(0.35, 0.35, 0.35, 1.00);
    colors[icol.PlotLines]              = ImVec4(1.00, 1.00, 1.00, 1.00);
    colors[icol.PlotLinesHovered]       = ImVec4(0.90, 0.70, 0.00, 1.00);
    colors[icol.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00);
    colors[icol.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00);
    colors[icol.TextSelectedBg]         = ImVec4(0.00, 0.00, 1.00, 0.35);
    colors[icol.ModalWindowDarkening]   = ImVec4(0.20, 0.20, 0.20, 0.35);
    if not main_window_state.v and not secondary_window_state.v then
        imgui.Process = false
    end
    
    if main_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(500, 320), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

        imgui.Begin("Ghetto Helper", main_window_state) -- название окна

        imgui.RadioButton(u8"Грув", checked_band, 2)            -- название круга, переменная,
        imgui.SameLine()
        imgui.RadioButton(u8"Баллас", checked_band, 3)            -- название круга, переменная,
        imgui.SameLine()
        imgui.RadioButton(u8"Вагос", checked_band, 4)            -- название круга, переменная,
        imgui.SameLine()
        imgui.RadioButton(u8"Ацтек", checked_band, 5)            -- название круга, переменная,

        imgui.Separator()

        imgui.RadioButton(u8"Наказание 1/3", checked_NakNumber, 2)            -- название квадрата, переменная.
        imgui.RadioButton(u8"Наказание 2/3", checked_NakNumber, 3)            -- название квадрата, переменная.
        imgui.RadioButton(u8"Наказание 3/3", checked_NakNumber, 4)            -- название квадрата, переменная.

        imgui.Separator()

        imgui.RadioButton(u8"Jail", checked_jail, 2)            -- название квадрата, переменная.
        imgui.RadioButton(u8"Ban", checked_jail, 4)


        imgui.Combo(u8"Причина", combo_select, arr_cheat, #arr_cheat)




        if imgui.Button(u8"Наказать!") then
            if checked_jail.v == 2 then
                if checked_NakNumber.v == 2 then
                    nakaz = "[1/3]"
                elseif checked_NakNumber.v == 3 then
                    nakaz = "[2/3]"
                elseif checked_NakNumber.v == 4 then
                    nakaz = "[3/3]"
                end
                if checked_band.v == 2 then
                    band = "Грув"
                elseif checked_band.v == 3 then
                    band = "Баллас"
                elseif checked_band.v == 4 then
                    band = "Вагос"
                elseif checked_band.v == 5 then
                    band = "Ацтек"
                end

                sampSendChat("/jail " .. ids .. " " .. arr_cheat[combo_select.v + 1] .. " " .. band .. " " .. nakaz)
            else
                if checked_NakNumber.v == 2 then
                    nakaz = "[1/3]"
                elseif checked_NakNumber.v == 3 then
                    nakaz = "[2/3]"
                elseif checked_NakNumber.v == 4 then
                    nakaz = "[3/3]"
                end
                if checked_band.v == 2 then
                    band = "Грув"
                elseif checked_band.v == 3 then
                    band = "Баллас"
                elseif checked_band.v == 4 then
                    band = "Вагос"
                elseif checked_band.v == 5 then
                    band = "Ацтек"
                end
                sampSendChat("/cban " .. ids .. " " .. arr_cheat[combo_select.v + 1] .. " " .. band .. " " .. nakaz)
            end
        end
    end
    imgui.End()

    if secondary_window_state.v then
        imgui.Begin(u8"Меню управления", secondary_window_state)
        if imgui.Button(u8"Правила капта") then
            cmd_grul()
        end
        if imgui.Button(u8"Рассказать о создании кланов") then
            cmd_clans()
        end
        if imgui.Button(u8"Начать следить") then
            cmd_1()
        end
        if imgui.Button(u8"Продолжить следить") then
            cmd_2()
        end
        if imgui.Button(u8"Закончить следить") then
            cmd_3()
        end
        imgui.End()
    end
end


function cmd_grul(arg)
    thread:run("grul")
end

function cmd_1(arg)
    thread:run("1")
end

function cmd_2(arg)
    thread:run("2")
end

function cmd_3(arg)
    thread:run("3")
end

function cmd_clans(arg)
    thread:run("clans")
end

function thread_ghetto(option)
    if option == "grul" then
        sampSendChat("/msg Уважаемые игроки, при виде нарушения на каптах, пожалйста пишите в репорт с тегом [GW].")
        wait(3000)
        sampSendChat("/msg Так же не забывайте правила: СК разрешено только с 0:59. Ответ на провокацию под запретом.")
        wait(3000)
        sampSendChat("/msg Побег от смерти на респу и стрельба с респы, воспринимаются, как провокация на СК")
        wait(3000)
        sampSendChat("/msg На форуме в разделе [Всё о гетто] есть тема [Края Спавн-Килл зон на Gang War]")
    end
    if option == "1" then
        sampSendChat("/a Начинаю следить за гетто")
        wait (1000)
        sampSendChat("/time")
    end
    if option == "2" then
        sampSendChat("/a Продолжаю следить за гетто")
        wait (1000)
        sampSendChat("/time")
    end
    if option == "3" then
        sampSendChat("/a Заканчиваю следить за гетто")
        wait (1000)
        sampSendChat("/time")
    end
    if option == "clans" then
        sampSendChat("/msg Хотите создать свой клан и стать самой сильно группировкой на сервере?")
        wait(3000)
        sampSendChat("/msg Всю подробню информацию по кланам, Вы найдте на форуме в соответствующем разделе.")
    end
end
--[[
--
--     _   _   _ _____ ___  _   _ ____  ____    _  _____ _____   ______   __   ___  ____  _     _  __
--    / \ | | | |_   _/ _ \| | | |  _ \|  _ \  / \|_   _| ____| | __)\ \ / /  / _ \|  _ \| |   | |/ /
--   / _ \| | | | | || | | | | | | |_) | | | |/ _ \ | | |  _|   |  _  \\ V /  | | | | |_) | |   | ' /
--  / ___ \ |_| | | || |_| | |_| |  __/| |_| / ___ \| | | |___  | |_) || |/  | |_| |  _ <| |___| . \
-- /_/   \_\___/  |_| \___/ \___/|_|   |____/_/   \_\_| |_____| |____/ |_|    \__\_\_| \_\_____|_|\_\                                                                                                                                                                                                                   
--
-- Author: http://qrlk.me/samp
--]]

--
--     _   _   _ _____ ___  _   _ ____  ____    _  _____ _____   ______   __   ___  ____  _     _  __
--    / \ | | | |_   _/ _ \| | | |  _ \|  _ \  / \|_   _| ____| | __ ) \ / /  / _ \|  _ \| |   | |/ /
--   / _ \| | | | | || | | | | | | |_) | | | |/ _ \ | | |  _|   |  _ \\ V /  | | | | |_) | |   | ' /
--  / ___ \ |_| | | || |_| | |_| |  __/| |_| / ___ \| | | |___  | |_) || |   | |_| |  _ <| |___| . \
-- /_/   \_\___/  |_| \___/ \___/|_|   |____/_/   \_\_| |_____| |____/ |_|    \__\_\_| \_\_____|_|\_\                                                                                                                                                                                                                   
--
-- Author: http://qrlk.me/samp
--
function autoupdate(json_url, prefix, url)
  local dlstatus = require('moonloader').download_status
  local json = getWorkingDirectory() .. '\\'..thisScript().name..'-version.json'
  if doesFileExist(json) then os.remove(json) end
  downloadUrlToFile(json_url, json,
    function(id, status, p1, p2)
      if status == dlstatus.STATUSEX_ENDDOWNLOAD then
        if doesFileExist(json) then
          local f = io.open(json, 'r')
          if f then
            local info = decodeJson(f:read('*a'))
            updatelink = info.updateurl
            updateversion = info.latest
            f:close()
            os.remove(json)
            if updateversion ~= thisScript().version then
              lua_thread.create(function(prefix)
                local dlstatus = require('moonloader').download_status
                local color = -1
                sampAddChatMessage((prefix..'Обнаружено обновление. Пытаюсь обновиться c '..thisScript().version..' на '..updateversion), color)
                wait(250)
                downloadUrlToFile(updatelink, thisScript().path,
                  function(id3, status1, p13, p23)
                    if status1 == dlstatus.STATUS_DOWNLOADINGDATA then
                      print(string.format('Загружено %d из %d.', p13, p23))
                    elseif status1 == dlstatus.STATUS_ENDDOWNLOADDATA then
                      print('Загрузка обновления завершена.')
                      sampAddChatMessage((prefix..'Обновление завершено!'), color)
                      goupdatestatus = true
                      lua_thread.create(function() wait(500) thisScript():reload() end)
                    end
                    if status1 == dlstatus.STATUSEX_ENDDOWNLOAD then
                      if goupdatestatus == nil then
                        sampAddChatMessage((prefix..'Обновление прошло неудачно. Запускаю устаревшую версию..'), color)
                        update = false
                      end
                    end
                  end
                )
                end, prefix
              )
            else
              update = false
              print('v'..thisScript().version..': Обновление не требуется.')
            end
          end
        else
          print('v'..thisScript().version..': Не могу проверить обновление. Смиритесь или проверьте самостоятельно на '..url)
          update = false
        end
      end
    end
  )
  while update ~= false do wait(100) end
end
 

Adrian G.

Известный
Проверенный
516
452
Кнопка включения основного imgui окна:

Lua:
        if wasKeyPressed(VK_F2) then

            array.test_window_state.v = not array.test_window_state.v
            imgui.Process = array.test_window_state.v
        end
Команда включения основного imgui окна:
Lua:
function cmd_fhelp(arg)
    array.test_window_state.v = not array.test_window_state.v
    imgui.Process = array.test_window_state.v
end

p.s в основном imgui окне, еще одна кнопка, для включения imgui окна с настройками
Вот кнопка для включения imgui окна " настройки":

Lua:
                imgui.SetCursorPos(imgui.ImVec2(10, 185))
                imgui.PushStyleVar(imgui.StyleVar.ButtonTextAlign , imgui.ImVec2(0.5, 0.5))
                if imgui.Button("" ..fa.ICON_ADDRESS_CARD.. u8"  Домой", imgui.ImVec2(330, 40)) then
                    array.test2_window_state.v = not array.test2_window_state.v
                    imgui.Process = array.test2_window_state.v
                end



Функция, если все imgui окна не активны, то имгуи процесс = false:
Lua:
    if not array.orpo_active_state.v and not array.test_window_state.v and not array.test2_window_state.v and not array.test3_window_state.v and not array.test4_window_state.v and not window.v and not mainMenu.v and not infobar.v then
        imgui.Process = false
    end

Вот togglebutton включения инфобара:

Lua:
                    if imgui.ToggleButton(u8'Инфобар', activeinfobar) then
                        infobar.v = not infobar.v
                    end

Вот непосредственно сам инфобар:

Lua:
    if infobar.v then

        _, myID = sampGetPlayerIdByCharHandle(PLAYER_PED)
        myName = sampGetPlayerNickname(myID)
        namer = string.gsub(sampGetPlayerNickname(myID), '_', ' ')
        lmyping = sampGetPlayerPing(myID)

        imgui.ShowCursor = false
        --local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(posX, posY), imgui.Cond.Always)
        imgui.SetNextWindowSize(imgui.ImVec2(250, 100), imgui.Cond.FirstUseEver)
        imgui.PushStyleColor(imgui.Col.WindowBg, imgui.ImVec4(color_back.v[1], color_back.v[2], color_back.v[3], color_back.v[4]))
        themes.SwitchColorTheme(15)
        --imgui.GetStyle(50.0)
        imgui.Begin(u8"", _, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove)
    
        --+ imgui.WindowFlags.NoResize + imgui.WindowFlags.NoTitleBar

        imgui.Text('' ..fa.ICON_ADDRESS_CARD_O.. ' ' ..myName.. ' [' ..myID.. ']')
        imgui.Text('' ..fa.ICON_WIFI.. u8'Пинг: ' ..lmyping)
        imgui.Text('' ..fa.ICON_MAP_MARKER.. '')
        imgui.SameLine()
        imgui.Text(u8(kvadrat()))
        imgui.Text('' ..os.date('%x | %X').. '')


        imgui.End()
        imgui.PopStyleColor()
    

    end

Проблема тут в двух вещах:

1) когда нажимаю F2 открываться основное imgui окно, затем открываю imgui окно "настройки"(у меня эта кнопка называется домой), открывается окно "настройки", там я с помощьюtogglebutton включаю инфобар, потом если прописать команду /fhelp или нажать F2 закрываеться основное окно, окно настроек и сам итнфобар

2) после перезагрузки скрипта, елси togglebutton = true, инфобар сам по себе не включается, приходится нажимать F2 - активируеться основное меню и инфобар, но если с ново нажать F2 то все выключается



p.s у меня просто более 3.000 строк, скинул то что связанно с этим
По объяснениям похоже на то, что у тебя проверка на переменную инфобара находится где то в блоке основного окна.
По этой малой части кода можно много чего предположить. Кинь код целиком.
Lua:
if osnovnoe_okno.v then
    if infobar.v then -- если проверка на переменную инфобара стоит где-то между if и end основного окна, то тогда инфобар будет показываться когда активно основное окно, проверь это.
end