Вопросы по 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

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,776
11,224
как использовать XOR в луа? ( cleo - 0B12: 1@ = 1@ XOR 1 )
Точнее сказать переключать переменную с 0 на 1 и обратно

так же интересует как прибавлять, убавлять и сравнивать значения в переменных
например то же хп в клео
if or
0@ == 100 (( в переменную ноль условно записано хп актера ))
0@ >= 100

так же интересует как провернуть такую штуку
....
1@ += 1 (( к переменной 1 прибавляется 1 ))
if 1@ == 500 (( если 1 переменная равна 500 ))
then 1@ = 0 (( тогда устанавливает на неё 0 ))
Lua:
--1
local active = false

sampRegisterChatCommand('switch_active', function()
    active = not active -- если active == true, то сменится на false и наоборот
end)

--2
local var_int = 50
if var_int >= 100 then
    sampAddChatMessage('var_int50 больше или равно 100')
end

--3
local var_int = 1
var_int = var_int + 1

if var_int == 500 then var_int = 0 end

я долго думал
и ничего не понял)

мне нужно переключать значение командой

sampRegisterChatCommand("hi", MAHEKEH)


function MAHEKEH(arg)
null = null or 1 -- xor
if null == 1 then sampAddChatMessage("BLASTHACK " ..Passed , 0xFF0000) else sampAddChatMessage("BLASTHACK " ..not passed , 0xFF0000)
end
end
end

или

if null == 1 then ... passed
if null == 0 then ... not passed
без else то есть

что то там такое должно было быть..
Lua:
local passed = false -- изначальное значение переменной

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('hi', function()
        passed = not passed -- если passed == true, то passed примет значение false и наоборот
        sampAddChatMessage('BLASTHACK '..(passed and 'PASSED' or 'NOT PASSED'), -1) -- если passed == true, то к строке "BLASTHACK " добавится текст 'PASSED', а если нет, то добавится текст 'NOT PASSED'
    end)
    wait(-1)
end
 
  • Bug
Реакции: MAHEKEH

Sanchez.

Известный
704
187
Первый раз работаю с либой мунбот, и когда я спавню моего бота, то он становится в афк. Как исправить?
Lua:
require 'lib.moonloader'

local mb = require('MoonBot')

local bots = {}

function main()
    while not isSampAvailable() do wait(0) end

    mb.registerIncomingRPC(12)
    mb.registerIncomingRPC(68)

    sampRegisterChatCommand('b.say', function(arg)
        
    end)

    sampRegisterChatCommand('b.spawn', function(arg)
        if arg:match('%d+') then
            local ind = tonumber(arg)
            for k, bot in pairs(bots) do
                if bot.index == ind then
                    local hb = mb.getBotHandleByIndex(bot.index)
                    if hb ~= nil then
                        hb:sendRequestClass(0)
                        hb:sendRequestSpawn()
                        hb:sendSpawn()
                        local x,y,z = getCharCoordinates(1)
                        bot.position = {x = x, y = y, z = z}
                        sampAddChatMessage('Спавню '.. bot.name, -1)
                    end
                end
            end
        end
    end)

    sampRegisterChatCommand('b.add', function(arg)
        local ip, port = sampGetCurrentServerAddress()
        local bot = mb.add(arg)
        table.insert(bots, {
            index = bot.index,
            name = bot.name,
            position = {
                x = 0,
                y = 0,
                z = 0,
            },
        })
        bot:connect(ip, port)
        sampAddChatMessage(string.format('Подключаю %s (index %d)', bot.name, bot.index), -1)
    end)

    sampRegisterChatCommand('b.remove', function(arg)
        local ind = tonumber(arg)
        for k, bot in pairs(bots) do
            if bot.index == ind then
                sampAddChatMessage('Отключаю '.. bot.name, -1)
                table.remove(bots, k)
                mb.remove(ind)
            end
        end
    end)

    while true do
        wait(0)
        mb.updateCallbacks()
    end
end

