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

Curtis

Участник
282
10
ты бы сначала переменные уникальные сделал бы, или через массив реализацию.
пишу для мозгов я тебе дал, подумаешь - разберешься
(устал код писать за других уже)
Я через уникальные переменные сделал и оно прекрасно работает, но хочу через массив или это не имеет смысла?
 

#Kai-

Известный
698
292
Есть такой скриптик MVDhelper там такая штукеция когда достаеш оружие ну например дигл то пишет в чат
/me достал дигл из жопы
когда убираеш дигл то пишет
/me засунул дигл в жопу
Очень интересно, спасибо что сообщил.
 

SSimidzu

Новичок
2
1
Есть такой скриптик MVDhelper там такая штукеция когда достаеш оружие ну например дигл то пишет в чат
/me достал дигл из жопы
когда убираеш дигл то пишет
/me засунул дигл в жопу
Как это реализовать?
Скрипт не мой

Lua:
script_name('RP GUN') -- название скрипта
script_author('FORMYS') -- автор скрипта
script_description('RP GUN true function') -- описание скрипта

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

rpgun = false -- изначально выключен
sex = 1 -- 0 женский, 1 мужской

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

    sampRegisterChatCommand("rpgun", cmd_rpgun)
    rp_thread = lua_thread.create_suspended(rp_weapons)

    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(id)
   
    while true do
        wait(0)

    end
end

function cmd_rpgun()
    rpgun = not rpgun
    if rpgun then
        sampAddChatMessage("РП оружие включено", -1)
        rp_thread:run()
    else
        sampAddChatMessage("РП оружие выключено", -1)
        rp_thread:terminate()
    end
end

function rp_weapons()
    local gunOn = {}
    local gunOff = {}
    local gunPartOn = {}
    local gunPartOff = {}
    local oldGun = nil
    local nowGun = getCurrentCharWeapon(PLAYER_PED)
    local rpTakeNames = {{"из-за спины", "за спину"}, {"из кармана", "в карман"}, {"из пояса", "на пояс"}, {"из кобуры", "в кобуру"}}
    local rpTake = {
        [2]=1, [5]=1, [6]=1, [7]=1, [8]=1, [9]=1, [14]=1, [15]=1, [25]=1, [26]=1, [27]=1, [28]=1, [29]=1, [30]=1, [31]=1, [32]=1, [33]=1, [34]=1, [35]=1, [36]=1, [37]=1, [38]=1, [42]=1, -- спина
        [1]=2, [4]=2, [10]=2, [11]=2, [12]=2, [13]=2, [41]=2, [43]=2, [44]=2, [45]=2, [46]=2, -- карман
        [3]=3, [16]=3, [17]=3, [18]=3, [39]=3, [40]=3, -- пояс
        [22]=4, [23]=4, [24]=4 -- кобура
    }
   
    for id, weapon in pairs(weapons.names) do
        --sampAddChatMessage(id .. " - " .. weapon, -1)

        if (id == 3 or (id > 15 and id < 19)) then -- 3 16 17 18 (for gunOn)
            gunOn[id] = sex and 'снял' or 'сняла'
        else
            gunOn[id] = sex and 'достал' or 'достала'
        end

        if (id == 3 or (id > 15 and id < 19) or (id > 38 and id < 41)) then -- 3 16 17 18 39 40 (for gunOff)
            gunOff[id] = sex and 'повесил' or 'повесила'
        else
            gunOff[id] = sex and 'убрал' or 'убрала'
        end

        if id > 0 then
            gunPartOn[id] = rpTakeNames[rpTake[id]][1]
            gunPartOff[id] = rpTakeNames[rpTake[id]][2]
        end
    end

    while true do
        wait(0)
        if nowGun ~= getCurrentCharWeapon(PLAYER_PED) then
            oldGun = nowGun
            nowGun = getCurrentCharWeapon(PLAYER_PED)
            if oldGun == 0 then
                sampAddChatMessage("/me " .. gunOn[nowGun] .. " " .. weapons.get_name(nowGun) .. " " .. gunPartOn[nowGun], -1)
            else
                if nowGun == 0 then
                    sampAddChatMessage("/me " .. gunOff[oldGun] .. " " .. weapons.get_name(oldGun) .. " " .. gunPartOff[oldGun], -1)
                else
                    sampAddChatMessage("/me " .. gunOff[oldGun] .. " " .. weapons.get_name(oldGun) .. " " .. gunPartOff[oldGun] .. ", после чего " .. gunOn[nowGun] .. " " .. weapons.get_name(nowGun) .. " " .. gunPartOn[nowGun], -1)
                end
            end
        end
    end
