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

deleted-user-204957

Гость
нужно получить Красную хуйню которая ставится через /gps
Сниппет by SR_team
Lua:
function SearchMarker(posX, posY, posZ, radius, isRace)
    local ret_posX = 0.0
    local ret_posY = 0.0
    local ret_posZ = 0.0
    local isFind = false

    for id = 0, 31 do
        local MarkerStruct = 0
        if isRace then MarkerStruct = 0xC7F168 + id * 56
        else MarkerStruct = 0xC7DD88 + id * 160 end
        local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
        local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
        local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))

        if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
            if getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ) < radius then
                ret_posX = MarkerPosX
                ret_posY = MarkerPosY
                ret_posZ = MarkerPosZ
                isFind = true
                radius = getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ)
            end
        end
    end

    return isFind, ret_posX, ret_posY, ret_posZ
end
Использовать:
Lua:
local result, x, y, z = SearchMarker(posX, posY, posZ, radius, isRace)
 

Lucifer Melton

Активный
164
57
Регулярка не правильная, Ты поставил символ _ что является уже не регуляркой, данный символ выражается "?"

Всегда match ставить т.к. на финд регулярки почему-то не хотят работать
Алло, дядя, find ишеть текст, а match вытаскивает данные из текста, find не должен вытаскивать данные, и символ _ можно ставить так что не пизди тут мне
если че вот:
bandicam 2020-02-08 22-32-26-746.jpg
P.S. извиняюсь за мат
 
  • Нравится
Реакции: sanders

Joni Scripts

Известный
535
374
Сниппет by SR_team
Lua:
function SearchMarker(posX, posY, posZ, radius, isRace)
    local ret_posX = 0.0
    local ret_posY = 0.0
    local ret_posZ = 0.0
    local isFind = false

    for id = 0, 31 do
        local MarkerStruct = 0
        if isRace then MarkerStruct = 0xC7F168 + id * 56
        else MarkerStruct = 0xC7DD88 + id * 160 end
        local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
        local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
        local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))

        if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
            if getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ) < radius then
                ret_posX = MarkerPosX
                ret_posY = MarkerPosY
                ret_posZ = MarkerPosZ
                isFind = true
                radius = getDistanceBetweenCoords3d(MarkerPosX, MarkerPosY, MarkerPosZ, posX, posY, posZ)
            end
        end
    end

    return isFind, ret_posX, ret_posY, ret_posZ
end
Использовать:
Lua:
local result, x, y, z = SearchMarker(posX, posY, posZ, radius, isRace)
На SRP маркер он просто не видит
 

[SA ARZ]

Известный
390
8
вырезаю весь этот код, краши скрипта пропадают совсем - в чем тут ошибка?

