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

NetyEgo

Участник
164
10
help не работает автологин, просто окна авторизации нету, и вот например пишу в imgui пароль свой, после перезахода он пропадает, но в ini остаётся
LUA:
script_name('DiamondRPHelper') -- название скрипта
script_author('NetyEgo') -- автор скрипта
script_description('DRPHelper') -- описание скрипта

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

local inicfg = require 'inicfg'

local fa_font = nil
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })

function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig() -- to use 'imgui.ImFontConfig.new()' on error
        font_config.MergeMode = true

        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 13.0, font_config, fa_glyph_ranges)
    end
end

local main_color = 0xFFFFFF
local main_color_text = "{FFFFFF}"
local blue_color = "{3112FF}"
local yellow_color = "{EBFF12}"
local blue_color = "{1E00FF}"
local green_color = "{04FF00}"
local biruzov_color = "{00FF95}"
local red_color = "{FF1212}"

local mainIni = inicfg.load({
config =
{
autologin = false,
parol = "",
wh = false
}
}, "DRPHelper")

local status = inicfg.load(mainIni, 'DRPHelper')
if not doesFileExist('moonloader\\config\\DRPHelper.ini') then inicfg.save(mainIni, 'DRPHelper.ini') end

local main_window_state = imgui.ImBool(false)

local wallhack = imgui.ImBool(mainIni.config.wh)
local aafk = imgui.ImBool(false)
local autologin = imgui.ImBool(mainIni.config.autologin)
parol = imgui.ImBuffer(256)

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

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

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

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

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


        end
    end

    render_text(text)
end

function SetStyle()
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.ChildWindowRounding = 4.0
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Button]                 = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.ButtonHovered]          = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.06, 0.53, 0.98, 1.00)
    colors[clr.TitleBg]                = ImVec4(0.04, 0.04, 0.04, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.16, 0.29, 0.48, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)-- (0.1, 0.9, 0.1, 1.0)
    colors[clr.CloseButtonHovered]     = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]      = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.26, 0.59, 0.98, 0.35)
    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.FrameBg]                = ImVec4(0.16, 0.29, 0.48, 0.54)
    colors[clr.FrameBgHovered]         = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.FrameBgActive]          = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.MenuBarBg]              = ImVec4(0.14, 0.14, 0.14, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]          = ImVec4(0.31, 0.31, 0.31, 1.00)
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.CheckMark]              = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.Header]                 = ImVec4(0.26, 0.59, 0.98, 0.31)
    colors[clr.HeaderHovered]          = ImVec4(0.26, 0.59, 0.98, 0.80)
    colors[clr.HeaderActive]           = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.24, 0.52, 0.88, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.26, 0.59, 0.98, 1.00)
end
SetStyle()

local sw, sh = getScreenResolution()

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

    sampRegisterChatCommand("helper", cmd_helper)
    sampRegisterChatCommand("diid", cmd_iddialog)

    imgui.Process = false

    while true do
        wait(0)
        if main_window_state.v == false then
            imgui.Process = false
        end
        if wallhack.v then
            if  isKeyJustPressed(4) then
                wh = not wh
                if wh then
                    nameTagOn()
                else
                    nameTagOff()
                end
            end
            if isKeyDown(119) then
                if wh then
                    nameTagOff()
                    wait(1000)
                    nameTagOn()
                end
            end
        end
    end
end

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

function cmd_iddialog()
did = sampGetCurrentDialogId()
sampAddChatMessage(string.format("{04FF00}Dialog ID:{00FF95} %d", did), 0xFFFFFF)
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(900, 905), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    
    imgui.Begin(fa.ICON_FA_SPINNER .. " DRPHelper", main_window_state, imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize)
    
    imgui.BeginChild("##Button", imgui.ImVec2(150, 650), true, imgui.WindowFlags.NoScrollbar)
    
    if not selected then selected = 5 end
    if imgui.Button(fa.ICON_FA_SERVER .. u8" Функции.", imgui.ImVec2(135, 50)) then selected = 1 end
    if imgui.Button(fa.ICON_FA_COGS .. u8" Настройки.", imgui.ImVec2(135, 50)) then selected = 2 end
    if imgui.Button(fa.ICON_FA_BOOK .. u8" Список команд.", imgui.ImVec2(135, 50)) then selected = 3 end
    if imgui.Button(fa.ICON_FA_PLUS .. u8" Читы.", imgui.ImVec2(135, 50)) then selected = 4 end
    if imgui.Button(fa.ICON_FA_INFO .. u8" Информация.", imgui.ImVec2(135, 50)) then selected = 5 end
    imgui.EndChild()
    imgui.SameLine()
    imgui.BeginGroup()
    

    
