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

FixZer

Активный
126
36
Начальный биндер:
script_name('Binder for SAMP by FixZer v 5') -- название биндера
script_author('FixZer and Matteo') -- автор скрипта
script_description('Command') -- описание биндера

require "lib.moonloader" -- подключение библиотеки
require"lib.sampfuncs" -- подключение библиотеки
local Matrix3X3 = require "matrix3x3"
local Vector3D = require "vector3d"

local my_font = renderCreateFont("Arial", 12, 5)

--- Config
keyToggle = VK_MBUTTON
keyApply = VK_LBUTTON

local keys = require "vkeys"
local sampev = require "lib.samp.events"
local imgui = require "imgui"
local inicfg = require "inicfg"
local encoding = require "encoding"
encoding.default = 'CP1251'
u8 = encoding.UTF8

local rkeys = require "rkeys"
imgui.HotKey = require("imgui_addons").HotKey
imgui.ToggleButton = require("imgui_addons").ToggleButton
imgui.Spinner = require("imgui_addons").Spinner
imgui.BufferingBar = require("imgui_addons").BufferingBar

local sw, sh = getScreenResolution()
-- Для обновления
local dlstatus = require('moonloader').download_status

update_state = false

local FMB_vers = 5
local FMB_vers_text = '5.00'

local update_url = "https://raw.githubusercontent.com/FixZer/FMB-Helper/main/config/FMB%20Helper/update.ini" -- тут свою ссылку
local update_path = getWorkingDirectory() .. "/FMB Helper/update.ini"

local FMB_url = "https://github.com/FixZer/FMB-Helper/blob/main/FMB_Helper.luac?raw=true" -- тут тоже свою ссылку
local FMB_path = thisScript().path

--  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
-- ###//     Сохранение для биндера   //###
--  ##//\\//\\//\\//\\//\\//\\//\\//\\//##

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//        Binder        //###
--  ##//\\//\\//\\//\\//\\//\\//##

binderbuffer = {}

binderbuffer[1] = imgui.ImBuffer(4096)
binderbuffer[3] = imgui.ImBuffer(3)

local binder_settings = false
local binder_slot = 50

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//       FLY_HACK       //###
--  ##//\\//\\//\\//\\//\\//\\//##

local speed = 0.5

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//         WH CAR       //###
--  ##//\\//\\//\\//\\//\\//\\//##

local font = renderCreateFont('Arial',20,1)

local themes = import "FMB Helper/imgui_themes"
local ot_messenges = import "FMB Helper/ot_messenges"

local tag = '[{E60C0C}FMB Helper{FFFFFF}]: ' -- локальная переменная
local label = 1
local main_color = 0x5A90CE
local main_color_text = "{5A90CE}"
local white_color = "{FFFFFF}"

local style = imgui.ImBool(false)
local settings = imgui.ImBool(false)
local binder = imgui.ImBool(false)
local cheker = imgui.ImBool(false)
local Form = imgui.ImBool(false)

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//         Чекеры       //###
--  ##//\\//\\//\\//\\//\\//\\//##

local cheker_2 = imgui.ImBool(false)

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

local text_buffer = imgui.ImBuffer(256)
local text_buffer_2 = imgui.ImBuffer(256)
local report_buffer = imgui.ImBuffer(256)

local checked_radio = imgui.ImInt(1)

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//       Сохранение     //###
--  ##//\\//\\//\\//\\//\\//\\//##

local mainIni = inicfg.load({
    config = {
    ClickWarp = false, -- В эту таблицу ты можешь вписать переменные для конфига
    WlHack = false,
    Cheker = false,
    FLY_HACK = false,
    button_time = false,
    reportinfo = false,
    theme = 1,
    jail = false,
    kick = false,
}               
    
}, "FMB Helper/settings") -- название файла твоего ini конфига (пишешь без .ini)