function onBotRPC(bot, rpcId, bs)
    --sampAddChatMessage('rpc '..rpcId)
    if rpcId == 12 then
        local x, y, z = bs:readFloat(), bs:readFloat(), bs:readFloat()
        for k, lBot in pairs(bots) do
            if lBot.index == bot.index then
                lBot.position = {x = x, y = y, z = z}
                sampAddChatMessage(string.format('Bot %d changed pos (x: %f, y: %f, z: %f)', bot.index, x, y, z), -1)
                break
            end
        end
    end
    if rpcId == 68 then
        bs:ignoreBits(48)
        local x, y, z = bs:readFloat(), bs:readFloat(), bs:readFloat()
        for k, lBot in pairs(bots) do
            if lBot.index == bot.index then
                lBot.position = {x = x, y = y, z = z}
                sampAddChatMessage(string.format('Bot %d changed pos (x: %f, y: %f, z: %f)', bot.index, x, y, z), -1)
                break
            end
        end
    end
end

function onScriptTerminate(script, quitGame)
    if script == thisScript() then
        mb.unload()
    end
end
 

Renty

Известный
151
80
Пацаны как сделать поиск в луа скрипте... Например у меня есть в луа скрипте Imgui окно в котором есть определенный текст. И мне нужно сделать строку ввода где человек сможет находить определенный текст из имеющегося.
 
  • Нравится
Реакции: William_Roses

abnomegd

Активный
335
35
govnocode:
require "lib.moonloader"
local keys = require "vkeys"
local imgui = require 'imgui'
local sampev   = require 'lib.samp.events'
local inicfg = require 'inicfg'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local directIni = "moonloader\\config\\settings.ini"

local mainIni = inicfg.load(nil, directIni)

local mainIni = inicfg.load({
    hotkey = {
        bindClock = "[18,82]",
        bindInvent = "[18,83]",
        bindLock = "[18,84]"
    }
}, directIni)

local config = inicfg.load(
    {
        scriptActivation = {
            fastBuy    = true
        }
    },
    'settings'
)

local configDescriptions = {
    fastBuy    = u8'FastBuy (позволяет покупать аптечки/маски быстро)',
}   

local rkeys = require 'rkeys'
imgui.HotKey = require('imgui_addons').HotKey

local tLastKeys = {}

local ActiveClockMenu = {
    v = decodeJson(mainIni.hotkey.bindClock)
}

local ActiveInventMenu = {
    v = decodeJson(mainIni.hotkey.bindInvent)
}

local ActiveLockMenu = {
    v = decodeJson(mainIni.hotkey.bindLock)
}

main_window_state = imgui.ImBool(false)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage("[BindARP]: {FFFFFF}Скрипт загружен!", 0x5CBCFF)
    sampAddChatMessage("[FBuy]: {FFFFFF}Скрипт загружен!", 0x5CBCFF)   
    sampRegisterChatCommand("bind", cmd_bind)
    sampRegisterChatCommand("fbuy", function(arg)
        lua_thread.create(function()
            local var1, var2 = string.match(arg, "(%w+) (%d+)")
            if var1 == nil or var1 == "" or var2 == nil or var2 == "" then
                sampAddChatMessage("[FBuy]: {FFFFFF}Ошибка, небыло введено нужное количество аптечек/масок!", 0x5CBCFF)
            else
                if var1 == "heal" then
                    sampAddChatMessage("[FBuy]: {FFFFFF}Вы начали скупать: {5CBCFF}" .. var2 .. " {FFFFFF}аптечек", 0x5CBCFF)
                    for i = 0, var2 do
                        sampSendChat("/buy")
                        wait(300)
                        sampSendDialogResponse(101, 1, 3,nil)
                        wait(200)
                        sampSendDialogResponse(374, 1, 0,nil)
                        i = i + 1
                        wait(200)
                    end
                elseif var1 == "mask" then
                    sampAddChatMessage("[FBuy]: {FFFFFF}Вы начали скупать: {5CBCFF}" .. var2 .. " {FFFFFF}масок", 0x5CBCFF)
                    for i = 0, var2 do
                        sampSendChat("/buy")
                        wait(300)
                        sampSendDialogResponse(101, 1, 9,nil)
                        wait(200)
                        sampSendDialogResponse(374, 1, 0,nil)
                        i = i + 1
                        wait(200)
                    end
                end
            end
        end)
    end)

    imgui.Process = false

    bindClock = rkeys.registerHotKey(ActiveClockMenu.v, true, clockFunc)
    bindInvent = rkeys.registerHotKey(ActiveInventMenu.v, true, inventFunc)
    bindLock = rkeys.registerHotKey(ActiveLockMenu.v, true, lockFunc)


    while true do
        wait(0)

    
    end