if selected == 1 then
    imgui.BeginChild("##Function", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    if imgui.Checkbox(u8"Автоматический вод пароля.", autologin) then
        if autologin.v == true then
            mainIni.config.autologin = true
            inicfg.save(mainIni, "DRPHelper.ini")
        end
        if autologin.v == false then
            mainIni.config.autologin = false
            inicfg.save(mainIni, "DRPHelper.ini")
        end
    end   
    imgui.SameLine()
    imgui.TextQuestion(u8"Водить пароль в настройках.")   
    imgui.EndChild()
end
    
if selected == 2 then
    imgui.BeginChild("##Setting", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    if imgui.InputText(u8"", parol) then
        mainIni.config.parol = u8:decode(parol.v)
        inicfg.save(mainIni, "DRPHelper.ini")
    end   
    imgui.SameLine()
    imgui.TextQuestion(u8"Пароль который будет водиться в окно авторизации.(Только на Diamond RP)")
    imgui.EndChild()
end
    
if selected == 3 then
    imgui.BeginChild("##Spisok", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    imgui.Text(u8"/helper")
    imgui.SameLine()
    imgui.TextQuestion(u8"Активация.")
    imgui.Text(u8"/diid")
    imgui.SameLine()
    imgui.TextQuestion(u8"В чате пишет ID диалога.")
    imgui.EndChild()
end

if selected == 4 then
    imgui.BeginChild("##Cheats", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    if imgui.Checkbox(u8"Анти Афк.", aafk) then
        if aafk.v == true then
            writeMemory(7634870, 1, 1, 1)
            writeMemory(7635034, 1, 1, 1)
            memory.fill(7623723, 144, 8)
            memory.fill(5499528, 144, 6)
            sampAddChatMessage("{EBFF12}[{1E00FF}DRPHelper{EBFF12}] {FFFFFF}Анти Афк {04FF00}активирован.", 0xFFFFFF)
        end           
        if aafk.v == false then
            writeMemory(7634870, 1, 0, 0)
            writeMemory(7635034, 1, 0, 0)
            memory.hex2bin('5051FF1500838500', 7623723, 8)
            memory.hex2bin('0F847B010000', 5499528, 6)
            sampAddChatMessage("{EBFF12}[{1E00FF}DRPHelper{EBFF12}] {FFFFFF}Анти Афк {FF1212}деактивирован.", 0xFFFFFF)
        end   
    end
    imgui.SameLine()
    imgui.TextQuestion(u8"За его использование можете получить БАН.")
    if imgui.Checkbox(u8"ВХ.", wallhack) then
        if wallhack.v == true then
            mainIni.config.wh = true
            inicfg.save(mainIni, "DRPHelper.ini")
        end
        if wallhack.v == false then
            mainIni.config.wh = false
            inicfg.save(mainIni, "DRPHelper.ini")
        end   
    end
    imgui.SameLine()
    imgui.TextQuestion(u8"Активация на CKM(Колёсико мыши), за его использование можете получить БАН.")
    imgui.EndChild()
end
    
if selected == 5 then
    imgui.BeginChild("##Info", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    imgui.Text(u8"Автор скрипта: NetyEgo")
    imgui.SameLine()
    imgui.TextQuestion(u8"Пользователь на BlastHack.")
    imgui.Text(u8"В скрипте отсуствует автообновление.")
    imgui.SameLine()
    imgui.TextQuestion(u8"Придётся иногда заглядывать на BlastHack.")
    imgui.Text(u8"Скрипт предназначен для Diamond RolePlay.")
    imgui.SameLine()
    imgui.TextQuestion(u8"На других проектах будет работать, но он предназначен для Diamond.")
    imgui.EndChild()
end
    imgui.EndGroup()
    imgui.End()
end

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

function nameTagOn()
    local pStSet = sampGetServerSettingsPtr()
    NTdist = memory.getfloat(pStSet + 39) -- дальность
    NTwalls = memory.getint8(pStSet + 47) -- видимость через стены
    NTshow = memory.getint8(pStSet + 56) -- видимость тегов
    memory.setfloat(pStSet + 39, 1488.0)
    memory.setint8(pStSet + 47, 0)
    memory.setint8(pStSet + 56, 1)
end

function nameTagOff()
    local pStSet = sampGetServerSettingsPtr()
    memory.setfloat(pStSet + 39, NTdist)
    memory.setint8(pStSet + 47, NTwalls)
    memory.setint8(pStSet + 56, NTshow)
end

function onExitScript()
    if NTdist then
        nameTagOff()
    end
end

function imgui.TextQuestion(text)
    imgui.TextDisabled('(?)')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted(text)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
end
 

NetyEgo

Участник
164
10
help не работает автологин, просто окна авторизации нету, и вот например пишу в imgui пароль свой, после перезахода он пропадает, но в ini остаётся
LUA:
script_name('DiamondRPHelper') -- название скрипта
script_author('NetyEgo') -- автор скрипта
script_description('DRPHelper') -- описание скрипта

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

local inicfg = require 'inicfg'

local fa_font = nil
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })

function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig() -- to use 'imgui.ImFontConfig.new()' on error
        font_config.MergeMode = true

        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 13.0, font_config, fa_glyph_ranges)
    end
end

local main_color = 0xFFFFFF
local main_color_text = "{FFFFFF}"
local blue_color = "{3112FF}"
local yellow_color = "{EBFF12}"
local blue_color = "{1E00FF}"
local green_color = "{04FF00}"
local biruzov_color = "{00FF95}"
local red_color = "{FF1212}"

local mainIni = inicfg.load({
config =
{
autologin = false,
parol = "",
wh = false
}
}, "DRPHelper")

local status = inicfg.load(mainIni, 'DRPHelper')
if not doesFileExist('moonloader\\config\\DRPHelper.ini') then inicfg.save(mainIni, 'DRPHelper.ini') end

local main_window_state = imgui.ImBool(false)

local wallhack = imgui.ImBool(mainIni.config.wh)
local aafk = imgui.ImBool(false)
local autologin = imgui.ImBool(mainIni.config.autologin)
parol = imgui.ImBuffer(256)

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

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

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

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

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


        end
    end

    render_text(text)
end

function SetStyle()
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.ChildWindowRounding = 4.0
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Button]                 = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.ButtonHovered]          = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.06, 0.53, 0.98, 1.00)
    colors[clr.TitleBg]                = ImVec4(0.04, 0.04, 0.04, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.16, 0.29, 0.48, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)-- (0.1, 0.9, 0.1, 1.0)
    colors[clr.CloseButtonHovered]     = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]      = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.26, 0.59, 0.98, 0.35)
    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.FrameBg]                = ImVec4(0.16, 0.29, 0.48, 0.54)
    colors[clr.FrameBgHovered]         = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.FrameBgActive]          = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.MenuBarBg]              = ImVec4(0.14, 0.14, 0.14, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]          = ImVec4(0.31, 0.31, 0.31, 1.00)
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.CheckMark]              = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.Header]                 = ImVec4(0.26, 0.59, 0.98, 0.31)
    colors[clr.HeaderHovered]          = ImVec4(0.26, 0.59, 0.98, 0.80)
    colors[clr.HeaderActive]           = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.24, 0.52, 0.88, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.26, 0.59, 0.98, 1.00)