local ClickWarp = imgui.ImBool(mainIni.config.ClickWarp) -- переменная для чекбокса
local WlHack = imgui.ImBool(mainIni.config.WlHack)
local Cheker = imgui.ImBool(mainIni.config.Cheker)
local FLY_HACK = imgui.ImBool(mainIni.config.FLY_HACK)
local button_time = imgui.ImBool(mainIni.config.button_time)
local reportinfo = imgui.ImBool(mainIni.config.reportinfo)
local theme = imgui.ImInt(mainIni.config.theme) -- Сохранение цвета imgui окна
local jail = imgui.ImBool(mainIni.config.jail)
local kick = imgui.ImBool(mainIni.config.kick)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    initializeRender()
    
    sampRegisterChatCommand("rec", reconnect)
    sampRegisterChatCommand("l", cmd_l)
    sampRegisterChatCommand("k", cmd_k)
    sampRegisterChatCommand("optimal", cmd_optimal)
    sampRegisterChatCommand("cool", cmd_cool)
    sampRegisterChatCommand("un", cmd_uninvite)
    sampRegisterChatCommand("fmb", cmd_imgui)

    _, tid = sampGetPlayerIdByCharHandle(PLAYER_RED)
    
    if not doesFileExist('moonloader/FMB Helper/settings.ini') then inicfg.save(mainIni, 'FMB Helper/settings.ini') end
    --Делаешь проверку: "Если нету файла конфига, то он создается автоматически". (вместо test.ini пишешь
    --название для своего конфига (с .ini в конце)

    imgui.Process = false

    imgui.SwitchContext()
    themes.SwitchColorTheme(mainIni.config.theme) -- Отвечает за цвет окна

    -- Для автообновления

    downloadUrlToFile(upadte_url,update_path,function(id, status)
        if status == dlstatus.STATUS_ENDDOOWNLOADDATA then
            updateIni = inicfg.load(nil, update_path)
            if tonumber(updateIni.info.vers) then
                sampAddChatMessage(tag .. " Есть новое обновление! Версия: " ..updateIni.info.vers, -1)
                update_state = true
            end
            os.remove(update_path)
        end
    end)

    if label == 1 then
        -- условие 1
        sampAddChatMessage(tag .. "Binder for SAMP by FixZer and Matteo v 5", 0xFFFFFF)
        sampAddChatMessage(tag .. "FMB Helper запущен и готов к работе!", 0xFFFFFF)
        sampAddChatMessage(tag .. "Скачав наш помошник, вы никогда не пожалеете об этом", 0xFFFFFF)
    else
        -- условие 2
        sampAddChatMessage(tag .. "There are problems with the FMB Helper binder", 0xE60C0C)
    end
        
    -- Блок выполняется один раз после старта сампа
    
    while true do
        wait(0)
        
        if button_time.v == true then
            check_time.v = true
        end

        if check_time.v == false and main_window_state.v == false then
            imgui.Process = false
        end
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
        -- ###//       Автообновление         //###
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##

        if update_state then
            downloadUrlToFile(FMB_url,FMB_path,function(id, status)
                if status == dlstatus.STATUS_ENDDOOWNLOADDATA then
                    sampAddChatMessage(tag .. "Скрипт успешно обновлён!", -1)
                    thisScript():reload()
                end
            end)
            break
        end

        --  ##//\\//\\//\\//\\//\\//\\//##
        -- ###//       Checker        //###
        --  ##//\\//\\//\\//\\//\\//\\//##


        if Cheker.v then
            for k,v in pairs(getAllChars()) do
                local myPos = {getCharCoordinates(playerPed)}
                local pPos = {getCharCoordinates(v)}
                local result, id = sampGetPlayerIdByCharHandle(v)
                if result then
                    local dist = getDistanceBetweenCoords3d(myPos[1], myPos[2], myPos[3], pPos[1], pPos[2], pPos[3])
                    renderFontDrawText(my_font, "Расстояние между {077ff7}"..sampGetPlayerNickname(id)..'['..id..']'..'{ffffff} равно: '..dist, 1075, 225 + k * 30, 0xFFFFFFFF)
                end
            end
        end

        --  ##//\\//\\//\\//\\//\\//\\//##
        -- ###//       FLY_HACK       //###
        --  ##//\\//\\//\\//\\//\\//\\//##

        if FLY_HACK.v then
            freezeCharPosition(PLAYER_PED, true)
            while FLY_HACK.v do wait(1)
                if isCharOnFoot(PLAYER_PED) then
                    local x, y, z = getCharCoordinates(PLAYER_PED)
                    local cx, cy, cz = getActiveCameraCoordinates()
                    local tx, ty, tz = getActiveCameraPointAt()
                    local angle = getHeadingFromVector2d(tx - cx, ty - cy)
                    setCharHeading(PLAYER_PED, angle)
                    local offset = {
                        x = 0,
                        y = 0,
                        z = -1.0,
                    }
                    if not sampIsChatInputActive() and not sampIsDialogActive() then
                        if isKeyDown(keys.VK_E) or isKeyDown(keys.VK_LSHIFT) then
                            offset.z = -1.2
                        end
                        if isKeyDown(keys.VK_Q) or isKeyDown(keys.VK_SPACE) then
                            offset.z = -0.8
                        end
                       if isKeyDown(keys.VK_W) then
                            offset.x = speed * math.sin(-math.rad(angle))
                            offset.y = speed * math.cos(-math.rad(angle))
                        end
                        if isKeyJustPressed(keys.VK_1) then
                            if speed < 0.2 then
                                speed = 0.1
                            end 
                            speed = speed - 0.1
                            printStringNow('Speed: ~r~'..speed, 300)
                        end
                        if isKeyJustPressed(keys.VK_2) then
                            speed = speed + 0.1
                            printStringNow('Speed: ~g~'..speed, 300)
                        end
                    end
                    --sendOnfootSync(x, y, z)
                    sendOnfootSync(x, y, z)
                    setCharCoordinates(PLAYER_PED, x + offset.x, y + offset.y, z + offset.z)
                end
            end
        else
               freezeCharPosition(PLAYER_PED, false)
        end

        --  ##//\\//\\//\\//\\//\\//\\//##
        -- ###//        WH CAR        //###
        --  ##//\\//\\//\\//\\//\\//\\//##

        if WlHack.v then
            for _, p_handle in pairs(getAllChars()) do
                if isCharOnScreen(p_handle) and p_handle ~= PLAYER_PED then
                    local res, id = sampGetPlayerIdByCharHandle(p_handle)
                    if res then
                        local x,y,z = getCharCoordinates(p_handle)
                        local x1,y2 = convert3DCoordsToScreen(x,y,z)
                        renderFontDrawText(font,string.format('ID %d',id),x1,y2,-1)
                    end
                end
            end
            for _, c_handle in pairs(getAllVehicles()) do
                if isCarOnScreen(c_handle) then
                    local res, id = sampGetVehicleIdByCarHandle(c_handle)
                    if res then
                        local x,y,z = getCarCoordinates(c_handle)
                        local x1,y2 = convert3DCoordsToScreen(x,y,z)
                        renderFontDrawText(font,string.format('{FFFFFF}CAR ID %d',id),x1,y2,-1)
                    end
                end
            end
        end

        --  ##//\\//\\//\\//\\//\\//\\//##
        -- ###//       Reconnect      //###
        --  ##//\\//\\//\\//\\//\\//\\//##

        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(10875)
                sampSetGamestate(1)
                res= false
            end
        end

        --  ##//\\//\\//\\//\\//\\//\\//##
        -- ###//       ClickWarp      //###
        --  ##//\\//\\//\\//\\//\\//\\//##

        if ClickWarp.v then
            while isPauseMenuActive() do
                if cursorEnabled then
                  showCursor(false)
                end
                wait(100)
              end

            if isKeyDown(keyToggle) then
                cursorEnabled = not cursorEnabled
                showCursor(cursorEnabled)
                while isKeyDown(keyToggle) do wait(80) end
              end
                    
              if cursorEnabled then
                local mode = sampGetCursorMode()
                if mode == 0 then
                  showCursor(true)
                end
                local sx, sy = getCursorPos()
                local sw, sh = getScreenResolution()
                -- is cursor in game window bounds?
                if sx >= 0 and sy >= 0 and sx < sw and sy < sh then
                  local posX, posY, posZ = convertScreenCoordsToWorld3D(sx, sy, 700.0)
                  local camX, camY, camZ = getActiveCameraCoordinates()
                  -- search for the collision point
                  local result, colpoint = processLineOfSight(camX, camY, camZ, posX, posY, posZ, true, true, false, true, false, false, false)
                  if result and colpoint.entity ~= 0 then
                    local normal = colpoint.normal
                    local pos = Vector3D(colpoint.pos[1], colpoint.pos[2], colpoint.pos[3]) - (Vector3D(normal[1], normal[2], normal[3]) * 0.1)
                    local zOffset = 300
                    if normal[3] >= 0.5 then zOffset = 1 end
                    -- search for the ground position vertically down
                    local result, colpoint2 = processLineOfSight(pos.x, pos.y, pos.z + zOffset, pos.x, pos.y, pos.z - 0.3,
                      true, true, false, true, false, false, false)
                    if result then
                      pos = Vector3D(colpoint2.pos[1], colpoint2.pos[2], colpoint2.pos[3] + 1)
          
                      local curX, curY, curZ  = getCharCoordinates(playerPed)
                      local dist              = getDistanceBetweenCoords3d(curX, curY, curZ, pos.x, pos.y, pos.z)
                      local hoffs             = renderGetFontDrawHeight(font)
          
                      sy = sy - 2
                      sx = sx - 2
                      renderFontDrawText(font, string.format("%0.2fm", dist), sx, sy - hoffs, 0xEEEEEEEE)
          
                      local tpIntoCar = nil
                      if colpoint.entityType == 2 then
                        local car = getVehiclePointerHandle(colpoint.entity)
                        if doesVehicleExist(car) and (not isCharInAnyCar(playerPed) or storeCarCharIsInNoSave(playerPed) ~= car) then
                          displayVehicleName(sx, sy - hoffs * 2, getNameOfVehicleModel(getCarModel(car)))
                          local color = 0xAAFFFFFF
                          if isKeyDown(VK_RBUTTON) then
                            tpIntoCar = car
                            color = 0xFFFFFFFF
                          end
                          renderFontDrawText(font2, "Удерживайте правую кнопку мыши, чтобы телепортироваться в машину", sx, sy - hoffs * 3, color)
                        end
                      end
          
                      createPointMarker(pos.x, pos.y, pos.z)
          
                      -- teleport!
                      if isKeyDown(keyApply) then
                        if tpIntoCar then
                          if not jumpIntoCar(tpIntoCar) then
                            -- teleport to the car if there is no free seats
                            teleportPlayer(pos.x, pos.y, pos.z)
                          end
                        else
                          if isCharInAnyCar(playerPed) then
                            local norm = Vector3D(colpoint.normal[1], colpoint.normal[2], 0)
                            local norm2 = Vector3D(colpoint2.normal[1], colpoint2.normal[2], colpoint2.normal[3])
                            rotateCarAroundUpAxis(storeCarCharIsInNoSave(playerPed), norm2)
                            pos = pos - norm * 1.8
                            pos.z = pos.z - 0.8
                          end
                          teleportPlayer(pos.x, pos.y, pos.z)
                        end
                        removePointMarker()
          
                        while isKeyDown(keyApply) do wait(0) end
                        showCursor(false)
                      end
                    end
                  end
                end
              end
              removePointMarker()
        end

        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//##
        -- ###//       Биндер при нажатии кнопок      //###
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//\\//\\//##

        if isKeyJustPressed(VK_F3) then
            sampSendChat("/d [ЛВПД] - [Всем]: Занимаю государственную волну.")
            wait(2000)
            sampSendChat("/gov Дорогие жители штата Детройт минуточку внимания!")
            wait(2000)
            sampSendChat("/gov Мы спешим сообщить, что сейчас пройдёт собеседование в ЛВПД.")
            wait(2000)
            sampSendChat("/gov Собеседование пройдёт в Холле Полиции Лас-Вентурас!")
            wait(2000)
            sampSendChat("/gov При себе иметь паспорт и лицензии.")
            wait(2000)
            sampSendChat("/gov Ждём всех в Холле Полиции Лас-Вентурас.")
            wait(2000)
            sampSendChat("/d [ЛВПД] - [Всем]: Освобождаю государственную волну.")
        end
        
        if isKeyDown(VK_MENU) and isKeyJustPressed(VK_9) then
            sampSendChat("Поздравляю вы нам подходите")
            wait(1500)
            sampSendChat("/do В кармане пиджака лежат ключи от раздевалке.")
            wait(1500)
            sampSendChat("/me резким движением достал из кармана ключи от раздевалки,")
            wait(1500)
            sampSendChat("/me передал ключи от шкафчика в раздевалке человеку на против")
            wait(1500)
            sampAddChatMessage("Напишите команду: /invite (id игрока)", main_color)
            wait(5000)
            sampSendChat("Удачного рабочего дня!")
        end
        -- Блок выполняется бесконечно (пока самп активен)
        
    end
end

--    ##//\\//\\//\\//\\//\\//\\//##
-- ###//       Для биндера    //###
--  ##//\\//\\//\\//\\//\\//\\//##
function getDownKeys()
    local curkeys = ""
    local bool = false
    for k, v in pairs(key) do
        if isKeyDown(v) and (v == VK_MENU or v == VK_CONTROL or v == VK_SHIFT or v == VK_LMENU or v == VK_RMENU or v == VK_RCONTROL or v == VK_LCONTROL or v == VK_LSHIFT or v == VK_RSHIFT) then
            if v ~= VK_MENU and v ~= VK_CONTROL and v ~= VK_SHIFT then
                curkeys = v
            end
        end
    end
    for k, v in pairs(key) do
        if isKeyDown(v) and (v ~= VK_MENU and v ~= VK_CONTROL and v ~= VK_SHIFT and v ~= VK_LMENU and v ~= VK_RMENU and v ~= VK_RCONTROL and v ~= VK_LCONTROL and v ~= VK_LSHIFT and v ~= VK_RSHIFT) then
            if tostring(curkeys):len() == 0 then
                curkeys = v
            else
                curkeys = curkeys .. " " .. v
            end
            bool = true
        end
    end
    return curkeys, bool
end

function getDownKeysText()
    tKeys = string.split(getDownKeys(), " ")
    if #tKeys ~= 0 then
        for i = 1, #tKeys do
            if i == 1 then
                str = key.id_to_name(tonumber(tKeys[i]))
            else
                str = str .. "+" .. key.id_to_name(tonumber(tKeys[i]))
            end
        end
        return str
    else
        return "None"
    end
end

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//    Для сохранения    //###
--  ##//\\//\\//\\//\\//\\//\\//##

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//       FLY_HACK       //###
--  ##//\\//\\//\\//\\//\\//\\//##

function sendOnfootSync(x, y, z)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(68)
    sampStorePlayerOnfootData(myId, data)
    setStructElement(data, 37, 1, 3, false)
    setStructFloatElement(data, 6, x, false)
    setStructFloatElement(data, 10, y, false)
    setStructFloatElement(data, 14, z, false)
    setStructElement(data, 62, 2, veh, false)
    sampSendOnfootData(data)
    freeMemory(data)
end

function onSendOnfootSync(data)
    local speed1 = data.moveSpeed
    if fly then
        speed.y = -0.00001
        speed.z = -0.00001
        data.position.z = -10
    else
        local X, Y, Z = getCharCoordinates(PLAYER_PED)
        while Z ~= data.position.z do
            data.position.z = data.position.z + 1
            X, Y, Z = getCharCoordinates(PLAYER_PED)
        end
    end
end

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//       Reconnect      //###
--  ##//\\//\\//\\//\\//\\//\\//##

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

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//       ClickWarp      //###
--  ##//\\//\\//\\//\\//\\//\\//##

function initializeRender()
  font = renderCreateFont("Tahoma", 10, FCR_BOLD + FCR_BORDER)
  font2 = renderCreateFont("Arial", 8, FCR_ITALICS + FCR_BORDER)
end


--- Functions
function rotateCarAroundUpAxis(car, vec)
  local mat = Matrix3X3(getVehicleRotationMatrix(car))
  local rotAxis = Vector3D(mat.up:get())
  vec:normalize()
  rotAxis:normalize()
  local theta = math.acos(rotAxis:dotProduct(vec))
  if theta ~= 0 then
    rotAxis:crossProduct(vec)
    rotAxis:normalize()
    rotAxis:zeroNearZero()
    mat = mat:rotate(rotAxis, -theta)
  end
  setVehicleRotationMatrix(car, mat:get())
end

function readFloatArray(ptr, idx)
  return representIntAsFloat(readMemory(ptr + idx * 4, 4, false))
end

function writeFloatArray(ptr, idx, value)
  writeMemory(ptr + idx * 4, 4, representFloatAsInt(value), false)
end

function getVehicleRotationMatrix(car)
  local entityPtr = getCarPointer(car)
  if entityPtr ~= 0 then
    local mat = readMemory(entityPtr + 0x14, 4, false)
    if mat ~= 0 then
      local rx, ry, rz, fx, fy, fz, ux, uy, uz
      rx = readFloatArray(mat, 0)
      ry = readFloatArray(mat, 1)
      rz = readFloatArray(mat, 2)

      fx = readFloatArray(mat, 4)
      fy = readFloatArray(mat, 5)
      fz = readFloatArray(mat, 6)

      ux = readFloatArray(mat, 8)
      uy = readFloatArray(mat, 9)
      uz = readFloatArray(mat, 10)
      return rx, ry, rz, fx, fy, fz, ux, uy, uz
    end
  end
end

function setVehicleRotationMatrix(car, rx, ry, rz, fx, fy, fz, ux, uy, uz)
  local entityPtr = getCarPointer(car)
  if entityPtr ~= 0 then
    local mat = readMemory(entityPtr + 0x14, 4, false)
    if mat ~= 0 then
      writeFloatArray(mat, 0, rx)
      writeFloatArray(mat, 1, ry)
      writeFloatArray(mat, 2, rz)

      writeFloatArray(mat, 4, fx)
      writeFloatArray(mat, 5, fy)
      writeFloatArray(mat, 6, fz)

      writeFloatArray(mat, 8, ux)
      writeFloatArray(mat, 9, uy)
      writeFloatArray(mat, 10, uz)
    end
  end
end

function displayVehicleName(x, y, gxt)
  x, y = convertWindowScreenCoordsToGameScreenCoords(x, y)
  useRenderCommands(true)
  setTextWrapx(640.0)
  setTextProportional(true)
  setTextJustify(false)
  setTextScale(0.33, 0.8)
  setTextDropshadow(0, 0, 0, 0, 0)
  setTextColour(255, 255, 255, 230)
  setTextEdge(1, 0, 0, 0, 100)
  setTextFont(1)
  displayText(x, y, gxt)
end

function createPointMarker(x, y, z)
  pointMarker = createUser3dMarker(x, y, z + 0.3, 4)
end

function removePointMarker()
  if pointMarker then
    removeUser3dMarker(pointMarker)
    pointMarker = nil
  end
end

function getCarFreeSeat(car)
  if doesCharExist(getDriverOfCar(car)) then
    local maxPassengers = getMaximumNumberOfPassengers(car)
    for i = 0, maxPassengers do
      if isCarPassengerSeatFree(car, i) then
        return i + 1
      end
    end
    return nil -- no free seats
  else
    return 0 -- driver seat
  end
end

function jumpIntoCar(car)
  local seat = getCarFreeSeat(car)
  if not seat then return false end                         -- no free seats
  if seat == 0 then warpCharIntoCar(playerPed, car)         -- driver seat
  else warpCharIntoCarAsPassenger(playerPed, car, seat - 1) -- passenger seat
  end
  restoreCameraJumpcut()
  return true
end

function teleportPlayer(x, y, z)
  if isCharInAnyCar(playerPed) then
    setCharCoordinates(playerPed, x, y, z)
  end
  setCharCoordinatesDontResetAnim(playerPed, x, y, z)
end

function setCharCoordinatesDontResetAnim(char, x, y, z)
  if doesCharExist(char) then
    local ptr = getCharPointer(char)
    setEntityCoordinates(ptr, x, y, z)
  end
end

function setEntityCoordinates(entityPtr, x, y, z)
  if entityPtr ~= 0 then
    local matrixPtr = readMemory(entityPtr + 0x14, 4, false)
    if matrixPtr ~= 0 then
      local posPtr = matrixPtr + 0x30
      writeMemory(posPtr + 0, 4, representFloatAsInt(x), false) -- X
      writeMemory(posPtr + 4, 4, representFloatAsInt(y), false) -- Y
      writeMemory(posPtr + 8, 4, representFloatAsInt(z), false) -- Z
    end
  end
end

function showCursor(toggle)
  if toggle then
    sampSetCursorMode(CMODE_LOCKCAM)
  else
    sampToggleCursor(false)
  end
  cursorEnabled = toggle
end

--  ##//\\//\\//\\//\\//\\//##
-- ###//      Команды     //###
--  ##//\\//\\//\\//\\//\\//##

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

function cmd_l(arg)
    sampSendChat("/lmenu")
end

function cmd_k(arg)
    if #arg == 0 then
        sampAddChatMessage("Введитие id игрока", main_color)
    else
        sampSendChat("/kick " .. arg .. " ДМ на МП")
    end
end

function cmd_uninvite(arg)
    if #arg == 0 then
        sampAddChatMessage("Чтобы уволить игрока введите id (игрок будет уволен по прчине: Профф непригоден.)", main_color)
    else
        sampSendChat("/uninvite " .. arg .. " Профф непригоден")
    end
end

function cmd_optimal(arg)
    if #arg == 0 then
        sampAddChatMessage("Привет, вы ввели команду, но не ввели аргумент :(", main_color)
    else
        sampAddChatMessage("Привет! Вы ввели команду и ввели аргумент: {FFFFFF}" .. arg, main_color)

    end
end

function cmd_cool(arg)
    var1, var2 = string.match(arg, "(.+) (.+)")
    if var1 == null or var1 == "" then
        sampAddChatMessage("Неплохо, у вас уже 2 аргумента, но вы их их не ввели :(", main_color)
    else
        sampAddChatMessage("Круто, вы ввели команду и 2 аргумента. 1ый: " .. white_color .. var1 .. ", " .. main_color_text .. "2ой: " .. white_color .. var2, main_color)
    end
end

--  ##//\\//\\//\\//\\//\\//\\//##
-- ###//         HotKey       //###
--  ##//\\//\\//\\//\\//\\//\\//##

--  ##//\\//\\//\\//\\//\\//##
-- ###//       Imgui      //###
--  ##//\\//\\//\\//\\//\\//##

function imgui.OnDrawFrame()
        
    if main_window_state.v then

        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(900, 600), imgui.Cond.FirstUseEver)
        
        imgui.Begin("FMB  Helper", main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoBringToFrontOnFocus + imgui.WindowFlags.NoScrollbar + imgui.WindowFlags.NoMove + imgui.WindowFlags.NoCollapse)
        imgui.InputText(u8"Вводить текст сюда", text_buffer)
        imgui.Text(text_buffer.v)
        imgui.BeginChild("ChildWindow1", imgui.ImVec2(103, 523), false)
        --  ##//\\//\\//\\//\\//\\//\\//##
        -- ###//    Кнопки в imgui    //###
        --  ##//\\//\\//\\//\\//\\//\\//##       
            if imgui.Button(u8"Стиль Хелпера", imgui.ImVec2(95,20)) then
                style.v = not style.v 
                settings.v = false
                binder.v = false
                cheker.v = false
                cheker_2.v = false
                Form.v = false
            end
    
            if imgui.Button(u8"    Основное", imgui.ImVec2(95,20), false) then
                settings.v = not settings.v
                style.v = false
                binder.v = false
                cheker.v = false
                cheker_2.v = false
                Form.v = false
            end
    
            if imgui.Button(u8"     Биндер", imgui.ImVec2(95,20)) then
                binder.v = not binder.v
                settings.v = false
                style.v = false
                cheker.v = false
                cheker_2.v = false
                Form.v = false
            end

            if imgui.Button(u8"     Чекеры", imgui.ImVec2(95,20)) then
                cheker.v = not cheker.v
                settings.v = false
                style.v = false
                binder.v = false
                cheker_2.v = false
                Form.v = false
            end

            if imgui.Button(u8"      Формы", imgui.ImVec2(95, 20)) then
                Form.v = not Form.v
                settings.v = false
                style.v = false
                binder.v = false
                cheker.v = false
                cheker_2.v = false
            end
        imgui.EndChild()
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//\\//##
        -- ###//    Функции кнопок при нажатии    //###
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//\\//##
        if style.v then
            imgui.SetCursorPos(imgui.ImVec2(105, 65))
            imgui.BeginChild("ChildWindow2", imgui.ImVec2(775, 525), true)
            for i, value in ipairs(themes.colorThemes) do
                if imgui.RadioButton(value, theme, i) then
                    themes.SwitchColorTheme(i)
                    mainIni.config.theme = theme.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end
            end
            imgui.EndChild()
        end
            
        if settings.v then
            imgui.SetCursorPos(imgui.ImVec2(105, 65))
            imgui.BeginChild("ChildWindow3", imgui.ImVec2(775, 525), true)
                if imgui.ToggleButton('ClickWarp', ClickWarp) then
                    mainIni.config.ClickWarp = ClickWarp.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end
    
                if imgui.ToggleButton('WlHack', WlHack)then
                    mainIni.config.WlHack = WlHack.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end
                
                if imgui.ToggleButton('FLY HACK', FLY_HACK) then
                    mainIni.config.FLY_HACK = FLY_HACK.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end

                if imgui.ToggleButton(u8'Счётчик', button_time) then
                    mainIni.config.button_time = button_time.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end

                if imgui.ToggleButton(u8'Уведомления о репорте', reportinfo) then
                    mainIni.config.reportinfo = reportinfo.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end

            imgui.EndChild()
        end
        
        if cheker.v then
            imgui.SetCursorPos(imgui.ImVec2(105, 65))
            imgui.BeginChild("ChildWindow4", imgui.ImVec2(775, 525), true)
                if imgui.Button(u8"                                                                                           Чекер игроков", imgui.ImVec2(765,20)) then
                    cheker_2.v = not cheker_2.v
                end
            imgui.EndChild()
        end

        if binder.v then
            imgui.SetCursorPos(imgui.ImVec2(105, 65))
            imgui.BeginChild("ChildWindow5", imgui.ImVec2(775, 525), true)
                imgui.BeginChild("Binder_Slots", imgui.ImVec2(100, -1),true)
                    for i = 1, binder_slot do
                        if imgui.Selectable(u8"Слот № " ..i) then
                            z = i
                            binder_settings = true
                            binderbuffer[1].v = ''
                            binderbuffer[3].v = ''
                        end
                    end
                imgui.EndChild()
                imgui.SameLine()
                imgui.BeginChild("binder_settings", imgui.ImVec2(-1,-1), true)
                    if binder_settings then
                        imgui.Text(u8"                                                        Вы редактируете слот под номером: " ..z)
                        imgui.Text(u8"Задержка:")
                        imgui.SameLine()
                        imgui.PushItemWidth(50)
                        imgui.InputText(u8'сек.', binderbuffer[3], imgui.InputTextFlags.CharsDecimal)
                        imgui.PopItemWidth()
                        imgui.SetCursorPos(imgui.ImVec2(3, 213))
                        imgui.InputTextMultiline(u8"##3", binderbuffer[1], imgui.ImVec2(765,300))
                    end
                imgui.EndChild()

            imgui.EndChild()
        end
        
        if Form.v then
            imgui.SetCursorPos(imgui.ImVec2(105, 65))
            imgui.BeginChild("ChildWindow6", imgui.ImVec2(775, 525), true)
                if imgui.ToggleButton(u8'Автоматическая форма принятие команды jail: ', jail) then
                    mainIni.config.jail = jail.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end

                if imgui.ToggleButton(u8'Автоматическая форма принятие команды kick: ', kick) then
                    mainIni.config.kick = kick.v
                    inicfg.save(mainIni, "FMB Helper/Settings.ini")
                end
            imgui.EndChild()
        end

        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
        -- ###//    Команды на выполнение     //###
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
        
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
        -- ###//             Чекер            //###
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##

        if cheker_2.v then
            imgui.SetCursorPos(imgui.ImVec2(110, 235))
            imgui.BeginChild("ChildWindow3", imgui.ImVec2(765, 350), false)
                if imgui.Checkbox(u8"Чекер игроков", Cheker) then
                    mainIni.config.Cheker = Cheker.v
                    inicfg.save(mainIni, 'FMB Helper/settings.ini')
                end
            imgui.EndChild()
        end

        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
        -- ###//             Биндер           //###
        --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##

        imgui.End()
    end

    --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##
    -- ###//            Счётчик           //###
    --  ##//\\//\\//\\//\\//\\//\\//\\//\\//##

    if check_time.v and button_time.v then
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(900, 600), imgui.Cond.FirstUseEver)
        
        imgui.Begin(u8"Счётчик", check_time, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoBringToFrontOnFocus + imgui.WindowFlags.NoScrollbar + imgui.WindowFlags.NoCollapse)
            imgui.Text(u8'Привет')
        imgui.End()
    end