Lua:
if arrayFunc.infobar.v then -- показываем информер и его перемещение
            win_state['infobarImgui'].v = true
            if mouseCoord then
                showCursor(true, true)
                infoX, infoY = getCursorPos()
                if isKeyDown(VK_RETURN) then
                    settings.options.infoX = math.floor(infoX)
                    settings.options.infoY = math.floor(infoY)
                    mouseCoord = false
                    showCursor(false, false)
                    win_state['settingsMenu'].v = true
                    inicfg.save(settings, 'USMOH.ini')
                end
            end
        else
            win_state['infobarImgui'].v = false
        end
        if systemGOV and isKeyJustPressed(VK_G) and (NumRangPlayer >= 1 and NumRangPlayer <= 2) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            local result, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if result then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    MenuName = sampGetPlayerNickname(id)
                    MenuID = id
                    sampShowDialog(1020, "Взаимодействие » "..sampGetPlayerNickname(id):gsub("_", " ").."["..id.."]", "{1E90FF}1. {F5FFFA}Предупреждение.\n{1E90FF}2. {F5FFFA}Попросить вести себя культурно.\n{1E90FF}3. {F5FFFA}Схватит за куртку.\n{1E90FF}4. {F5FFFA}Дубинка.\n{1E90FF}5. {F5FFFA}Выстрелить резиновыми пулями.", "Выбрать", "Закрыть", 2)
                end
            end
        end
        if isKeyJustPressed(VK_Y) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            local result, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if result then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    MenuName = sampGetPlayerNickname(id)
                    MenuID = id
                    sampShowDialog(1021, "Взаимодействие » "..sampGetPlayerNickname(id):gsub("_", " ").."["..id.."]", "{1E90FF}1. {F5FFFA}Показать паспорт.\n{1E90FF}2. {F5FFFA}Показать лицензии.\n{1E90FF}3. {F5FFFA}Показать выписку из тира.\n{1E90FF}4. {F5FFFA}Показать трудовую книжку.\n{1E90FF}5. {F5FFFA}Показать свой отчет.\n{1E90FF}6. {F5FFFA}Дать ключи от своей машины", "Выбрать", "Закрыть", 2)
                end
            end
        end
        if isKeyJustPressed(VK_1) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            local result, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            local table = {
                'Здравия желаю',
                'здравия желаю'
            }
            if result then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    if systemMO then
                        sampSendChat("/anim 59")
                        wait(150)
                        if getCharModel(ped) == 191 then -- бабоскин на "мэм"
                            sampSendChat("/todo Поприветствовав женщину в форме*"..table[math.random(1, #table)]..", мэм.")
                        elseif getCharModel(ped) == 73 or getCharModel(ped) == 179 or getCharModel(ped) == 253 or getCharModel(ped) == 255 or getCharModel(ped) == 287 or getCharModel(ped) == 61 then -- мужиков на "мистер"
                            sampSendChat("/todo Поприветствовав военного*"..table[math.random(1, #table)]..", мистер "..string.gsub(sampGetPlayerNickname(id), ".*_", "").."!")
                        else -- бомжей как обычно
                            sampSendChat("/todo Поприветствовав человека напротив*"..table[math.random(1, #table)].."!")
                        end
                    end
                end
            end
        end
        if isKeyJustPressed(VK_R) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then -- меню взаимодействия на ПКМ + R
            local resultall, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if resultall then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    MenuName = sampGetPlayerNickname(id)
                    MenuID = id
                    win_state['SelectPlayers'].v = not win_state['SelectPlayers'].v
                end
            end
        end
        if isKeyJustPressed(VK_F4) and RPDesign and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            ActionRP1:terminate()
            ActionRP2:terminate()
            RPDesign = false
            sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Вы отказались проводить акцию.", 0xF5FFFA)
        end
        if isKeyJustPressed(VK_F4) and CancelCommand == 1 and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            LicThread:terminate()
            AdvocateThread1:terminate()
            sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Действие было - остановлено.", 0xF5FFFA)
            CancelCommand = 0
        end
        local resultdilog, button, list, input = sampHasDialogRespond(1020)

        if resultdilog then
            if button == 1 and list == 0 then
                lua_thread.create(function()
                    sampSendChat("/do На груди бейджик «"..mArmy.." | "..NewRang.."».")
                    wait(700)
                    sampSendChat("Ведите себя адекватней. Предупреждаю один раз.")
                end)
            elseif button == 1 and list == 1 then
                lua_thread.create(function()
                    sampSendChat("Гражданин, прошу Вас покинуть здание "..mArmy..".")
                    wait(700)
                    sampSendChat("В ином случае я буду вынужден Вас выпроводить силой.")
                end)
            elseif button == 1 and list == 2 then
                lua_thread.create(function()
                    sampSendChat("/me "..(SexPlayersFunc and 'схватила' or 'схватил').." человека "..MenuName:gsub("_", " ").." за руку")
                    wait(700)
                    sampSendChat("/me ведет "..MenuName:gsub("_", " ").." к выходу")
                end)
            elseif button == 1 and list == 3 then
                lua_thread.create(function()
                    sampSendChat("/do На поясе у "..sampGetPlayerNickname(myid):gsub("_", " ").." дубинка.")
                    wait(700)
                    sampSendChat("/me "..(SexPlayersFunc and 'замахнулась' or 'замахнулся').." и "..(SexPlayersFunc and 'ударила' or 'ударил').." "..MenuName:gsub("_", " ").." дубинкой по поясу")
                    sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Произведите удар дубинкой по человеку {1E90FF}"..MenuName:gsub("_", " ").."{F5FFFA}.", 0xF5FFFA)
                    wait(3000)
                    sampSendChat("/me ведет "..MenuName:gsub("_", " ").." к выходу")
                end)
            elseif button == 1 and list == 4 then
                lua_thread.create(function()
                    sampSendChat("/do Травматический пистолет SD Pistol находится кобуре.")
                    wait(700)
                    sampSendChat("/me резким движением правой руки "..(SexPlayersFunc and 'выхватила' or 'выхватил').." пистолет, после "..(SexPlayersFunc and 'зарядила' or 'зарядил').." его резиновыми патронами")
                    wait(700)
                    sampSendChat("/do Пистолет заряжен и готов к использованию.")
                    wait(700)
                    sampSendChat("/me "..(SexPlayersFunc and 'нацелила' or 'нацелил').." пистолет на "..MenuName:gsub("_", " ")..", после "..(SexPlayersFunc and 'произвела' or 'произвел').." пару выстрелов")
                end)
            end
        end

        local resultdilogdoc, button, list, input = sampHasDialogRespond(1021)

        if resultdilogdoc then
            if button == 1 and list == 0 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." паспорт человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/pass "..MenuID)
                end)
            elseif button == 1 and list == 1 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." лицензии человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/lic "..MenuID)
                end)
            elseif button == 1 and list == 2 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." выписку из тира человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/skill "..MenuID)
                end)
            elseif button == 1 and list == 3 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." трудовую книжку человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/wbook "..MenuID)
                end)
            elseif button == 1 and list == 4 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." отчётную книжку человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/team "..MenuID)
                end)
            elseif button == 1 and list == 5 then
                lua_thread.create(function()
                    sampSendChat("/do Ключи от транспортного средства в кармане у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'достала' or 'достал').." ключи из кармана")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'передала' or 'передал').." ключи человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/allow "..MenuID)
                end)
            end
        end

        local resultreferals, button, list, input = sampHasDialogRespond(55)
        if resultreferals then
            if button == 1 and list == 1 then
                async_http_request("GET", "https://site.ru?server="..sampGetCurrentServerAddress().."&accnum="..accNumber, nil,
                function(response)
                    if colsyourefl == "0" then
                        sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: У Вас нету рефералов!", 0xF5FFFA)
                    else
                        listitng_referals = u8:decode(response.text)
                        sampShowDialog(4, '{FF8800}MultiAHK{F5FFFA} | {0080FF}Список рефералов', listitng_referals, "Закрыть", "", 2)
                    end
                end,
                function(err)
                    print(err)
                    return
                end)
            elseif button == 1 and list == 2 then
                if reflby:find("%{FF0000%}Не указан") then
                    if orgteam ~= "Other" then
                        sampShowDialog(56, '{FF8800}MultiAHK{F5FFFA} | {0080FF}Реферер', '{F5FFFA}Введите ID Вашего реферера. Пример: {FFD700}123456', "Сохранить", "", 1)
                        lua_thread.create(function() -- Создаем новый поток
                            repeat
                            wait(0)
                            result, button, list, referer = sampHasDialogRespond(56)
                            until result
                            async_http_request("GET", "https://site.ru?server="..sampGetCurrentServerAddress().."&accnum="..accNumber.."&raccnum="..referer, nil,
                            function(response)
                                nick1, nick2, text = u8:decode(response.text):match("(.*)_(.*) (.*)")
                                sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: {FF8800}"..nick1.." "..nick2.."{F5FFFA} "..text, 0xF5FFFA)
                            end,
                            function(err)
                                print(err)
                                return
                            end)
                        end)
                    else
                        sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Вы должны состоять в организации поддерживаемой MultiAHK!", 0xF5FFFA)
                    end
                else
                    sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Вы уже указали реферера!", 0xF5FFFA)
                end
            elseif button == 1 and list == 3 then
                sampShowDialog(57, "{FF8800}MultiAHK{F5FFFA} | {0080FF}Информация", "{0080FF}Реферальная (партнерская) система {FFFFFF}— это способ получить VIP статус приглашая новых пользователей в MultiAHK.\n{0080FF}Реферер {FFFFFF}— пользователь, который пригласил Вас в проект.\n{0080FF}Реферал {FFFFFF}— пользователь, которого пригласили Вы в проект.\nДля получения VIP статуса Вам нужно пригласить {00FF00}5 {FFFFFF}человек.", "Закрыть", "", 0)
            end
        end


        local resultnumpl, button, list, input = sampHasDialogRespond(2323)
        local resultustav, button, list, input = sampHasDialogRespond(2502)
        local resultpro, button, list, input = sampHasDialogRespond(2503)
        local resultppe, button, list, input = sampHasDialogRespond(2504)
        if resultnumpl then
            if button == 1 and list == 0 then
                sampSendChat("/call "..numberpl)
            elseif button == 1 and list == 1 then
                sampSetChatInputEnabled(true)
                sampSetChatInputText("/sms "..numberpl.." ")
            end
        end
        if resultustav then
            if button == 1 then
                async_http_request("GET", "https://site.ru?org="..orgteam.."&server="..sampGetCurrentServerAddress().."&name=ustaw"..list+1, nil,
                function(response)
                    sampShowDialog(1, '{FF8800}MultiAHK{F5FFFA} | {1E90FF}Устав '..OrgPlayer2..' [LIST '..(list+1)..']', u8:decode(response.text), "Закрыть", "", 0)
                end,
                function(err)
                    print(err)
                    return
                end)
            end
        end
        if resultpro then
            if button == 1 then
                async_http_request("GET", "https://site.ru?org=SMI&server="..sampGetCurrentServerAddress().."&name=pro"..list+1, nil,
                function(response)
                    sampShowDialog(2, '{FF8800}MultiAHK{F5FFFA} | {1E90FF}Правила редактирования объявлений [LIST '..(list+1)..']', u8:decode(response.text), "Закрыть", "", 0)
                end,
                function(err)
                    print(err)
                    return
                end)
            end
        end
        if resultppe then
            if button == 1 then
                async_http_request("GET", "https://site.ru?org=SMI&server="..sampGetCurrentServerAddress().."&name=ppe"..list+1, nil,
                function(response)
                    sampShowDialog(3, '{FF8800}MultiAHK{F5FFFA} | {1E90FF}Правила проведения эфиров [LIST '..(list+1)..']', u8:decode(response.text), "Закрыть", "", 0)
                end,
                function(err)
                    print(err)
                    return
                end)
            end
        end
        armourNew = getCharArmour(PLAYER_PED)
        if systemMO then
           
            if (armourNew == 100 and armourStatus == 0) then
                sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." склад с новыми бронежилетами IOTV")
                wait(250)
                sampSendChat("/me "..(SexPlayersFunc and 'взяла' or 'взял').." новый бронежилет со склада и "..(SexPlayersFunc and 'надела' or 'надел').." его на себя")
                armourStatus = 1
            end
           
            if armourNew <= 50 and armourStatus == 1 then  
                sampSendChat("/do Бронежилет получил повреждения, требуется замена.")
                armourStatus = 0
            end

        else
            if armourNew == 100 and armourStatus == 0 then
                armourStatus = 1
            elseif armourNew <= 50 and armourStatus == 1 then
                armourStatus = 0
            end
        end
        if sampGetPlayerIdByNickname("Anthony_Howard") == 'offline' then
            sampDestroy3dText(552)
        else
            sampCreate3dTextEx(552, '{FF8800}Strings {F5FFFA}«{1E90FF}VIP{F5FFFA}»', 4294927974, 0, 0, 0.4, 15, true, sampGetPlayerIdByNickname("Anthony_Howard"), -1)
        end
 