end

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

function clockFunc()
    sampSendChat("/c 60")
end

function inventFunc()
    sampSendChat("/i")
end

function lockFunc()
    sampSendChat("/lock 1")
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(400, 200), imgui.Cond.FirstUseEver)
        imgui.RenderInMenu = true -- Allowing rendering menu in afk

        apply_custom_style() -- Changing gui style

        imgui.Begin('Bind', imgui.WindowFlags.NoResize)

 -- Initialising checkboxes
 for key, value in pairs(configDescriptions) do
    if imgui.Checkbox(value, imgui.ImBool(config.scriptActivation[key])) then
        config.scriptActivation[key] = not config.scriptActivation[key]
    end
end

        imgui.Text(u8"Посмотреть время")
        imgui.SameLine()
        if imgui.HotKey("##1", ActiveClockMenu, tLastKeys, 100) then
            rkeys.changeHotKey(bindClock, ActiveClockMenu.v)
            sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveClockMenu.v), " + "), -1)
            sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveClockMenu.v), -1)

            mainIni.hotkey.bindClock = encodeJson(ActiveClockMenu.v)
            inicfg.save(mainIni, directIni)
        end

        imgui.Text(u8"Открыть инвентарь")
        imgui.SameLine()
        if imgui.HotKey("##2", ActiveInventMenu, tLastKeys, 100) then
            rkeys.changeHotKey(bindInvent, ActiveInventMenu.v)
            sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveInventMenu.v), " + "), -1)
            sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveInventMenu.v), -1)

            mainIni.hotkey.bindInvent = encodeJson(ActiveInventMenu.v)
            inicfg.save(mainIni, directIni)
        end

        imgui.Text(u8"Открыть/закрыть автомобиль-мотоцикл")
        imgui.SameLine()
        if imgui.HotKey("##3", ActiveLockMenu, tLastKeys, 100) then
            rkeys.changeHotKey(bindLock, ActiveLockMenu.v)
            sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveLockMenu.v), " + "), -1)
            sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveLockMenu.v), -1)

-- Savaing data in config while script dies
function onScriptTerminate(script, quitGame)
    if script == thisScript() then
        inicfg.save(config, 'advanceFixSettings')
    end
end

            mainIni.hotkey.bindLock = encodeJson(ActiveLockMenu.v)
            inicfg.save(mainIni, directIni)
        end

-- Setting cursor position
imgui.SetCursorPosX(imgui.GetWindowSize().x / 2.7 - imgui.CalcTextSize('Скрыть').x + imgui.GetStyle().ItemSpacing.x)
imgui.SetCursorPosY(imgui.GetWindowSize().y - imgui.CalcTextSize('Скрыть').y - imgui.GetStyle().WindowPadding.y - imgui.GetStyle().ItemSpacing.y)

-- Handles button pressing
if imgui.Button(u8'Скрыть') then
    imgui.Process = not imgui.Process
end

        imgui.End()
    end