end

--  ##//\\//\\//\\//\\//\\//##
-- ###//      Модули      //###
--  ##//\\//\\//\\//\\//\\//##


function sampev.onSendChat(text) -- OUTCOMING_PACKETS // Отправка пакета при отправке текста в чат
    
end

function sampev.onSendCommand(command) -- OUTCOMING_PACKETS // Отправка пакета при отправке команды в чат
    
end

function sampev.onSendPickedUoPickup(pickupId) -- OUTCOMING_PACKETS // Отправка пакета при взаимодействии с пикапом
    
end

function sampev.onSendExitVehicle(vehicleId) -- OUTCOMING_PACKETS // Отправка пакета при взаимодействии автомобилем (При высадке с авто)
    
end

function sampev.onSendEnterVehicle(vehicleId, passenger) -- OUTCOMING_PACKETS // Отправка пакета при взаимодействии автомобилем (При посадке с авто)
    
end

function sampev.onServerMessage(color, text) -- OUTCOMING_PACKETS // Получение пакет при появлении сообщения в чате от сервера

    if string.find(text, 'Внимание!', 1, true) then
        return false
    end

    if reportinfo.v then
        if string.find(text, '[Жалоба]', 1, true) then
            sampAddChatMessage(tag .. "Поступила новая жалоба от игрока, скорее ответь!", -1)
            sampAddChatMessage(tag .. "Чтобы ответить на жалобу напишите команду /ot !!", -1)
        end
    end

    --  ##//\\//\\//\\//\\//\\//\\//##
    -- ###//          Form        //###
    --  ##//\\//\\//\\//\\//\\//\\//##
    if jail.v then
        if text:find('%[A%] (%S+)%[(%d+)%]: /jail (%d+) (%d+) (.+)') then
            nickadmin, idadmin, idplayer, time, reason = text:match('%[A%] (%S+)%[(%d+)%]: /jail (%d+) (%d+) (.+)')
            sampSendChat('/a [Forma] +')
            sampSendChat('/jail ' ..idplayer.. ' ' ..time.. ' ' ..reason)
            return true
        end
    end

    if kick.v then
        if text:find('%[A%] (%S+)%[(%d+)%]: /kick (%d+) (.+)') then
            nickadmins, idadmins, idplayers, reasons = text:match('%[A%] (%S+)%[(%d+)%]: /kick (%d+) (.+)')
            sampSendChat('/a [Forma] +')
            sampSendChat('/kick ' ..idplayers.. ' ' ..reasons)
            return true
        end
    end