end



Помогите пожайлуста как сделать /invite, чтоб я смог ввести туда ник или ID, например: /inv 1 или /inv Test_Test



Lua:
require('lib.moonloader')
local sampev = require('lib.samp.events')

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

    if valid and doesCharExist(ped) then
        local result, id = sampGetPlayerIdByCharHandle(ped)
        if result then
        end
    end

    sampRegisterChatCommand('ads', cmd_ads)
    sampRegisterChatCommand('mb', cmd_mb) -- /members
    sampRegisterChatCommand('bz', cmd_bz) -- /bizwar
    sampRegisterChatCommand('inv', cmd_inv) -- /invite

    sampAddChatMessage('Soprano loaded', 0xFFFFFF)
    sampAddChatMessage('Activation: /ads | /mb | /bz | /inv | /uninv | /uninvoff', 0xFFFFFF)

    while true do
       wait(100)
    end
end

function cmd_mb(arg)
    sampSendChat('/members')
end

function cmd_bz(arg)
    sampSendChat('/bizwar ')
end

function cmd_inv(arg)
    sampSendChat('/invite' .. {id})
end


function cmd_ads(arg)
    sampSendChat('/ad Идет собеседование в ресторан "Сопрано". Мы в навигаторе: 10-8')
end
 
  • Нравится
Реакции: deleted-user-443489

Smeruxa

smeruxa.ru
Проверенный
1,434
800
Скрипт не мой

Lua:
script_name('RP GUN') -- название скрипта
script_author('FORMYS') -- автор скрипта
script_description('RP GUN true function') -- описание скрипта

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

rpgun = false -- изначально выключен
sex = 1 -- 0 женский, 1 мужской

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

    sampRegisterChatCommand("rpgun", cmd_rpgun)
    rp_thread = lua_thread.create_suspended(rp_weapons)

    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(id)
  
    while true do
        wait(0)

    end
end

function cmd_rpgun()
    rpgun = not rpgun
    if rpgun then
        sampAddChatMessage("РП оружие включено", -1)
        rp_thread:run()
    else
        sampAddChatMessage("РП оружие выключено", -1)
        rp_thread:terminate()
    end
end