end

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

    style.WindowPadding     = ImVec2(15, 15)
    style.WindowRounding    = 5.0
    style.FramePadding      = ImVec2(5, 5)
    style.FrameRounding     = 4.0
    style.ItemSpacing       = ImVec2(12, 8)
    style.ItemInnerSpacing  = ImVec2(8, 6)
    style.IndentSpacing     = 25.0
    style.ScrollbarSize     = 15.0
    style.ScrollbarRounding = 9.0
    style.GrabMinSize       = 5.0
    style.GrabRounding      = 3.0

    colors[clr.Text]                 = ImVec4(0.80, 0.80, 0.83, 1.00)
    colors[clr.TextDisabled]         = ImVec4(0.24, 0.23, 0.29, 1.00)
    colors[clr.WindowBg]             = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.ChildWindowBg]        = ImVec4(0.07, 0.07, 0.09, 1.00)
    colors[clr.PopupBg]              = ImVec4(0.07, 0.07, 0.09, 1.00)
    colors[clr.Border]               = ImVec4(0.80, 0.80, 0.83, 0.88)
    colors[clr.BorderShadow]         = ImVec4(0.92, 0.91, 0.88, 0.00)
    colors[clr.FrameBg]              = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.FrameBgHovered]       = ImVec4(0.24, 0.23, 0.29, 1.00)
    colors[clr.FrameBgActive]        = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.TitleBg]              = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.TitleBgCollapsed]     = ImVec4(1.00, 0.98, 0.95, 0.75)
    colors[clr.TitleBgActive]        = ImVec4(0.07, 0.07, 0.09, 1.00)
    colors[clr.MenuBarBg]            = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.ScrollbarBg]          = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.ScrollbarGrab]        = ImVec4(0.80, 0.80, 0.83, 0.31)
    colors[clr.ScrollbarGrabHovered] = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.ScrollbarGrabActive]  = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.ComboBg]              = ImVec4(0.19, 0.18, 0.21, 1.00)
    colors[clr.CheckMark]            = ImVec4(0.80, 0.80, 0.83, 0.31)
    colors[clr.SliderGrab]           = ImVec4(0.80, 0.80, 0.83, 0.31)
    colors[clr.SliderGrabActive]     = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.Button]               = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.ButtonHovered]        = ImVec4(0.24, 0.23, 0.29, 1.00)
    colors[clr.ButtonActive]         = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.Header]               = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.HeaderHovered]        = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.HeaderActive]         = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.ResizeGrip]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.ResizeGripHovered]    = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.ResizeGripActive]     = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.CloseButton]          = ImVec4(0.40, 0.39, 0.38, 0.16)
    colors[clr.CloseButtonHovered]   = ImVec4(0.40, 0.39, 0.38, 0.39)
    colors[clr.CloseButtonActive]    = ImVec4(0.40, 0.39, 0.38, 1.00)
    colors[clr.PlotLines]            = ImVec4(0.40, 0.39, 0.38, 0.63)
    colors[clr.PlotLinesHovered]     = ImVec4(0.25, 1.00, 0.00, 1.00)
    colors[clr.PlotHistogram]        = ImVec4(0.40, 0.39, 0.38, 0.63)
    colors[clr.PlotHistogramHovered] = ImVec4(0.25, 1.00, 0.00, 1.00)
    colors[clr.TextSelectedBg]       = ImVec4(0.25, 1.00, 0.00, 0.43)
    colors[clr.ModalWindowDarkening] = ImVec4(1.00, 0.98, 0.95, 0.73)
end

ну крч типо хотел сделать fastbuy через активацию в имгуи окне, ну никак реагирует есть метка или нет, fastbuy всё равно работает дальше,
 

madrasso

Потрачен
883
324
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Как сделать checkbox по середине? и input поле
imgui.SetCursorPosX((imgui.GetWindowWidth() - element width) / 2);

Пацаны как сделать поиск в луа скрипте... Например у меня есть в луа скрипте Imgui окно в котором есть определенный текст. И мне нужно сделать строку ввода где человек сможет находить определенный текст из имеющегося.
Делаешь InputText, где у тебя будет храниться поисковой запрос, далее парсишь нужные тебе данные, ищешь там содержание инпута, совпадает - выводишь.

