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

CaJlaT

Овощ
Модератор
2,806
2,609
Помогите пожалуйста, при запуске сампа в лог идёт подгрузка скрипта, но он не работает, начинает работать только после перезапуска (CTRL+R).
Так не работают несколько скриптов.
Log:
[19:51:22.890638] (system)    Loading script "E:\GTA 120K BY DAPO SHOW\moonloader\PlayersStreamed.lua"...    (id:34)
[19:51:22.901638] (system)    PlayersStreamed.lua: Loaded successfully.

Lua:
require "lib.moonloader"
local inicfg = require 'inicfg'
local imgui = require 'imgui'
local encoding = require 'encoding'
u8 = encoding.UTF8
encoding.default = 'CP1251'

local mainIni = inicfg.load({
    config =
    {
        active = false,
        posX = 0,
        posY = 0,
        size = 12
    }
}, 'PlayerStreamed.ini')
if not doesFileExist("moonloader/config/PlayerStreamed.ini") then inicfg.save(mainIni, "PlayerStreamed.ini") end

local settings = imgui.ImBool(false)
local active = imgui.ImBool(mainIni.config.active)
local height = imgui.ImInt(mainIni.config.size)

function main()
    if not isSampAvailable() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage('PlayerStreamed by CaJlaT {00ff00}[Loaded]', -1)
    Font = renderCreateFont("Molot", mainIni.config.size, 12)
    sampRegisterChatCommand("stream", function()
        settings.v = not settings.v
        imgui.Process= settings.v
    end)
    while true do
        wait(0)
        imgui.Process = settings.v
        if changePos or mainIni.config.active then
            if changePos then
                renderFontDrawText(Font, "{DC143C}" .. sampGetPlayerCount(true), mainIni.config.posX, mainIni.config.posY, -1)
                showCursor(true, true)
                local int_posX, int_posY = getCursorPos()
                mainIni.config.posX = int_posX
                mainIni.config.posY = int_posY
                if isKeyJustPressed(13) then
                    showCursor(false, false)
                    sampAddChatMessage("Положение {fff000}сохранено.", -1)
                    changePos = false
                    inicfg.save(mainIni, 'PlayerStreamed.ini')
                    settings.v = true
                    imgui.Process = true
                end
            else
                renderFontDrawText(Font, "{DC143C}" .. sampGetPlayerCount(true), mainIni.config.posX, mainIni.config.posY, -1)
            end
        end
    end
end