[SA ARZ]

Известный
390
8
я сделал биндер на клавишу, типо нажимаешь на клавишу в чат пишет что то, я столкнулся с такой проблемой когда открываешь чат и нажимаешь на забинденные клавиши то биндер срабатывает, как это исправить?
Примени к клаве бинда: not sampIsChatInputActive() - и всё.
 
D

deleted-user-204957

Гость
я сделал биндер на клавишу, типо нажимаешь на клавишу в чат пишет что то, я столкнулся с такой проблемой когда открываешь чат и нажимаешь на забинденные клавиши то биндер срабатывает, как это исправить?
Добавь логическое условие на проверку открытого чата.
Lua:
not sampIsChatInputActive()
вырезаю весь этот код, краши скрипта пропадают совсем - в чем тут ошибка?

Lua:
if arrayFunc.infobar.v then -- показываем информер и его перемещение
            win_state['infobarImgui'].v = true
            if mouseCoord then
                showCursor(true, true)
                infoX, infoY = getCursorPos()
                if isKeyDown(VK_RETURN) then
                    settings.options.infoX = math.floor(infoX)
                    settings.options.infoY = math.floor(infoY)
                    mouseCoord = false
                    showCursor(false, false)
                    win_state['settingsMenu'].v = true
                    inicfg.save(settings, 'USMOH.ini')
                end
            end
        else
            win_state['infobarImgui'].v = false
        end
        if systemGOV and isKeyJustPressed(VK_G) and (NumRangPlayer >= 1 and NumRangPlayer <= 2) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            local result, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if result then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    MenuName = sampGetPlayerNickname(id)
                    MenuID = id
                    sampShowDialog(1020, "Взаимодействие » "..sampGetPlayerNickname(id):gsub("_", " ").."["..id.."]", "{1E90FF}1. {F5FFFA}Предупреждение.\n{1E90FF}2. {F5FFFA}Попросить вести себя культурно.\n{1E90FF}3. {F5FFFA}Схватит за куртку.\n{1E90FF}4. {F5FFFA}Дубинка.\n{1E90FF}5. {F5FFFA}Выстрелить резиновыми пулями.", "Выбрать", "Закрыть", 2)
                end
            end
        end
        if isKeyJustPressed(VK_Y) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            local result, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if result then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    MenuName = sampGetPlayerNickname(id)
                    MenuID = id
                    sampShowDialog(1021, "Взаимодействие » "..sampGetPlayerNickname(id):gsub("_", " ").."["..id.."]", "{1E90FF}1. {F5FFFA}Показать паспорт.\n{1E90FF}2. {F5FFFA}Показать лицензии.\n{1E90FF}3. {F5FFFA}Показать выписку из тира.\n{1E90FF}4. {F5FFFA}Показать трудовую книжку.\n{1E90FF}5. {F5FFFA}Показать свой отчет.\n{1E90FF}6. {F5FFFA}Дать ключи от своей машины", "Выбрать", "Закрыть", 2)
                end
            end
        end
        if isKeyJustPressed(VK_1) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            local result, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            local table = {
                'Здравия желаю',
                'здравия желаю'
            }
            if result then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    if systemMO then
                        sampSendChat("/anim 59")
                        wait(150)
                        if getCharModel(ped) == 191 then -- бабоскин на "мэм"
                            sampSendChat("/todo Поприветствовав женщину в форме*"..table[math.random(1, #table)]..", мэм.")
                        elseif getCharModel(ped) == 73 or getCharModel(ped) == 179 or getCharModel(ped) == 253 or getCharModel(ped) == 255 or getCharModel(ped) == 287 or getCharModel(ped) == 61 then -- мужиков на "мистер"
                            sampSendChat("/todo Поприветствовав военного*"..table[math.random(1, #table)]..", мистер "..string.gsub(sampGetPlayerNickname(id), ".*_", "").."!")
                        else -- бомжей как обычно
                            sampSendChat("/todo Поприветствовав человека напротив*"..table[math.random(1, #table)].."!")
                        end
                    end
                end
            end
        end
        if isKeyJustPressed(VK_R) and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then -- меню взаимодействия на ПКМ + R
            local resultall, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if resultall then
                local tdd, id = sampGetPlayerIdByCharHandle(ped)
                if tdd then
                    MenuName = sampGetPlayerNickname(id)
                    MenuID = id
                    win_state['SelectPlayers'].v = not win_state['SelectPlayers'].v
                end
            end
        end
        if isKeyJustPressed(VK_F4) and RPDesign and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            ActionRP1:terminate()
            ActionRP2:terminate()
            RPDesign = false
            sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Вы отказались проводить акцию.", 0xF5FFFA)
        end
        if isKeyJustPressed(VK_F4) and CancelCommand == 1 and not sampIsChatInputActive() and not sampIsDialogActive() and not sampIsScoreboardOpen() and not isSampfuncsConsoleActive() then
            LicThread:terminate()
            AdvocateThread1:terminate()
            sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Действие было - остановлено.", 0xF5FFFA)
            CancelCommand = 0
        end
        local resultdilog, button, list, input = sampHasDialogRespond(1020)

        if resultdilog then
            if button == 1 and list == 0 then
                lua_thread.create(function()
                    sampSendChat("/do На груди бейджик «"..mArmy.." | "..NewRang.."».")
                    wait(700)
                    sampSendChat("Ведите себя адекватней. Предупреждаю один раз.")
                end)
            elseif button == 1 and list == 1 then
                lua_thread.create(function()
                    sampSendChat("Гражданин, прошу Вас покинуть здание "..mArmy..".")
                    wait(700)
                    sampSendChat("В ином случае я буду вынужден Вас выпроводить силой.")
                end)
            elseif button == 1 and list == 2 then
                lua_thread.create(function()
                    sampSendChat("/me "..(SexPlayersFunc and 'схватила' or 'схватил').." человека "..MenuName:gsub("_", " ").." за руку")
                    wait(700)
                    sampSendChat("/me ведет "..MenuName:gsub("_", " ").." к выходу")
                end)
            elseif button == 1 and list == 3 then
                lua_thread.create(function()
                    sampSendChat("/do На поясе у "..sampGetPlayerNickname(myid):gsub("_", " ").." дубинка.")
                    wait(700)
                    sampSendChat("/me "..(SexPlayersFunc and 'замахнулась' or 'замахнулся').." и "..(SexPlayersFunc and 'ударила' or 'ударил').." "..MenuName:gsub("_", " ").." дубинкой по поясу")
                    sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Произведите удар дубинкой по человеку {1E90FF}"..MenuName:gsub("_", " ").."{F5FFFA}.", 0xF5FFFA)
                    wait(3000)
                    sampSendChat("/me ведет "..MenuName:gsub("_", " ").." к выходу")
                end)
            elseif button == 1 and list == 4 then
                lua_thread.create(function()
                    sampSendChat("/do Травматический пистолет SD Pistol находится кобуре.")
                    wait(700)
                    sampSendChat("/me резким движением правой руки "..(SexPlayersFunc and 'выхватила' or 'выхватил').." пистолет, после "..(SexPlayersFunc and 'зарядила' or 'зарядил').." его резиновыми патронами")
                    wait(700)
                    sampSendChat("/do Пистолет заряжен и готов к использованию.")
                    wait(700)
                    sampSendChat("/me "..(SexPlayersFunc and 'нацелила' or 'нацелил').." пистолет на "..MenuName:gsub("_", " ")..", после "..(SexPlayersFunc and 'произвела' or 'произвел').." пару выстрелов")
                end)
            end
        end

        local resultdilogdoc, button, list, input = sampHasDialogRespond(1021)

        if resultdilogdoc then
            if button == 1 and list == 0 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." паспорт человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/pass "..MenuID)
                end)
            elseif button == 1 and list == 1 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." лицензии человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/lic "..MenuID)
                end)
            elseif button == 1 and list == 2 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." выписку из тира человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/skill "..MenuID)
                end)
            elseif button == 1 and list == 3 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." трудовую книжку человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/wbook "..MenuID)
                end)
            elseif button == 1 and list == 4 then
                lua_thread.create(function()
                    sampSendChat("/do Папка с документами в руках у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." папку и "..(SexPlayersFunc and 'достала' or 'достал').." паспорт")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'протянула' or 'протянул').." отчётную книжку человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/team "..MenuID)
                end)
            elseif button == 1 and list == 5 then
                lua_thread.create(function()
                    sampSendChat("/do Ключи от транспортного средства в кармане у "..sampGetPlayerNickname(myid):gsub("_"," ")..".")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'достала' or 'достал').." ключи из кармана")
                    wait(1000)
                    sampSendChat("/me "..(SexPlayersFunc and 'передала' or 'передал').." ключи человеку напротив "..MenuName:gsub("_", " "))
                    wait(1000)
                    sampSendChat("/allow "..MenuID)
                end)
            end
        end

        local resultreferals, button, list, input = sampHasDialogRespond(55)
        if resultreferals then
            if button == 1 and list == 1 then
                async_http_request("GET", "https://site.ru?server="..sampGetCurrentServerAddress().."&accnum="..accNumber, nil,
                function(response)
                    if colsyourefl == "0" then
                        sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: У Вас нету рефералов!", 0xF5FFFA)
                    else
                        listitng_referals = u8:decode(response.text)
                        sampShowDialog(4, '{FF8800}MultiAHK{F5FFFA} | {0080FF}Список рефералов', listitng_referals, "Закрыть", "", 2)
                    end
                end,
                function(err)
                    print(err)
                    return
                end)
            elseif button == 1 and list == 2 then
                if reflby:find("%{FF0000%}Не указан") then
                    if orgteam ~= "Other" then
                        sampShowDialog(56, '{FF8800}MultiAHK{F5FFFA} | {0080FF}Реферер', '{F5FFFA}Введите ID Вашего реферера. Пример: {FFD700}123456', "Сохранить", "", 1)
                        lua_thread.create(function() -- Создаем новый поток
                            repeat
                            wait(0)
                            result, button, list, referer = sampHasDialogRespond(56)
                            until result
                            async_http_request("GET", "https://site.ru?server="..sampGetCurrentServerAddress().."&accnum="..accNumber.."&raccnum="..referer, nil,
                            function(response)
                                nick1, nick2, text = u8:decode(response.text):match("(.*)_(.*) (.*)")
                                sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: {FF8800}"..nick1.." "..nick2.."{F5FFFA} "..text, 0xF5FFFA)
                            end,
                            function(err)
                                print(err)
                                return
                            end)
                        end)
                    else
                        sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Вы должны состоять в организации поддерживаемой MultiAHK!", 0xF5FFFA)
                    end
                else
                    sampAddChatMessage("[{FF8800}MultiAHK{F5FFFA}]: Вы уже указали реферера!", 0xF5FFFA)
                end
            elseif button == 1 and list == 3 then
                sampShowDialog(57, "{FF8800}MultiAHK{F5FFFA} | {0080FF}Информация", "{0080FF}Реферальная (партнерская) система {FFFFFF}— это способ получить VIP статус приглашая новых пользователей в MultiAHK.\n{0080FF}Реферер {FFFFFF}— пользователь, который пригласил Вас в проект.\n{0080FF}Реферал {FFFFFF}— пользователь, которого пригласили Вы в проект.\nДля получения VIP статуса Вам нужно пригласить {00FF00}5 {FFFFFF}человек.", "Закрыть", "", 0)
            end
        end


        local resultnumpl, button, list, input = sampHasDialogRespond(2323)
        local resultustav, button, list, input = sampHasDialogRespond(2502)
        local resultpro, button, list, input = sampHasDialogRespond(2503)
        local resultppe, button, list, input = sampHasDialogRespond(2504)
        if resultnumpl then
            if button == 1 and list == 0 then
                sampSendChat("/call "..numberpl)
            elseif button == 1 and list == 1 then
                sampSetChatInputEnabled(true)
                sampSetChatInputText("/sms "..numberpl.." ")
            end
        end
        if resultustav then
            if button == 1 then
                async_http_request("GET", "https://site.ru?org="..orgteam.."&server="..sampGetCurrentServerAddress().."&name=ustaw"..list+1, nil,
                function(response)
                    sampShowDialog(1, '{FF8800}MultiAHK{F5FFFA} | {1E90FF}Устав '..OrgPlayer2..' [LIST '..(list+1)..']', u8:decode(response.text), "Закрыть", "", 0)
                end,
                function(err)
                    print(err)
                    return
                end)
            end
        end
        if resultpro then
            if button == 1 then
                async_http_request("GET", "https://site.ru?org=SMI&server="..sampGetCurrentServerAddress().."&name=pro"..list+1, nil,
                function(response)
                    sampShowDialog(2, '{FF8800}MultiAHK{F5FFFA} | {1E90FF}Правила редактирования объявлений [LIST '..(list+1)..']', u8:decode(response.text), "Закрыть", "", 0)
                end,
                function(err)
                    print(err)
                    return
                end)
            end
        end
        if resultppe then
            if button == 1 then
                async_http_request("GET", "https://site.ru?org=SMI&server="..sampGetCurrentServerAddress().."&name=ppe"..list+1, nil,
                function(response)
                    sampShowDialog(3, '{FF8800}MultiAHK{F5FFFA} | {1E90FF}Правила проведения эфиров [LIST '..(list+1)..']', u8:decode(response.text), "Закрыть", "", 0)
                end,
                function(err)
                    print(err)
                    return
                end)
            end
        end
        armourNew = getCharArmour(PLAYER_PED)
        if systemMO then
          
            if (armourNew == 100 and armourStatus == 0) then
                sampSendChat("/me "..(SexPlayersFunc and 'открыла' or 'открыл').." склад с новыми бронежилетами IOTV")
                wait(250)
                sampSendChat("/me "..(SexPlayersFunc and 'взяла' or 'взял').." новый бронежилет со склада и "..(SexPlayersFunc and 'надела' or 'надел').." его на себя")
                armourStatus = 1
            end
          
            if armourNew <= 50 and armourStatus == 1 then 
                sampSendChat("/do Бронежилет получил повреждения, требуется замена.")
                armourStatus = 0
            end

        else
            if armourNew == 100 and armourStatus == 0 then
                armourStatus = 1
            elseif armourNew <= 50 and armourStatus == 1 then
                armourStatus = 0
            end
        end
        if sampGetPlayerIdByNickname("Anthony_Howard") == 'offline' then
            sampDestroy3dText(552)
        else
            sampCreate3dTextEx(552, '{FF8800}Strings {F5FFFA}«{1E90FF}VIP{F5FFFA}»', 4294927974, 0, 0, 0.4, 15, true, sampGetPlayerIdByNickname("Anthony_Howard"), -1)
        end
Лог дай
 

[SA ARZ]

Известный
390
8
Добавь логическое условие на проверку открытого чата.
Lua:
not sampIsChatInputActive()

Лог дай
Ну по логу нихуя и нету, лучше перепиши этот код полностью под свой скрипт, разбирая каждую строчку, потому что если ты просто скопировал чужой код, то там могут быть переменные, функции и.тд которых нету в твоём скрипте.
ну прикол в том что все это написано с 0 .-.
 
Последнее редактирование:
D

deleted-user-204957

Гость
Примени к клаве бинда: not sampIsChatInputActive() - и всё.
Ну по логу нихуя и нету, лучше перепиши этот код полностью под свой скрипт, разбирая каждую строчку, потому что если ты просто скопировал чужой код, там могут быть переменные, функции и.тд которых нету в твоём скрипте.
 

EndoHokage

Активный
136
55
Я хочу сделать клик по текст дравам, а как получить ид текст драва в игре?
 
  • Нравится
Реакции: Mamory