Пример реализации: https://www.blast.hk/threads/55017/ (строки 187 - 217)
 
Последнее редактирование:
  • Нравится
Реакции: Renty

whitepower88

Новичок
14
0
как возможно реализовать проверку на клист? То есть узнать сначала свой клист а потом клист игрока на которого наведен прицел(за луа вообще не шарю помогите добрые люди)
 

abnomegd

Активный
335
35
script:
require "lib.moonloader"
local keys = require "vkeys"
local imgui = require 'imgui'
local sampev   = require 'lib.samp.events'
local inicfg = require 'inicfg'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local directIni = "moonloader\\config\\settings.ini"

local mainIni = inicfg.load(nil, directIni)

local mainIni = inicfg.load({
    hotkey = {
        bindClock = "[18,82]",
        bindInvent = "[18,83]",
        bindLock = "[18,84]"
    }
}, directIni)

local config = inicfg.load(
    {
        scriptActivation = {
            fastBuy    = true
        }
    },
    'settings'
)

local configDescriptions = {
    fastBuy    = u8'FastBuy (позволяет покупать аптечки/маски быстро)',
}   

local rkeys = require 'rkeys'
imgui.HotKey = require('imgui_addons').HotKey

local tLastKeys = {}

local ActiveClockMenu = {
    v = decodeJson(mainIni.hotkey.bindClock)
}

local ActiveInventMenu = {
    v = decodeJson(mainIni.hotkey.bindInvent)
}

local ActiveLockMenu = {
    v = decodeJson(mainIni.hotkey.bindLock)
}

main_window_state = imgui.ImBool(false)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage("[BindARP]: {FFFFFF}Скрипт загружен!", 0x5CBCFF)
    sampAddChatMessage("[FBuy]: {FFFFFF}Скрипт загружен!", 0x5CBCFF)   
    sampRegisterChatCommand("bind", cmd_bind)
    sampRegisterChatCommand("fbuy", function(arg)
        lua_thread.create(function()
            local var1, var2 = string.match(arg, "(%w+) (%d+)")
            if var1 == nil or var1 == "" or var2 == nil or var2 == "" then
                sampAddChatMessage("[FBuy]: {FFFFFF}Ошибка, небыло введено нужное количество аптечек/масок!", 0x5CBCFF)
            else
                if var1 == "heal" then
                    sampAddChatMessage("[FBuy]: {FFFFFF}Вы начали скупать: {5CBCFF}" .. var2 .. " {FFFFFF}аптечек", 0x5CBCFF)
                    for i = 0, var2 do
                        sampSendChat("/buy")
                        wait(300)
                        sampSendDialogResponse(101, 1, 3,nil)
                        wait(200)
                        sampSendDialogResponse(374, 1, 0,nil)
                        i = i + 1
                        wait(200)
                    end
                elseif var1 == "mask" then
                    sampAddChatMessage("[FBuy]: {FFFFFF}Вы начали скупать: {5CBCFF}" .. var2 .. " {FFFFFF}масок", 0x5CBCFF)
                    for i = 0, var2 do
                        sampSendChat("/buy")
                        wait(300)
                        sampSendDialogResponse(101, 1, 9,nil)
                        wait(200)
                        sampSendDialogResponse(374, 1, 0,nil)
                        i = i + 1
                        wait(200)
                    end
                end
            end
        end)
    end)

    imgui.Process = false

    bindClock = rkeys.registerHotKey(ActiveClockMenu.v, true, clockFunc)
    bindInvent = rkeys.registerHotKey(ActiveInventMenu.v, true, inventFunc)
    bindLock = rkeys.registerHotKey(ActiveLockMenu.v, true, lockFunc)


    while true do
        wait(0)

    
    end
end

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

function clockFunc()
    sampSendChat("/c 60")
end

function inventFunc()
    sampSendChat("/i")
end