end

function sampev.onShowDialog(dialogId, style, title, button1, button2, text) -- OUTCOMING_PACKETS // Получение пакета при открытии самп диалогов

end

function sampev.onSetInterior(interior) -- OUTCOMING_PACKETS // Получение пакета при изменении интерьера
    
end

function sampev.onDisplayGameText(style, time, text) -- OUTCOMING_PACKETS // Получение пакета при появлении GameText'a

end

function sampev.onApplyPlayerAnimation(playerId, animLib, animName, loop, lockY, freeze, time) -- OUTCOMING_PACKETS // Получение пакета при изменении анимации педа

end

Почему после перезагрузки окно Счётчика не открыто, хотя после перезагрузки окно Счётчика должно быть открыто(по задумке)
 

Ba4a

Новичок
15
2
Приветствую, есть максимально простой код отсюда, который включает мигалки на g
Вопрос, как сделать так, чтобы в чате выводилось сообщение включении и выключении мигалок.
Типа я нажимаю кнопку, если они включились, вывести соответствующее сообщение в чатик
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        if testCheat('g') and isCharInAnyCar(PLAYER_PED) then
        switchCarSiren(storeCarCharIsInNoSave(PLAYER_PED), not isCarSirenOn(storeCarCharIsInNoSave(PLAYER_PED)))
        end
    end