end
SetStyle()

local sw, sh = getScreenResolution()

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

    sampRegisterChatCommand("helper", cmd_helper)
    sampRegisterChatCommand("diid", cmd_iddialog)

    imgui.Process = false

    while true do
        wait(0)
        if main_window_state.v == false then
            imgui.Process = false
        end
        if wallhack.v then
            if  isKeyJustPressed(4) then
                wh = not wh
                if wh then
                    nameTagOn()
                else
                    nameTagOff()
                end
            end
            if isKeyDown(119) then
                if wh then
                    nameTagOff()
                    wait(1000)
                    nameTagOn()
                end
            end
        end
    end
end

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

function cmd_iddialog()
did = sampGetCurrentDialogId()
sampAddChatMessage(string.format("{04FF00}Dialog ID:{00FF95} %d", did), 0xFFFFFF)
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(900, 905), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   
    imgui.Begin(fa.ICON_FA_SPINNER .. " DRPHelper", main_window_state, imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize)
   
    imgui.BeginChild("##Button", imgui.ImVec2(150, 650), true, imgui.WindowFlags.NoScrollbar)
   
    if not selected then selected = 5 end
    if imgui.Button(fa.ICON_FA_SERVER .. u8" Функции.", imgui.ImVec2(135, 50)) then selected = 1 end
    if imgui.Button(fa.ICON_FA_COGS .. u8" Настройки.", imgui.ImVec2(135, 50)) then selected = 2 end
    if imgui.Button(fa.ICON_FA_BOOK .. u8" Список команд.", imgui.ImVec2(135, 50)) then selected = 3 end
    if imgui.Button(fa.ICON_FA_PLUS .. u8" Читы.", imgui.ImVec2(135, 50)) then selected = 4 end
    if imgui.Button(fa.ICON_FA_INFO .. u8" Информация.", imgui.ImVec2(135, 50)) then selected = 5 end
    imgui.EndChild()
    imgui.SameLine()
    imgui.BeginGroup()
   

   