function lockFunc()
    sampSendChat("/lock 1")
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(400, 200), imgui.Cond.FirstUseEver)
        imgui.RenderInMenu = true -- Allowing rendering menu in afk

        apply_custom_style() -- Changing gui style

        imgui.Begin('Bind', imgui.WindowFlags.NoResize)

 -- Initialising checkboxes
 for key, value in pairs(configDescriptions) do
    if imgui.Checkbox(value, imgui.ImBool(config.scriptActivation[key])) then
        config.scriptActivation[key] = not config.scriptActivation[key]
    end
end

        imgui.Text(u8"Посмотреть время")
        imgui.SameLine()
        if imgui.HotKey("##1", ActiveClockMenu, tLastKeys, 100) then
            rkeys.changeHotKey(bindClock, ActiveClockMenu.v)
            sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveClockMenu.v), " + "), -1)
            sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveClockMenu.v), -1)

            mainIni.hotkey.bindClock = encodeJson(ActiveClockMenu.v)
            inicfg.save(mainIni, directIni)
        end

        imgui.Text(u8"Открыть инвентарь")
        imgui.SameLine()
        if imgui.HotKey("##2", ActiveInventMenu, tLastKeys, 100) then
            rkeys.changeHotKey(bindInvent, ActiveInventMenu.v)
            sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveInventMenu.v), " + "), -1)
            sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveInventMenu.v), -1)

            mainIni.hotkey.bindInvent = encodeJson(ActiveInventMenu.v)
            inicfg.save(mainIni, directIni)
        end

        imgui.Text(u8"Открыть/закрыть автомобиль-мотоцикл")
        imgui.SameLine()
        if imgui.HotKey("##3", ActiveLockMenu, tLastKeys, 100) then
            rkeys.changeHotKey(bindLock, ActiveLockMenu.v)
            sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveLockMenu.v), " + "), -1)
            sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveLockMenu.v), -1)

-- Savaing data in config while script dies
function onScriptTerminate(script, quitGame)
    if script == thisScript() then
        inicfg.save(config, 'advanceFixSettings')
    end
end

            mainIni.hotkey.bindLock = encodeJson(ActiveLockMenu.v)
            inicfg.save(mainIni, directIni)
        end

-- Setting cursor position
imgui.SetCursorPosX(imgui.GetWindowSize().x / 2.7 - imgui.CalcTextSize('Скрыть').x + imgui.GetStyle().ItemSpacing.x)
imgui.SetCursorPosY(imgui.GetWindowSize().y - imgui.CalcTextSize('Скрыть').y - imgui.GetStyle().WindowPadding.y - imgui.GetStyle().ItemSpacing.y)

-- Handles button pressing
if imgui.Button(u8'Скрыть') then
    imgui.Process = not imgui.Process
end

        imgui.End()
    end