end
 

Sanchez.

Известный
704
187
Приветствую, есть максимально простой код отсюда, который включает мигалки на g
Вопрос, как сделать так, чтобы в чате выводилось сообщение включении и выключении мигалок.
Типа я нажимаю кнопку, если они включились, вывести соответствующее сообщение в чатик
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        if testCheat('g') and isCharInAnyCar(PLAYER_PED) then
        switchCarSiren(storeCarCharIsInNoSave(PLAYER_PED), not isCarSirenOn(storeCarCharIsInNoSave(PLAYER_PED)))
        end
    end
end
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        if testCheat('g') and isCharInAnyCar(PLAYER_PED) then
        switchCarSiren(storeCarCharIsInNoSave(PLAYER_PED), not isCarSirenOn(storeCarCharIsInNoSave(PLAYER_PED)))
        sampAddChatMessage('Ты переключил мигалки',-1)
        end
    end
end
Lua:
function sampev.onServerMessage(color, text)
    lua_thread.create(function()
        wait(1)
        sampSendChat(text)
        return true
    end)
end

Почему у меня бесконечно спамит? Кикает за флуд функциями
 
Последнее редактирование:

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Lua:
function sampev.onShowDialog(dialogid, style, title, b1, b2, text)
    if rabota then
        if dialogid == 235 then
            for line in text:gmatch("[^\r\n]+") do
                if line:find("%{......%}Имя%: %{......%}%[(.+)%]") then
                    msg(line)
                end
            end
            return false
        end
    end