if selected == 1 then
    imgui.BeginChild("##Function", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    if imgui.Checkbox(u8"Автоматический вод пароля.", autologin) then
        if autologin.v == true then
            mainIni.config.autologin = true
            inicfg.save(mainIni, "DRPHelper.ini")
        end
        if autologin.v == false then
            mainIni.config.autologin = false
            inicfg.save(mainIni, "DRPHelper.ini")
        end
    end  
    imgui.SameLine()
    imgui.TextQuestion(u8"Водить пароль в настройках.")  
    imgui.EndChild()
end
   
if selected == 2 then
    imgui.BeginChild("##Setting", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    if imgui.InputText(u8"", parol) then
        mainIni.config.parol = u8:decode(parol.v)
        inicfg.save(mainIni, "DRPHelper.ini")
    end  
    imgui.SameLine()
    imgui.TextQuestion(u8"Пароль который будет водиться в окно авторизации.(Только на Diamond RP)")
    imgui.EndChild()
end
   
if selected == 3 then
    imgui.BeginChild("##Spisok", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    imgui.Text(u8"/helper")
    imgui.SameLine()
    imgui.TextQuestion(u8"Активация.")
    imgui.Text(u8"/diid")
    imgui.SameLine()
    imgui.TextQuestion(u8"В чате пишет ID диалога.")
    imgui.EndChild()
end

if selected == 4 then
    imgui.BeginChild("##Cheats", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    if imgui.Checkbox(u8"Анти Афк.", aafk) then
        if aafk.v == true then
            writeMemory(7634870, 1, 1, 1)
            writeMemory(7635034, 1, 1, 1)
            memory.fill(7623723, 144, 8)
            memory.fill(5499528, 144, 6)
            sampAddChatMessage("{EBFF12}[{1E00FF}DRPHelper{EBFF12}] {FFFFFF}Анти Афк {04FF00}активирован.", 0xFFFFFF)
        end          
        if aafk.v == false then
            writeMemory(7634870, 1, 0, 0)
            writeMemory(7635034, 1, 0, 0)
            memory.hex2bin('5051FF1500838500', 7623723, 8)
            memory.hex2bin('0F847B010000', 5499528, 6)
            sampAddChatMessage("{EBFF12}[{1E00FF}DRPHelper{EBFF12}] {FFFFFF}Анти Афк {FF1212}деактивирован.", 0xFFFFFF)
        end  
    end
    imgui.SameLine()
    imgui.TextQuestion(u8"За его использование можете получить БАН.")
    if imgui.Checkbox(u8"ВХ.", wallhack) then
        if wallhack.v == true then
            mainIni.config.wh = true
            inicfg.save(mainIni, "DRPHelper.ini")
        end
        if wallhack.v == false then
            mainIni.config.wh = false
            inicfg.save(mainIni, "DRPHelper.ini")
        end  
    end
    imgui.SameLine()
    imgui.TextQuestion(u8"Активация на CKM(Колёсико мыши), за его использование можете получить БАН.")
    imgui.EndChild()
end
   
if selected == 5 then
    imgui.BeginChild("##Info", imgui.ImVec2(400, 650), true, imgui.WindowFlags.NoScrollbar)
    imgui.Text(u8"Автор скрипта: NetyEgo")
    imgui.SameLine()
    imgui.TextQuestion(u8"Пользователь на BlastHack.")
    imgui.Text(u8"В скрипте отсуствует автообновление.")
    imgui.SameLine()
    imgui.TextQuestion(u8"Придётся иногда заглядывать на BlastHack.")
    imgui.Text(u8"Скрипт предназначен для Diamond RolePlay.")
    imgui.SameLine()
    imgui.TextQuestion(u8"На других проектах будет работать, но он предназначен для Diamond.")
    imgui.EndChild()
end
    imgui.EndGroup()
    imgui.End()
end

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

function nameTagOn()
    local pStSet = sampGetServerSettingsPtr()
    NTdist = memory.getfloat(pStSet + 39) -- дальность
    NTwalls = memory.getint8(pStSet + 47) -- видимость через стены
    NTshow = memory.getint8(pStSet + 56) -- видимость тегов
    memory.setfloat(pStSet + 39, 1488.0)
    memory.setint8(pStSet + 47, 0)
    memory.setint8(pStSet + 56, 1)
end

function nameTagOff()
    local pStSet = sampGetServerSettingsPtr()
    memory.setfloat(pStSet + 39, NTdist)
    memory.setint8(pStSet + 47, NTwalls)
    memory.setint8(pStSet + 56, NTshow)
end

function onExitScript()
    if NTdist then
        nameTagOff()
    end
end

function imgui.TextQuestion(text)
    imgui.TextDisabled('(?)')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted(text)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
end
на других серверах работает, но на даймонде нет
 

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Хочу сделать авто-забив, но не знаю как сделать функцию тип /avtozabiv [кому забивать] [время] пример: /avtozabiv Ацтек 16:00 и в пейдее писало /bc Ацтек забиваю вам капт в 16:00.
(Функцию с пей деем сделал, не знаю как эту /avtozabiv [кому забивать] [время] функцию сделать)
Lua:
--main
sampRegisterChatCommand("avtozabiv", function(arg)
    local band, time = string.match(arg, "(.+) (%d+:%d+)")
    if band == nil or time == "" then
        sampAddChatMessage("Вы забыли указать 1 аргумент.", -1)
    else
        sampSendChat(band..", забиваю вам капт в "..time)
    end
end)
Время нужно указать в формате 00:00, т.е с двоеточиями. Ну это так, если тебе нужно. Если не нужно, то замени (%d+:%d+) на (%d+%s%d+) и формат будет таким "00 00", т.е с пробелом
 
  • Нравится
Реакции: Temate

Temate

Участник
46
4
Lua:
--main
sampRegisterChatCommand("avtozabiv", function(arg)
    local band, time = string.match(arg, "(.+) (%d+:%d+)")
    if band == nil or time == "" then
        sampAddChatMessage("Вы забыли указать 1 аргумент.", -1)
    else
        sampSendChat(band..", забиваю вам капт в "..time)
    end
end)
Время нужно указать в формате 00:00, т.е с двоеточиями. Ну это так, если тебе нужно. Если не нужно, то замени (%d+:%d+) на (%d+%s%d+) и формат будет таким "00 00", т.е с пробелом
Как обратиться к функции, например, написал команду, будет использоваться функция и band.., ..time будет использоваться из main
 

Anton Nixon

Активный
474
48
чем может быть причина, что скрипт записывает данные в ini, по после рестарта скрипта либо релога игры данные пропадают из файла
 

|DEVIL|

Известный
359
273
чем может быть причина, что скрипт записывает данные в ini, по после рестарта скрипта либо релога игры данные пропадают из файла
чем может быть причина, что скрипт записывает данные в ini, по после рестарта скрипта либо релога игры данные пропадают из файла
inicfg.save юзаешь? И ещё скинь что написал в скрипте, ото я помню что у меня была очень давно такая проблема из-за неправильного кода вроде-бы
 

Fott

Простреленный
3,434
2,279
Подскажет кто как юзать эти функции?
onSendGiveDamage', 'onSendTakeDamage