function rp_weapons()
    local gunOn = {}
    local gunOff = {}
    local gunPartOn = {}
    local gunPartOff = {}
    local oldGun = nil
    local nowGun = getCurrentCharWeapon(PLAYER_PED)
    local rpTakeNames = {{"из-за спины", "за спину"}, {"из кармана", "в карман"}, {"из пояса", "на пояс"}, {"из кобуры", "в кобуру"}}
    local rpTake = {
        [2]=1, [5]=1, [6]=1, [7]=1, [8]=1, [9]=1, [14]=1, [15]=1, [25]=1, [26]=1, [27]=1, [28]=1, [29]=1, [30]=1, [31]=1, [32]=1, [33]=1, [34]=1, [35]=1, [36]=1, [37]=1, [38]=1, [42]=1, -- спина
        [1]=2, [4]=2, [10]=2, [11]=2, [12]=2, [13]=2, [41]=2, [43]=2, [44]=2, [45]=2, [46]=2, -- карман
        [3]=3, [16]=3, [17]=3, [18]=3, [39]=3, [40]=3, -- пояс
        [22]=4, [23]=4, [24]=4 -- кобура
    }
  
    for id, weapon in pairs(weapons.names) do
        --sampAddChatMessage(id .. " - " .. weapon, -1)

        if (id == 3 or (id > 15 and id < 19)) then -- 3 16 17 18 (for gunOn)
            gunOn[id] = sex and 'снял' or 'сняла'
        else
            gunOn[id] = sex and 'достал' or 'достала'
        end

        if (id == 3 or (id > 15 and id < 19) or (id > 38 and id < 41)) then -- 3 16 17 18 39 40 (for gunOff)
            gunOff[id] = sex and 'повесил' or 'повесила'
        else
            gunOff[id] = sex and 'убрал' or 'убрала'
        end

        if id > 0 then
            gunPartOn[id] = rpTakeNames[rpTake[id]][1]
            gunPartOff[id] = rpTakeNames[rpTake[id]][2]
        end
    end

    while true do
        wait(0)
        if nowGun ~= getCurrentCharWeapon(PLAYER_PED) then
            oldGun = nowGun
            nowGun = getCurrentCharWeapon(PLAYER_PED)
            if oldGun == 0 then
                sampAddChatMessage("/me " .. gunOn[nowGun] .. " " .. weapons.get_name(nowGun) .. " " .. gunPartOn[nowGun], -1)
            else
                if nowGun == 0 then
                    sampAddChatMessage("/me " .. gunOff[oldGun] .. " " .. weapons.get_name(oldGun) .. " " .. gunPartOff[oldGun], -1)
                else
                    sampAddChatMessage("/me " .. gunOff[oldGun] .. " " .. weapons.get_name(oldGun) .. " " .. gunPartOff[oldGun] .. ", после чего " .. gunOn[nowGun] .. " " .. weapons.get_name(nowGun) .. " " .. gunPartOn[nowGun], -1)
                end
            end
        end
    end
end



Помогите пожайлуста как сделать /invite, чтоб я смог ввести туда ник или ID, например: /inv 1 или /inv Test_Test



Lua:
require('lib.moonloader')
local sampev = require('lib.samp.events')

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

    if valid and doesCharExist(ped) then
        local result, id = sampGetPlayerIdByCharHandle(ped)
        if result then
        end
    end

    sampRegisterChatCommand('ads', cmd_ads)
    sampRegisterChatCommand('mb', cmd_mb) -- /members
    sampRegisterChatCommand('bz', cmd_bz) -- /bizwar
    sampRegisterChatCommand('inv', cmd_inv) -- /invite

    sampAddChatMessage('Soprano loaded', 0xFFFFFF)
    sampAddChatMessage('Activation: /ads | /mb | /bz | /inv | /uninv | /uninvoff', 0xFFFFFF)

    while true do
       wait(100)
    end
end

function cmd_mb(arg)
    sampSendChat('/members')
end

function cmd_bz(arg)
    sampSendChat('/bizwar ')
end

function cmd_inv(arg)
    sampSendChat('/invite' .. {id})
end


function cmd_ads(arg)
    sampSendChat('/ad Идет собеседование в ресторан "Сопрано". Мы в навигаторе: 10-8')
end
Lua:
sampRegisterChatCommand("invite", function(id)
    if id:find("(%d+)") and id ~= "" then
        sampSendChat("/invite "..id)
    end
end)
 

GoddanYL

Новичок
5
0
Помогите, пожалуйста.
[18:58:03.334521] (error) lib_imgui_notf.lua: cannot resume non-suspended coroutine
stack traceback:
[C]: in function 'SetMouseCursor'
D:\ARIZONA GAMES\bin\Arizona\moonloader\lib_imgui_notf.lua:103: in function <D:\ARIZONA GAMES\bin\Arizona\moonloader\lib_imgui_notf.lua:99>
[18:58:03.334521] (error) lib_imgui_notf.lua: Script died due to an error. (08D948D4)
 

Curtis

Участник
282
10
imgui.InputTextFlags не работает для InputInt? Есть какие-то замены этому?
 

Sanchez.

Известный
704
190
Как хукнуть текст, что в скрипте произошла ошибка, чтобы в дальнейшем перезагрузить скрипт
актуал
Помогите, пожалуйста.
[18:58:03.334521] (error) lib_imgui_notf.lua: cannot resume non-suspended coroutine
stack traceback:
[C]: in function 'SetMouseCursor'
D:\ARIZONA GAMES\bin\Arizona\moonloader\lib_imgui_notf.lua:103: in function <D:\ARIZONA GAMES\bin\Arizona\moonloader\lib_imgui_notf.lua:99>
[18:58:03.334521] (error) lib_imgui_notf.lua: Script died due to an error. (08D948D4)
кинь код
 