end
не находитПосмотреть вложение 109041
Задержку, что-ли, добавь, я не знаю..
Lua:
function sampev.onShowDialog(dialogid, style, title, b1, b2, text)
    if rabota then
        if dialogid == 235 then
            for line in text:gmatch("[^\r\n]+") do
                if line:find("%{......%}Имя%: %{......%}%[(.+)%]") then
                    lua_thread.create(function() wait(10)
                        msg(line)
                    end)
                end
            end
            return false
        end
    end
end


---
Не знаете, почему скрипт с JSON'a инфу не берёт?
Когда меняю шрифт, он сохраняется, но при перезапуске не загружается.
Lua:
local config =
{
    settings =
    {
        renderFont = "Tahoma",
        renderFontSize = 8,
        renderPosX = 40,
        renderPosY = 300,
        cursorEnable = {v = {VK_C}}
    }
}

local settings = {
    Font                    = imgui.ImBuffer(config.settings.renderFont, 256), -- Это
    FontSize                = imgui.ImInt(config.settings.renderFontSize), -- И это не загружает с JSON'a
    EnableRender            = imgui.ImBool(false),
    Render                  = imgui.ImInt(1),
}

local font = renderCreateFont(config.settings.renderFont, config.settings.renderFontSize, 5)

-- main
if not doesFileExist(path) then
    local f = io.open(path, 'w+')
    f:write(encodeJson(config)):close()