end

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

    style.WindowPadding     = ImVec2(15, 15)
    style.WindowRounding    = 5.0
    style.FramePadding      = ImVec2(5, 5)
    style.FrameRounding     = 4.0
    style.ItemSpacing       = ImVec2(12, 8)
    style.ItemInnerSpacing  = ImVec2(8, 6)
    style.IndentSpacing     = 25.0
    style.ScrollbarSize     = 15.0
    style.ScrollbarRounding = 9.0
    style.GrabMinSize       = 5.0
    style.GrabRounding      = 3.0

    colors[clr.Text]                 = ImVec4(0.80, 0.80, 0.83, 1.00)
    colors[clr.TextDisabled]         = ImVec4(0.24, 0.23, 0.29, 1.00)
    colors[clr.WindowBg]             = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.ChildWindowBg]        = ImVec4(0.07, 0.07, 0.09, 1.00)
    colors[clr.PopupBg]              = ImVec4(0.07, 0.07, 0.09, 1.00)
    colors[clr.Border]               = ImVec4(0.80, 0.80, 0.83, 0.88)
    colors[clr.BorderShadow]         = ImVec4(0.92, 0.91, 0.88, 0.00)
    colors[clr.FrameBg]              = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.FrameBgHovered]       = ImVec4(0.24, 0.23, 0.29, 1.00)
    colors[clr.FrameBgActive]        = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.TitleBg]              = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.TitleBgCollapsed]     = ImVec4(1.00, 0.98, 0.95, 0.75)
    colors[clr.TitleBgActive]        = ImVec4(0.07, 0.07, 0.09, 1.00)
    colors[clr.MenuBarBg]            = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.ScrollbarBg]          = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.ScrollbarGrab]        = ImVec4(0.80, 0.80, 0.83, 0.31)
    colors[clr.ScrollbarGrabHovered] = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.ScrollbarGrabActive]  = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.ComboBg]              = ImVec4(0.19, 0.18, 0.21, 1.00)
    colors[clr.CheckMark]            = ImVec4(0.80, 0.80, 0.83, 0.31)
    colors[clr.SliderGrab]           = ImVec4(0.80, 0.80, 0.83, 0.31)
    colors[clr.SliderGrabActive]     = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.Button]               = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.ButtonHovered]        = ImVec4(0.24, 0.23, 0.29, 1.00)
    colors[clr.ButtonActive]         = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.Header]               = ImVec4(0.10, 0.09, 0.12, 1.00)
    colors[clr.HeaderHovered]        = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.HeaderActive]         = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.ResizeGrip]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.ResizeGripHovered]    = ImVec4(0.56, 0.56, 0.58, 1.00)
    colors[clr.ResizeGripActive]     = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.CloseButton]          = ImVec4(0.40, 0.39, 0.38, 0.16)
    colors[clr.CloseButtonHovered]   = ImVec4(0.40, 0.39, 0.38, 0.39)
    colors[clr.CloseButtonActive]    = ImVec4(0.40, 0.39, 0.38, 1.00)
    colors[clr.PlotLines]            = ImVec4(0.40, 0.39, 0.38, 0.63)
    colors[clr.PlotLinesHovered]     = ImVec4(0.25, 1.00, 0.00, 1.00)
    colors[clr.PlotHistogram]        = ImVec4(0.40, 0.39, 0.38, 0.63)
    colors[clr.PlotHistogramHovered] = ImVec4(0.25, 1.00, 0.00, 1.00)
    colors[clr.TextSelectedBg]       = ImVec4(0.25, 1.00, 0.00, 0.43)
    colors[clr.ModalWindowDarkening] = ImVec4(1.00, 0.98, 0.95, 0.73)
end
ну крч типо хотел сделать fastbuy через активацию в имгуи окне, ну никак реагирует есть метка или нет, fastbuy всё равно работает дальше,
 

Sanchez.

Известный
704
187
Как правильно посадить моего бота в кар, чтобы не вылетал скрипт. Ну нужно как-то отправить синхру о машине, я так делаю, но крашит. Как это можно нормально реализовать? (библиотека MoonBot)
 

Lance Sterling

Потрачен
140
8
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
script::
local sampev = require 'lib.samp.events'

local lauch = 0



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

    local thread = lua_thread.create_suspended(thread_function)

    print("{1F1FD6}[Auto Smoke] {1FD626}Успешно загружено,{FFFFFF} автор скрипта: vk.com/maksytka2009")
    sampAddChatMessage("{1F1FD6}[Auto Smoke] {1FD626}Успешно загружено,{FFFFFF} автор скрипта: vk.com/maksytka2009",-1)
    sampRegisterChatCommand("asmoke", cmd_launch)
end

function thread_function(opt)
    if opt == 'launch' then
        wait(30000)
    end

    if opt == 'find' then
        wait(1000)
    end
end

function cmd_launch(arg)
    if lauch == 0 then
        lauch = 1
        sampAddChatMessage("{1F1FD6}[Auto Smoke] {1FD626}Включено!",-1)
        while true do
            sampSendChat("/smoke")
            thread:run("launch")
        end
    else
        launch = 0
        sampAddChatMessage("{1F1FD6}[Auto Smoke] {1FD626}Выключено!",-1)
    end