Sanchez.

Известный
704
190
Легче файлом кинуть.
Если ты пишешь скрипт, то скинь не этот файл, а сам файл, в котором ты пишешь скрипт. А если ты не пишешь скрипт, и просто скачал эту либу для другого скрипта, то проблема в скачанном скрипте
 
D

deleted-user-210352

Гость
хз шо сделал, но при заходе в игру, мне нужно нажимать ctr+r чтоб я смог открыть менюшку скрипта, потом после нескольких нажатий включить\выключить больше 6-10 раз, еще раз включаешь и у скрипта кд не работает почему то
Lua:
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local imgui = require 'imgui'
local inicfg = require 'inicfg'

function imgui.OnDrawFrame()
    w, h = getScreenResolution()
    if imguiVars.windowState.v then
        imgui.SetNextWindowSize(imgui.ImVec2(250, 350), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2(w / 2 , h / 2), imgui.Cond.FirsUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8'Flooder | Настройки by KARLEONE', imguiVars.windowState, imgui.WindowFlags.NoCollapse)
        imgui.Text(u8'Флуд серверными командами')
        imgui.InputText(u8'Текст##input1', imguiVars.input1)
        imgui.InputInt(u8'Задержка##delay1', imguiVars.delay1, 0, 0)
        imgui.InputText(u8'Текст##input2', imguiVars.input2)
        imgui.InputInt(u8'Задержка##delay2', imguiVars.delay2, 0, 0)
        imgui.InputText(u8'Текст##input3', imguiVars.input3)
        imgui.InputInt(u8'Задержка##delay3', imguiVars.delay3, 0, 0)
        imgui.InputText(u8'Текст##input5', imguiVars.input5)
        imgui.InputInt(u8'Задержка##delay5', imguiVars.delay5, 0, 0)
        imgui.Separator()
        imgui.Text(u8'Флуд любыми командами.')
        imgui.Text(u8'Отправляет команды в чат.')
        imgui.InputText(u8'Текст##input4', imguiVars.input4)
        imgui.InputInt(u8'Задержка##delay4', imguiVars.delay4, 0, 0)
        imgui.Separator()
        if imgui.Button(imguiVars.enabled.v and u8'Выключить' or u8'Включить', imgui.ImVec2(250, 20)) then
            imguiVars.enabled.v = not imguiVars.enabled.v
            if imguiVars.enabled.v then
                if #imguiVars.input1.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input1.v), imguiVars.delay1.v)
                end
                if #imguiVars.input2.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input2.v), imguiVars.delay2.v)
                end
                if #imguiVars.input3.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input3.v), imguiVars.delay3.v)
                end
                if #imguiVars.input5.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input5.v), imguiVars.delay5.v)
                end
                if #imguiVars.input4.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input4.v), imguiVars.delay4.v, true)
                end
            end
        end
        if imgui.Button(u8'Сохранить настройки', imgui.ImVec2(250, 20)) then
            inicfg.save({settings = {input1 = imguiVars.input1.v, input2 = imguiVars.input2.v, input3 = imguiVars.input3.v, input4 = imguiVars.input4.v,input5 = imguiVars.input5.v, delay1 = imguiVars.delay1.v, delay2 = imguiVars.delay2.v, delay3 = imguiVars.delay3.v, delay4 = imguiVars.delay4.v, delay5 = imguiVars.delay5.v,}}, 'flooder-settings')
        end
        imgui.End()
    end
end

function flood(text, delay, localcmd)
    while imguiVars.enabled.v do
        if localcmd then
            sampProcessChatInput(text)
        else
            sampSendChat(text)
        end
        wait(delay * 1000)
    end
end