else
    local f = io.open(path, "r")
    a = f:read("*a")
    config = decodeJson(a)
    f:close()
end

-- OnDrawFrawe
if imgui.InputText(u8"Название шрифта", settings.Font) then
    --font = renderCreateFont(settings.Font.v, settings.FontSize.v, 5)
    config.settings.renderFont = settings.Font.v
    JSONSave()
    --rebuildFont()
end

-- save
function JSONSave()
    if doesFileExist(path) then
        local f = io.open(path, 'w+')
        if f then
            f:write(encodeJson(config)):close()
        end
    end
end
Актуально..
 
Последнее редактирование:
  • Bug
Реакции: Shepi

Morse

Потрачен
436
70
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Есть может у кого исходник админ чекера который пробивает через /admins, заносит в таблицу и выводит рендером?
 

Sanchez.

Известный
704
187
Есть может у кого исходник админ чекера который пробивает через /admins, заносит в таблицу и выводит рендером?
А что сложного самому написать? Сделать авто-написание /admins, написать return false, хукнуть регулярки, занести все в массив и вывести все через рендер. Все
 
  • Нравится
Реакции: Morse

СоМиК

Известный
457
311
Смотри, мне нужно, чтобы Посмотреть вложение 108953скрипт искал текст "Купить валюту ЕВРО" по этому диалоговому окну, и кликал по этому элементу диалог окна с помощью sampSendDialogResponse(). Потому что элементы этого диалог окна могут как увеличиваться, так и убавляться (Строка "Купить валюту ЕВРО" скачет с 8 по 12 строку, и скрипт должен сам определять какая это строка по названию элемента)
up
 

Sanchez.

Известный
704
187
Есть может у кого исходник админ чекера который пробивает через /admins, заносит в таблицу и выводит рендером?
Если что, вот исходник чекера лидеров. Можешь переделать его под чекер админов

Lua:
local leaderscheck = true
local font_flag = require('moonloader').font_flag
local font = renderCreateFont("Arial", 9, 11)

local leaders = {}

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

    lua_thread.create(leaderschecker)
    leaderschecker = false

    while true do
        wait(0)

        if leaderscheck then
            if leaders ~= {} then
                for k,v in pairs(leaders) do
                    renderFontDrawText(font, v.lead_name .. "[" .. v.lead_id .. "] - " .. v.lead_org, 960, 540 + k * 30 --[[измени это значение, чтобы поменять расстояние между лидерами]], 0xFFFFFFFF)
                end
            end
        end
    end
end

function leaderschecker()
    while true do
        wait(500)
        if sampGetGamestate() == 3 and not isGamePaused() then
            sampSendChat("/leaders")
        end
    end
end

function sampev.onServerMessage(color, text)
    if leaderscheck then
        if text:find("Лидеры онлайн:") then
            leaders = {}
            return false
        end
 
        if text:find("(.*)%[(%d+)%] %- (.*) %| Номер%: (%d+)") then
            lead_name, lead_id, lead_org, lead_number = text:match("(.*)%[(%d+)%] %- (.*) %| Номер%: (%d+)")
            table.insert(leaders,{
                lead_name = lead_name,
                lead_id = lead_id,
                lead_org = lead_org
            })
            return false
        end
        if text:find("Используйте /phone %- menu, чтобы найти членов организаций.") then
            return false
        end
    end
end

(код от @JustMini )




Ребята, как сделать так, чтобы если в массиве содержались одинаковые строки, то повторяющаяся строка удалялась?
 
Последнее редактирование:

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Ребята, как сделать так, чтобы если в массиве содержались одинаковые строки, то повторяющаяся строка удалялась?
Цикл в цикле, в обоих прогонять массив и во втором сравнивать значение из первого со вторым
 
  • Нравится
Реакции: Sanchez.

Sanchez.

Известный
704
187
Lua:
[ML] (error) GiveAway.lua: D:\GTA San Andreas\moonloader\GiveAway.lua:61: attempt to compare string with number
stack traceback:
    D:\GTA San Andreas\moonloader\GiveAway.lua:61: in function 'OnDrawFrame'
    D:\GTA San Andreas\moonloader\lib\imgui.lua:1378: in function <D:\GTA San Andreas\moonloader\lib\imgui.lua:1367>

Lua:
if #member > members.v then sampAddChatMessage('Достигнут лимит участников! Начинаю розыгрыш', -1) hook = true end

Почему вылазит эта ошибка? Я не сравниваю строку с числом, я добавил возле member #
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,777
11,225
Lua:
[ML] (error) GiveAway.lua: D:\GTA San Andreas\moonloader\GiveAway.lua:61: attempt to compare string with number
stack traceback:
    D:\GTA San Andreas\moonloader\GiveAway.lua:61: in function 'OnDrawFrame'
    D:\GTA San Andreas\moonloader\lib\imgui.lua:1378: in function <D:\GTA San Andreas\moonloader\lib\imgui.lua:1367>

Lua:
if #member > members.v then sampAddChatMessage('Достигнут лимит участников! Начинаю розыгрыш', -1) hook = true end

Почему вылазит эта ошибка? Я не сравниваю строку с числом, я добавил возле member #
#member возвращает число.
если member - массив, то # возвращает кол-во элементов в массиве
если member - строка, то # возвращает кол-во символов в строке
 
  • Нравится
Реакции: Sanchez.

Sanchez.

Известный
704
187
Lua:
local imgui = require 'imgui'
local encoding = require 'encoding'
local sampev = require 'lib.samp.events'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local window = imgui.ImBool(false)

local nickname, id, msg = nil,nil,nil

local sw, sh = getScreenResolution()

local members = imgui.ImBuffer(256)

--ocal members1 = 0

local prize = imgui.ImBuffer(256)

local mesta = imgui.ImBuffer(256)

local giveaway = false

local hook = false

local member = {}

function imgui.CenterButton(text)
    local width = imgui.GetWindowWidth()
    local calc = imgui.CalcTextSize(text)
    imgui.SetCursorPosX( width / 2 - calc.x / 2 )
    imgui.Button(text)
end

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

    sampRegisterChatCommand('giveaway', function()
        window.v = not window.v
    end)

    while true do
        wait(0)
        imgui.Process = window.v
    end
end