function imgui.OnDrawFrame()
    ScreenX, ScreenY = getScreenResolution()
    imgui.SetNextWindowSize(imgui.ImVec2(100, 60), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2(ScreenX / 2, ScreenY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("PlayerStreamed | by CaJlaT", settings, imgui.WindowFlags.NoResize + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Button(u8'Изменить положение') then settings.v = false changePosition() end
    if imgui.Checkbox(u8'Включить отображение', active) then
        mainIni.config.active = active.v
        inicfg.save(mainIni, 'PlayerStreamed.ini')
    end
    imgui.PushItemWidth(100)
    if imgui.InputInt(u8'Размер текста', height) then
        mainIni.config.size = height.v
        inicfg.save(mainIni, 'PlayerStreamed.ini')
        Font = renderCreateFont("Molot", mainIni.config.size, 12)
    end
    imgui.End()
end

function changePosition()
    if changePos==true then
        changePos=false
    else
        changePos=true
        sampAddChatMessage("Для сохранения положения нажмите {fff000}ENTER.", -1)
    end
end

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

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0

    colors[clr.FrameBg]                = ImVec4(0.42, 0.48, 0.16, 0.54)
    colors[clr.FrameBgHovered]         = ImVec4(0.85, 0.98, 0.26, 0.40)
    colors[clr.FrameBgActive]          = ImVec4(0.85, 0.98, 0.26, 0.67)
    colors[clr.TitleBg]                = ImVec4(0.04, 0.04, 0.04, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.42, 0.48, 0.16, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.CheckMark]              = ImVec4(0.85, 0.98, 0.26, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.77, 0.88, 0.24, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.85, 0.98, 0.26, 1.00)
    colors[clr.Button]                 = ImVec4(0.85, 0.98, 0.26, 0.40)
    colors[clr.ButtonHovered]          = ImVec4(0.85, 0.98, 0.26, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.82, 0.98, 0.06, 1.00)
    colors[clr.Header]                 = ImVec4(0.85, 0.98, 0.26, 0.31)
    colors[clr.HeaderHovered]          = ImVec4(0.85, 0.98, 0.26, 0.80)
    colors[clr.HeaderActive]           = ImVec4(0.85, 0.98, 0.26, 1.00)
    colors[clr.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.63, 0.75, 0.10, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.63, 0.75, 0.10, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.85, 0.98, 0.26, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.85, 0.98, 0.26, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.85, 0.98, 0.26, 0.95)
    colors[clr.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.81, 0.35, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.85, 0.98, 0.26, 0.35)
    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    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.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    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.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
apply_custom_style()
 

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Я немного запутался..
Вот у меня массив
Lua:
local vla = {
    'Aztec',
    'Aztecas',
    'VLA',
    'vla',
    'aztec',
    'aztecas',
    'ацтек',
    'азтек',
    'Ацтек',
    'Азтек',
}

local lsv = {
    'Vagos',
    'vagos',
    'LSV',
    'lsv',
    'Вагос',
    'вагос',
}

local grovestreet = {
    'Grove',
    'grove',
    'Грув',
    'грув',
}

local therifa = {
    'Rifa',
    'rifa',
    'Рифа',
    'рифа',
}

local theballas = {
    'Ballas',
    'ballas',
    'Баллас',
    'баллас',
}
Хочу сделать проверку, когда варнят чела с причиной в конце с одним из этих слов, то прибавлять + 1
Как мне хукать текст и находить через elseif?
Lua:
function sampev.onServerMessage(color, text)
    lua_thread.create(function()
        for i = 1, #vla do
            if text:find(vla[i]) then
                wait(10)
                vagos = vagos + 1
            end
        end
        -- ...
 

skarzer999

Известный
24
2
Есть диалог 100001,но когда в нем выбираю 1 пункт то он не открывает диалог 100003,подскажите в чем проблема?
И как в будущем сделать так что бы после выбора в диалоге 100003 открывался следующий диалог или сразу отправлялась команда в чат через sampSendChat,заранее благодарен.

Lua:
function dialog()
    sampShowDialog(100001, tag.. ' {ffffff}' ..playername.. ' | Меню взаимодействия',fmhelperList,'Выбрать','Закрыть',2)
    lua_thread.create(cheker)
end

function cheker()
    while sampIsDialogActive() do
        wait(0)
        local result,button,list,input = sampHasDialogRespond(100001)
        if result and list == 0 then
            sampShowDialog(100003, tag.. ' {ffffff}' ..playername.. ' | Передача денег',moneymenu,'Выбрать','Закрыть',2)
        elseif result and list == 1 then
            sampSendChat('/test')
        elseif result and list == 2 then
            sampSendChat('/test')
        elseif result and list == 3 then
            sampSendChat('/test')
        elseif result and list == 4 then
            sampSendChat('/test')
        elseif result and list == 5 then
            sampSendChat('/test')
        end
    end
end
 

astynk

Известный
Проверенный
742
530
Есть диалог 100001,но когда в нем выбираю 1 пункт то он не открывает диалог 100003,подскажите в чем проблема?
И как в будущем сделать так что бы после выбора в диалоге 100003 открывался следующий диалог или сразу отправлялась команда в чат через sampSendChat,заранее благодарен.

Lua:
function dialog()
    sampShowDialog(100001, tag.. ' {ffffff}' ..playername.. ' | Меню взаимодействия',fmhelperList,'Выбрать','Закрыть',2)
    lua_thread.create(cheker)
end

function cheker()
    while sampIsDialogActive() do
        wait(0)
        local result,button,list,input = sampHasDialogRespond(100001)
        if result and list == 0 then
            sampShowDialog(100003, tag.. ' {ffffff}' ..playername.. ' | Передача денег',moneymenu,'Выбрать','Закрыть',2)
        elseif result and list == 1 then
            sampSendChat('/test')
        elseif result and list == 2 then
            sampSendChat('/test')
        elseif result and list == 3 then
            sampSendChat('/test')
        elseif result and list == 4 then
            sampSendChat('/test')
        elseif result and list == 5 then
            sampSendChat('/test')
        end
    end
end

У диалога не может быть ID больше 32768
 

Fott

Простреленный
3,435
2,280
Как сделать чтобы при помощи print выводился абсолютно весь чат?
 

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Есть диалог 100001,но когда в нем выбираю 1 пункт то он не открывает диалог 100003,подскажите в чем проблема?
И как в будущем сделать так что бы после выбора в диалоге 100003 открывался следующий диалог или сразу отправлялась команда в чат через sampSendChat,заранее благодарен.

Lua:
function dialog()
    sampShowDialog(100001, tag.. ' {ffffff}' ..playername.. ' | Меню взаимодействия',fmhelperList,'Выбрать','Закрыть',2)
    lua_thread.create(cheker)
end

function cheker()
    while sampIsDialogActive() do
        wait(0)
        local result,button,list,input = sampHasDialogRespond(100001)
        if result and list == 0 then
            sampShowDialog(100003, tag.. ' {ffffff}' ..playername.. ' | Передача денег',moneymenu,'Выбрать','Закрыть',2)
        elseif result and list == 1 then
            sampSendChat('/test')
        elseif result and list == 2 then
            sampSendChat('/test')
        elseif result and list == 3 then
            sampSendChat('/test')
        elseif result and list == 4 then
            sampSendChat('/test')
        elseif result and list == 5 then
            sampSendChat('/test')
        end
    end
end
Lua:
if result then
    if button == 1 and list == 0 then
        -- code
    elseif button == 1 and list == 1 then
        -- code
    -- ...
 
  • Нравится
Реакции: skarzer999

Akionka

akionka.lua
Проверенный
742
500
при вводе команды "/popa" должна быть надпись "скрипт включен", но эта команда вместо одноразового сообщения флудит в чат. что я не так сделал?
код в студию
Как сделать чтобы при помощи print выводился абсолютно весь чат?
function sampev.onServerMessage(color, text)
print(color, text)
end
Я немного запутался..
Вот у меня массив
Lua:
local vla = {
    'Aztec',
    'Aztecas',
    'VLA',
    'vla',
    'aztec',
    'aztecas',
    'ацтек',
    'азтек',
    'Ацтек',
    'Азтек',
}

local lsv = {
    'Vagos',
    'vagos',
    'LSV',
    'lsv',
    'Вагос',
    'вагос',
}

local grovestreet = {
    'Grove',
    'grove',
    'Грув',
    'грув',
}

local therifa = {
    'Rifa',
    'rifa',
    'Рифа',
    'рифа',
}

local theballas = {
    'Ballas',
    'ballas',
    'Баллас',
    'баллас',
}
Хочу сделать проверку, когда варнят чела с причиной в конце с одним из этих слов, то прибавлять + 1
Как мне хукать текст и находить через elseif?
Lua:
function sampev.onServerMessage(color, text)
    lua_thread.create(function()
        for i = 1, #vla do
            if text:find(vla[i]) then
                wait(10)
                vagos = vagos + 1
            end
        end
        -- ...
а в чем вопрос, код же рабочий с виду
 

Rei

Известный
Друг
1,590
1,621
можно ли с помощью регулярных выражений отсеивать числа большие или меньшие, чем заданное?
 
D

deleted-user-204957

Гость
можно ли с помощью регулярных выражений отсеивать числа большие или меньшие, чем заданное?
На счёт регулярок не уверен, но можно же получать в переменную число и сравнивать уже потом переменную с числом с другой переменной.
 

Rei

Известный
Друг
1,590
1,621
На счёт регулярок не уверен, но можно же получать в переменную число и сравнивать уже потом переменную с числом с другой переменной.
я понимаю, просто в связи со спецификой моего быдлокода хотелось это именно так изобразить... но ладно, буду переделывать тогда
 

yeahbitch

Потрачен
28
5
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Крашит при открытии меню, в чём проблема?
Lua:
script_name('Imgui Script Icons') -- название скрипта
script_author('FORMYS') -- автор скрипта
script_description('Imgui') -- описание скрипта

require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
local sampev   = require 'lib.samp.events'
local ini  = require 'inicfg'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local def = {
    settings = {
        vkladka = 1
    }
}

local directIni = "PrisonHelper\\PrHelper"

local ini = ini.load(def, directIni)

local vkladki = {
    false,
        false,
        false,
        false,
}

vkladki[ini.settings.vkladka] = true

local fa = require 'faIcons'
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })

main_window_state = imgui.ImBool(false)
arrSelectable = {false, false}

function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig() -- to use 'imgui.ImFontConfig.new()' on error
        font_config.MergeMode = true
        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fontawesome-webfont.ttf', 14.0, font_config, fa_glyph_ranges)
    end
end


function imgui.TextColoredRGB(text, render_text)
    local max_float = imgui.GetWindowWidth()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local ImVec4 = imgui.ImVec4

    local explode_argb = function(argb)
        local a = bit.band(bit.rshift(argb, 24), 0xFF)
        local r = bit.band(bit.rshift(argb, 16), 0xFF)
        local g = bit.band(bit.rshift(argb, 8), 0xFF)
        local b = bit.band(argb, 0xFF)
        return a, r, g, b
    end

    local getcolor = function(color)
        if color:sub(1, 6):upper() == 'SSSSSS' then
            local r, g, b = colors[1].x, colors[1].y, colors[1].z
            local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
            return ImVec4(r, g, b, a / 255)
        end
        local color = type(color) == 'string' and tonumber(color, 16) or color
        if type(color) ~= 'number' then return end
        local r, g, b, a = explode_argb(color)
        return imgui.ImColor(r, g, b, a):GetVec4()
    end

    local render_text = function(text_)
        for w in text_:gmatch('[^\r\n]+') do
            local text, colors_, m = {}, {}, 1
            w = w:gsub('{(......)}', '{%1FF}')
            while w:find('{........}') do
                local n, k = w:find('{........}')
                local color = getcolor(w:sub(n + 1, k - 1))
                if color then
                    text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                    colors_[#colors_ + 1] = color
                    m = n
                end
                w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
            end

            local length = imgui.CalcTextSize(w)
            if render_text == 2 then
                imgui.NewLine()
                imgui.SameLine(max_float / 2 - ( length.x / 2 ))
            elseif render_text == 3 then
                imgui.NewLine()
                imgui.SameLine(max_float - length.x - 5 )
            end
            if text[0] then
                for i = 0, #text do
                    imgui.TextColored(colors_[i] or colors[1], text[i])
                    imgui.SameLine(nil, 0)
                end
                imgui.NewLine()
            else imgui.Text(w) end


        end
    end

    render_text(text)
end

function SetStyle()
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.ChildWindowRounding = 4.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("icons", cmd_icons)

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

    imgui.Process = false

    while true do
        wait(0)
    end
end

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

function imgui.OnDrawFrame()

    if not main_window_state.v then
        imgui.Process = false
    end

   if main_window_state.v then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(600, 300), imgui.Cond.FirstUseEver)

        imgui.Begin('Helper for Prison', main_window_state)

            imgui.BeginChild("ChildButtons", imgui.ImVec2(153, 265), true)
                if imgui.Button(u8"Информация "..fa.ICON_ADDRESS_BOOK_O, imgui.ImVec2(137, 35)) then
                    vkladki[1] = true
                    ini.settings.vkladka = 1
                    inicfg.save(def, directIni)
                end
                if imgui.Button(u8"Биндер "..fa.ICON_FILE_TEXT, imgui.ImVec2(137, 35))then
                    vkladki[2] = true
                    ini.settings.vkladka = 2
                    inicfg.save(def, directIni)
                end
                if imgui.Button(u8"О скрипте "..fa.ICON_USER, imgui.ImVec2(137, 35)) then
                    vkladki[3] = true
                    ini.settings.vkladka = 3
                    inicfg.save(def, directIni)
                end
                if imgui.Button(u8"Настройки "..fa.ICON_COGS, imgui.ImVec2(137, 35)) then
                    vkladki[4] = true
                    ini.settings.vkladka = 4
                    inicfg.save(def, directIni)
                end
            imgui.EndChild()
            imgui.SameLine()
        if vkladki[1] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        if vkladki[2] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        if vkladki[3] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        if vkladki[4] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        imgui.End()
    end
end
при вводе команды "/popa" должна быть надпись "скрипт включен", но эта команда вместо одноразового сообщения флудит в чат. что я не так сделал?
Вынеси sampAddChatMessage из бесконечного цикла
 
Последнее редактирование:

copypaste_scripter

Известный
1,218
224
Lua:
script_name('CPS_Script')
script_author('Copy_Paste_from_Internet')
script_description('Something')

require "lib.moonloader"
require "lib.samp.events"

local sampev = require "lib.samp.events"
local keys = require "vkeys"
local main_color = 0x8B0000

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

function sampev.onServerMessage(color, text)
    if text:find("Отредактировал сотрудник СМИ") then
        return false
    end
end

в этом скрипте, как сделать, чтобы вся фигня остановился работать если я напишу в чат сампа /myscript и потом когда опять захочу чтобы работал чтобы опять написал тот же или другую команду? я пишу /smenu и там делаю unload и потом load но писец неудобно