function main()
    while not isSampfuncsLoaded() do
        wait(100)
    end
    config = inicfg.load({
        settings =
        {
            input1 = '',
            input2 = '',
            input3 = '',
            input4 = '',
            input5 = '',
            delay1 = 1,
            delay2 = 1,
            delay3 = 1,
            delay4 = 1,
            delay5 = 1
        }
    },
    'flooder-settings')
    imguiVars = {
        windowState = imgui.ImBool(false),
        enabled = imgui.ImBool(false),
        input1 = imgui.ImBuffer(255),
        input2 = imgui.ImBuffer(255),
        input3 = imgui.ImBuffer(255),
        input4 = imgui.ImBuffer(255),
        input5 = imgui.ImBuffer(255),
        delay1 = imgui.ImInt(config.settings.delay1),
        delay2 = imgui.ImInt(config.settings.delay2),
        delay3 = imgui.ImInt(config.settings.delay3),
        delay4 = imgui.ImInt(config.settings.delay4),
        delay5 = imgui.ImInt(config.settings.delay5)
    }
    imguiVars.input1.v = config.settings.input1
    imguiVars.input2.v = config.settings.input2
    imguiVars.input3.v = config.settings.input3
    imguiVars.input4.v = config.settings.input4
    imguiVars.input5.v = config.settings.input5
    apply_custom_style()
    sampAddChatMessage("{60FF60}[Fflooder {DAA520}by {FF0000}KARLEONE] {FFFFFF}Загружен успешно!", -1)
    sampAddChatMessage("{60FF60}[Fflooder {DAA520}by {FF0000}KARLEONE] {FFFFFF}Команда активации /fs.", -1)
    sampRegisterChatCommand('fs', fs)
    while true do
        imgui.Process = imguiVars.windowState.v
        wait(0)
    end
    wait(-1)
end

function fs()
    imguiVars.windowState.v = not imguiVars.windowState.v
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.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.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.CheckMark]              = 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)
    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.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.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    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.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.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 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
 

Smeruxa

smeruxa.ru
Проверенный
1,434
800
хз шо сделал, но при заходе в игру, мне нужно нажимать ctr+r чтоб я смог открыть менюшку скрипта, потом после нескольких нажатий включить\выключить больше 6-10 раз, еще раз включаешь и у скрипта кд не работает почему то
Lua:
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local imgui = require 'imgui'
local inicfg = require 'inicfg'

function imgui.OnDrawFrame()
    w, h = getScreenResolution()
    if imguiVars.windowState.v then
        imgui.SetNextWindowSize(imgui.ImVec2(250, 350), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2(w / 2 , h / 2), imgui.Cond.FirsUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8'Flooder | Настройки by KARLEONE', imguiVars.windowState, imgui.WindowFlags.NoCollapse)
        imgui.Text(u8'Флуд серверными командами')
        imgui.InputText(u8'Текст##input1', imguiVars.input1)
        imgui.InputInt(u8'Задержка##delay1', imguiVars.delay1, 0, 0)
        imgui.InputText(u8'Текст##input2', imguiVars.input2)
        imgui.InputInt(u8'Задержка##delay2', imguiVars.delay2, 0, 0)
        imgui.InputText(u8'Текст##input3', imguiVars.input3)
        imgui.InputInt(u8'Задержка##delay3', imguiVars.delay3, 0, 0)
        imgui.InputText(u8'Текст##input5', imguiVars.input5)
        imgui.InputInt(u8'Задержка##delay5', imguiVars.delay5, 0, 0)
        imgui.Separator()
        imgui.Text(u8'Флуд любыми командами.')
        imgui.Text(u8'Отправляет команды в чат.')
        imgui.InputText(u8'Текст##input4', imguiVars.input4)
        imgui.InputInt(u8'Задержка##delay4', imguiVars.delay4, 0, 0)
        imgui.Separator()
        if imgui.Button(imguiVars.enabled.v and u8'Выключить' or u8'Включить', imgui.ImVec2(250, 20)) then
            imguiVars.enabled.v = not imguiVars.enabled.v
            if imguiVars.enabled.v then
                if #imguiVars.input1.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input1.v), imguiVars.delay1.v)
                end
                if #imguiVars.input2.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input2.v), imguiVars.delay2.v)
                end
                if #imguiVars.input3.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input3.v), imguiVars.delay3.v)
                end
                if #imguiVars.input5.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input5.v), imguiVars.delay5.v)
                end
                if #imguiVars.input4.v >= 1 then
                    lua_thread.create(flood, u8:decode(imguiVars.input4.v), imguiVars.delay4.v, true)
                end
            end
        end
        if imgui.Button(u8'Сохранить настройки', imgui.ImVec2(250, 20)) then
            inicfg.save({settings = {input1 = imguiVars.input1.v, input2 = imguiVars.input2.v, input3 = imguiVars.input3.v, input4 = imguiVars.input4.v,input5 = imguiVars.input5.v, delay1 = imguiVars.delay1.v, delay2 = imguiVars.delay2.v, delay3 = imguiVars.delay3.v, delay4 = imguiVars.delay4.v, delay5 = imguiVars.delay5.v,}}, 'flooder-settings')
        end
        imgui.End()
    end