function imgui.OnDrawFrame()
    if window.v then
        imgui.SetNextWindowSize(imgui.ImVec2(250, 225), imgui.Cond.FirstUseEver)

        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin('GiveAway || BETA', window)
        --imgui.SameLine(60)
        if imgui.Button(giveaway and u8'Остановить розыгрыш' or u8'Запустить розыгрыш', imgui.ImVec2(-1, 35)) then
            if members.v == "" or mesta.v == "" or prize.v == "" then
                sampAddChatMessage('Недостаточно аргументов', -1)
            else
                giveaway = not giveaway
                proverka()
                hook = not hook
            end
        end
        --if #member > members.v then sampAddChatMessage('Достигнут лимит участников! Начинаю розыгрыш', -1) hook = true end
        --if members.v > #member then podchet = true en
        if #member > members.v then sampAddChatMessage('Достигнут лимит участников. Начинаю розыгрыш!', -1) hook = true end

        imgui.Separator()
        imgui.PushItemWidth(50)
        imgui.InputText(u8' || Кол-во участников', members)
        imgui.PopItemWidth()
        imgui.PushItemWidth(50)
        imgui.InputText(u8' || Сколько призовых мест', mesta)
        imgui.PopItemWidth()
        imgui.PushItemWidth(50)
        imgui.InputText(u8' || Приз на каждого', prize)
        imgui.PopItemWidth()
        imgui.Separator()
        --imgui.NewLine()
        --imgui.NewLine()
        --imgui.SameLine(63)
        imgui.BeginChild('##memberrss', imgui.ImVec2(-1, -1), true)
        imgui.Text(u8'Список участников:')
        imgui.SameLine()
        if imgui.Button(u8'Очистить', imgui.ImVec2(-1, 18)) then member = {} end
        for i=1, #member do
            imgui.Text(member[i])
        end
        --if members.v ~= "" and giveaway then
        --end
        imgui.NewLine()
        imgui.EndChild()
        imgui.End()
    end
end

function sampev.onServerMessage(color, text)
    if giveaway and hook then
        if text:find('{......}(%S+)%[(%d+)%] говорит:{B7AFAF}  %+') and #member ~= nickname then
            nickname, id, msg = text:match('{......}(%S+)%[(%d+)%] говорит:{B7AFAF}  %+')
            table.insert(member, string.format('%s[%d]', nickname, id))
            --members = members + 1
        end
    end
end
Помогите пожалуйста подправить код, в консоле вот такая ошибка [ML] (error) GiveAway.lua: D:\GTA San Andreas\moonloader\GiveAway.lua:67: attempt to compare string with number stack traceback: Кто может помогите прошу, я ебусь с этой хуетой пол дня. В пустой мозг ничего не приходит
 

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Помогите пожалуйста исправить код, в консоле вот такая ошибка [ML] (error) GiveAway.lua: D:\GTA San Andreas\moonloader\GiveAway.lua:67: attempt to compare string with number stack traceback: Кто может помогите прошу, я ебусь с этой хуетой пол дня
тебе же ответили уже
ты пытаешься сравнить число и строку, так делать нельзя
1628367278938.png
 
  • Нравится
Реакции: Sanchez.

kizn

О КУ)))
Всефорумный модератор
2,405
2,057
Lua:
local imgui = require 'imgui'
local encoding = require 'encoding'
local sampev = require 'lib.samp.events'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local window = imgui.ImBool(false)

local nickname, id, msg = nil,nil,nil

local sw, sh = getScreenResolution()

local members = imgui.ImBuffer(256)

--ocal members1 = 0

local prize = imgui.ImBuffer(256)

local mesta = imgui.ImBuffer(256)

local giveaway = false

local hook = false

local member = {}

function imgui.CenterButton(text)
    local width = imgui.GetWindowWidth()
    local calc = imgui.CalcTextSize(text)
    imgui.SetCursorPosX( width / 2 - calc.x / 2 )
    imgui.Button(text)
end

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

    sampRegisterChatCommand('giveaway', function()
        window.v = not window.v
    end)

    while true do
        wait(0)
        imgui.Process = window.v
    end
end

function imgui.OnDrawFrame()
    if window.v then
        imgui.SetNextWindowSize(imgui.ImVec2(250, 225), imgui.Cond.FirstUseEver)

        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin('GiveAway || BETA', window)
        --imgui.SameLine(60)
        if imgui.Button(giveaway and u8'Остановить розыгрыш' or u8'Запустить розыгрыш', imgui.ImVec2(-1, 35)) then
            if members.v == "" or mesta.v == "" or prize.v == "" then
                sampAddChatMessage('Недостаточно аргументов', -1)
            else
                giveaway = not giveaway
                proverka()
                hook = not hook
            end
        end
        --if #member > members.v then sampAddChatMessage('Достигнут лимит участников! Начинаю розыгрыш', -1) hook = true end
        --if members.v > #member then podchet = true en
        if #member > members.v then sampAddChatMessage('Достигнут лимит участников. Начинаю розыгрыш!', -1) hook = true end

        imgui.Separator()
        imgui.PushItemWidth(50)
        imgui.InputText(u8' || Кол-во участников', members)
        imgui.PopItemWidth()
        imgui.PushItemWidth(50)
        imgui.InputText(u8' || Сколько призовых мест', mesta)
        imgui.PopItemWidth()
        imgui.PushItemWidth(50)
        imgui.InputText(u8' || Приз на каждого', prize)
        imgui.PopItemWidth()
        imgui.Separator()
        --imgui.NewLine()
        --imgui.NewLine()
        --imgui.SameLine(63)
        imgui.BeginChild('##memberrss', imgui.ImVec2(-1, -1), true)
        imgui.Text(u8'Список участников:')
        imgui.SameLine()
        if imgui.Button(u8'Очистить', imgui.ImVec2(-1, 18)) then member = {} end
        for i=1, #member do
            imgui.Text(member[i])
        end
        --if members.v ~= "" and giveaway then
        --end
        imgui.NewLine()
        imgui.EndChild()
        imgui.End()
    end
end

function sampev.onServerMessage(color, text)
    if giveaway and hook then
        if text:find('{......}(%S+)%[(%d+)%] говорит:{B7AFAF}  %+') and #member ~= nickname then
            nickname, id, msg = text:match('{......}(%S+)%[(%d+)%] говорит:{B7AFAF}  %+')
            table.insert(member, string.format('%s[%d]', nickname, id))
            --members = members + 1
        end
    end
end
Помогите пожалуйста подправить код, в консоле вот такая ошибка [ML] (error) GiveAway.lua: D:\GTA San Andreas\moonloader\GiveAway.lua:67: attempt to compare string with number stack traceback: Кто может помогите прошу, я ебусь с этой хуетой пол дня. В пустой мозг ничего не приходит
#member > #members.v
 
  • Нравится
Реакции: Sanchez.