end

function sampev.onServerMessage(color, text)
    if string.find(text, 'и попытался закурить (Неудачно)', 1, true) then
        thread:run("find")
        sampSendChat("/smoke")
        return false
    end
end
не знаю что делать, 1 раз ввожу работает, хочу выключить уже пишет комманды нету,
log:
[ML] (error) smoke.lua: D:\my samp\GTA San Andreas\moonloader\smoke.lua:34: attempt to index global 'thread' (a nil value)
stack traceback:
    D:\my samp\GTA San Andreas\moonloader\smoke.lua:34: in function <D:\my samp\GTA San Andreas\moonloader\smoke.lua:28>
[ML] (error) smoke.lua: Script died due to an error. (01CD437C)
 

#SameLine

Активный
417
37
imgui.SetCursorPosX((imgui.GetWindowWidth() - element width) / 2);


Делаешь InputText, где у тебя будет храниться поисковой запрос, далее парсишь нужные тебе данные, ищешь там содержание инпута, совпадает - выводишь.

Пример реализации: https://www.blast.hk/threads/55017/ (строки 187 - 217)
Куда пихать то его?
 

Morse

Потрачен
436
70
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
если заменяю текст в чате вот так, то потом не ищет в нем через text:find, как исправить?
Lua:
    if text:find("%[A%] (%w+_%w+)%[(%d+)%]: .+") and color == -1714683649 then
        nickachat, idachat, textachat = text:match("%[A%] (%w+_%w+)%[(%d+)%]: (.*)")
        colachat = imgui.ImColor(cfg.colors.clradmchat)
        r, g, b, a = colachat:GetRGBA()
        tachat = string.format("[A] {%06X}"..nickachat..'['..idachat..']: {%06X}'..textachat, join_rgb(r, g, b), 0x8AFF41)
        return {join_argb(r, g, b, a), tachat}
    end
 

abnomegd

Активный
335
35
Почему не работает скрипт, мб end'ы поставил неверно)
script:
local lsampev, sp = pcall(require, 'lib.samp.events')
local inicfg = require 'inicfg'
local directini = "moonloader\\config\\AdvanceConnect.ini"
local mainini = inicfg.load(nil, directini)
    require 'lib.moonloader'
    parol = (mainini.config.parol)
    pinkod = (mainini.config.pinkod)
    
    function main()
        repeat wait(0) until isSampAvailable()
        wait(-1)
    end   
    sampRegisterChatCommand("reс"--[[Поменяйте re на команду, какую хотите]], reconnect)
    sampAddChatMessage("{0ff000}[AdvanceConnect] {FFA500}Скрипт загружен.", -1)

    function sp.onShowDialog(id, style, title, button1, button2, text)
        if id == (2) then
            sampSendDialogResponse(id, 1, _, parol)
            return false
        end
        if id == (1) then
        sampSendDialogResponse(id, 1, _, parol)
            return false
        end
        if id == (10) then
        sampSendDialogResponse(id, 1, _, parol)
            return false
        end

function sp.onShowDialog(id, style, title, button1, button2, text)
                if id == (199) then
        sampSendDialogResponse(id, 1, _, pinkod)
            return false
        end
    end

    while true do
        wait(1)
        local chatstring = sampGetChatString(99)
        if chatstring == "Server closed the connection." or chatstring == "You are banned from this server." then
        sampDisconnectWithReason(false)
            sampAddChatMessage("Wait reconnecting...", 0xa9c4e4)
            wait(5000)
            sampSetGamestate(1)
        end
    end

if res and time ~= nil then
    sampDisconnectWithReason(quit)
    wait(time*1000)
    sampSetGamestate(1)
    res= false
    else if res and time == nil then
        sampDisconnectWithReason(quit)
        wait(15500)
        sampSetGamestate(1)
        res= false
        end
    end

function reconnect(param)
time = tonumber(param)
res = true
end
end