end

function flood(text, delay, localcmd)
    while imguiVars.enabled.v do
        if localcmd then
            sampProcessChatInput(text)
        else
            sampSendChat(text)
        end
        wait(delay * 1000)
    end
end

function main()
    while not isSampfuncsLoaded() do
        wait(100)
    end
    config = inicfg.load({
        settings =
        {
            input1 = '',
            input2 = '',
            input3 = '',
            input4 = '',
            input5 = '',
            delay1 = 1,
            delay2 = 1,
            delay3 = 1,
            delay4 = 1,
            delay5 = 1
        }
    },
    'flooder-settings')
    imguiVars = {
        windowState = imgui.ImBool(false),
        enabled = imgui.ImBool(false),
        input1 = imgui.ImBuffer(255),
        input2 = imgui.ImBuffer(255),
        input3 = imgui.ImBuffer(255),
        input4 = imgui.ImBuffer(255),
        input5 = imgui.ImBuffer(255),
        delay1 = imgui.ImInt(config.settings.delay1),
        delay2 = imgui.ImInt(config.settings.delay2),
        delay3 = imgui.ImInt(config.settings.delay3),
        delay4 = imgui.ImInt(config.settings.delay4),
        delay5 = imgui.ImInt(config.settings.delay5)
    }
    imguiVars.input1.v = config.settings.input1
    imguiVars.input2.v = config.settings.input2
    imguiVars.input3.v = config.settings.input3
    imguiVars.input4.v = config.settings.input4
    imguiVars.input5.v = config.settings.input5
    apply_custom_style()
    sampAddChatMessage("{60FF60}[Fflooder {DAA520}by {FF0000}KARLEONE] {FFFFFF}Загружен успешно!", -1)
    sampAddChatMessage("{60FF60}[Fflooder {DAA520}by {FF0000}KARLEONE] {FFFFFF}Команда активации /fs.", -1)
    sampRegisterChatCommand('fs', fs)
    while true do
        imgui.Process = imguiVars.windowState.v
        wait(0)
    end
    wait(-1)
end

function fs()
    imguiVars.windowState.v = not imguiVars.windowState.v
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.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.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.CheckMark]              = 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)
    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.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.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    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.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.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 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
все это происходит из-за говнокода
 

Gorskin

t.me/gorskintgk
Проверенный
1,442
1,284
@Gorskin наверно может игра повиснуть, если повиснет то юзай вот так:
Lua:
local function RemoveLastLine(str)
    local pos = 0 -- start position
    while true do -- loop for searching newlines
        wait(0)
        local nl = string.find(str, "\n", pos, true) -- find next newline, true indicates we use plain search, this speeds up on LuaJIT.
        if not nl then break end -- We didn't find any newline or no newlines left.
        pos = nl + 1 -- Save newline position, + 1 is necessary to avoid infinite loop of scanning the same newline, so we search for newlines __after__ this character
    end
    if pos == 0 then return str end -- If didn't find any newline, return original string

    return string.sub(str, 1, pos - 2) -- Return substring from the beginning of the string up to last newline (- 2 returns new string without the last newline itself
end

local file = io.open(путь, "w")
if file then
    local content = lua_thread.create(RemoveLastLine, file:read("*a"))
    file:write(content)
    file:close()
end
удаляет вообще все что есть в txt...