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

blessave

Известный
362
109
Крашит скрипт с причиной:


Код скрипта:
Script:
script_name("AutoPiar")
script_author("ARMOR")
script_version("1.0 release")

require "lib.moonloader"
local imgui = require "imgui"
local inicfg = require "inicfg"
local encoding = require 'encoding'
local ev = require 'lib.samp.events'

encoding.default = 'CP1251'
u8 = encoding.UTF8

local cfg = inicfg.load({
    config = {
        vr = "",
        fam = "",
        j = "",
        s = "",
        ad = "",
    },
    interface = {
        vr_checkbox = false,
        fam_checkbox = false,
        j_checkbox = false,
        s_checkbox = false,
        ad_checkbox = false,
        vr_slider = 1,
        fam_slider = 1,
        j_slider = 1,
        s_slider = 1,
        ad_slider = 1,
        ad_radiobutton = 1,
        theme_id = 0,
    }
}, "AutoPiar.ini")

stat = { ['act'] = false}

-- imgui window
local main_window_state = imgui.ImBool(false)

-- imgui checkbox
local vr_check = imgui.ImBool(cfg.interface.vr_checkbox)
local fam_check = imgui.ImBool(cfg.interface.fam_checkbox)
local j_check = imgui.ImBool(cfg.interface.j_checkbox)
local s_check = imgui.ImBool(cfg.interface.s_checkbox)
local ad_check = imgui.ImBool(cfg.interface.ad_checkbox)

-- imgui buffer
local vr = imgui.ImBuffer(256)
local fam = imgui.ImBuffer(256)
local j = imgui.ImBuffer(256)
local s = imgui.ImBuffer(256)
local ad = imgui.ImBuffer(256)

-- imgui slider
local vr_slider = imgui.ImInt(cfg.interface.vr_slider)
local fam_slider = imgui.ImInt(cfg.interface.fam_slider)
local j_slider = imgui.ImInt(cfg.interface.j_slider)
local s_slider = imgui.ImInt(cfg.interface.s_slider)
local ad_slider = imgui.ImInt(cfg.interface.ad_slider)

-- imgui radiobutton
local ad_radiobutton = imgui.ImInt(cfg.interface.ad_radiobutton)

-- imgui combo
local themes_combo = imgui.ImInt(0)

-- other
local delay = 0.5

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
   
    if not doesFileExist(getWorkingDirectory()..'\\config\\AutoPiar.ini') then inicfg.save(cfg, 'AutoPiar.ini') end

    sampAddChatMessage("[AutoPiar]: {FFFFFF}Скрипт загружен, для настройки введите /ap", 0x5CBCFF)

    sampRegisterChatCommand("ap", cmd_imgui)

    while true do
        wait(0)
        vr.v = cfg.config.vr
        fam.v = cfg.config.fam
        j.v = cfg.config.j
        s.v = cfg.config.s
        ad.v = cfg.config.ad
        themes_combo.v = cfg.interface.theme_id
        styles = cfg.interface.theme_id
        if main_window_state.v == true then
            lockPlayerControl(true)
        else
            lockPlayerControl(false)
        end
        if stat['act'] == true and vr_check.v == false and fam_check.v == false and j_check.v == false and ad_check.v == false and s_check.v == false then
            sampAddChatMessage("[AutoPiar]: {FFFFFF}Произошла ошибка, были сняты все CheckBox'ы ", 0x5CBCFF)
            stat['act'] = false
        end
    end
end

function piar_fam()
    while stat['act'] do
        if fam_check.v == true then
            sampSendChat("/fam " .. u8:decode(cfg.config.fam))
        end
        wait(fam_slider.v*60000)
    end
end

function piar_j()
    wait(500)
    while stat['act'] do
        if j_check.v == true then
            sampSendChat("/j " .. u8:decode(cfg.config.j))
        end
        wait(j_slider.v*60000)
    end
end

function piar_s()
    wait(1000)
    while stat['act'] do
        if s_check.v == true then
            sampSendChat("/s " .. u8:decode(cfg.config.s))
        end
        wait(s_slider.v*60000)
    end
end

function piar_ad()
    wait(1500)
    while stat['act'] do
        if ad_check.v == true and cfg.interface.ad_radiobutton == 1 then
            sampSendChat("/ad " .. u8:decode(cfg.config.ad))
            wait(300)
            sampSendDialogResponse(15346, 1, 1, nil)
            sampCloseCurrentDialogWithButton(1)
            wait(500)
            sampCloseCurrentDialogWithButton(1)
        elseif ad_check.v == true and cfg.interface.ad_radiobutton == 2 then
            sampSendChat("/ad " .. u8:decode(cfg.config.ad))
            wait(300)
            sampSendDialogResponse(15346, 1, 2, nil)
            sampCloseCurrentDialogWithButton(1)
            wait(500)
            sampCloseCurrentDialogWithButton(1)
        end
        wait(ad_slider.v*60000)
    end
end

function piar_vr()
    wait(2300)
    while stat['act'] do
        if vr_check.v then
            sampSendChat("/vr " .. vr.v)
        end
        if finished then
            wait(vr_slider.v*60000)
            sampAddChatMessage("Если ты видишь это сообщение, значит отчет работает", -1)
        end
    end
end

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

function imgui.OnDrawFrame()
    local style = imgui.GetStyle()
    local clrs = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    style.Alpha = 1
    style.ChildWindowRounding = 0
    style.WindowRounding = 0
    style.GrabRounding = 0
    style.GrabMinSize = 12
    style.FrameRounding = 5
    if styles == 0 then
        clrs[clr.Text] = ImVec4(1, 1, 1, 1)
        clrs[clr.TextDisabled] = ImVec4(0.60000002384186, 0.60000002384186, 0.60000002384186, 1)
        clrs[clr.WindowBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ChildWindowBg] = ImVec4(9.9998999303352e-07, 9.9999613212276e-07, 9.9999999747524e-07, 0)
        clrs[clr.PopupBg] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.Border] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.BorderShadow] = ImVec4(9.9999999747524e-07, 9.9998999303352e-07, 9.9998999303352e-07, 0)
        clrs[clr.FrameBg] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.FrameBgHovered] = ImVec4(0.062745101749897, 0.37254902720451, 0.74509805440903, 1)
        clrs[clr.FrameBgActive] = ImVec4(0.10196078568697, 0.41176471114159, 0.7843137383461, 1)
        clrs[clr.TitleBg] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.TitleBgActive] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.TitleBgCollapsed] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.MenuBarBg] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.ScrollbarBg] = ImVec4(0.14883691072464, 0.14883720874786, 0.14883571863174, 1)
        clrs[clr.ScrollbarGrab] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.ScrollbarGrabHovered] = ImVec4(0.062745101749897, 0.37254902720451, 0.74509805440903, 1)
        clrs[clr.ScrollbarGrabActive] = ImVec4(0.10196078568697, 0.41176471114159, 0.7843137383461, 1)
        clrs[clr.ComboBg] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.CheckMark] = ImVec4(1, 1, 1, 1)
        clrs[clr.SliderGrab] = ImVec4(0.1803921610117, 0.1803921610117, 0.1803921610117, 1)
        clrs[clr.SliderGrabActive] = ImVec4(0.258823543787, 0.258823543787, 0.258823543787, 1)
        clrs[clr.Button] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.ButtonHovered] = ImVec4(0.062745101749897, 0.37254902720451, 0.74509805440903, 1)
        clrs[clr.ButtonActive] = ImVec4(0.10196078568697, 0.41176471114159, 0.7843137383461, 1)
        clrs[clr.Header] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.HeaderHovered] = ImVec4(0.062745101749897, 0.37254902720451, 0.74509805440903, 1)
        clrs[clr.HeaderActive] = ImVec4(0.10196078568697, 0.41176471114159, 0.7843137383461, 1)
        clrs[clr.Separator] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.SeparatorHovered] = ImVec4(0.062745101749897, 0.37254902720451, 0.74509805440903, 1)
        clrs[clr.SeparatorActive] = ImVec4(0.10196078568697, 0.41176471114159, 0.7843137383461, 1)
        clrs[clr.ResizeGrip] = ImVec4(0.14117647707462, 0.45098039507866, 0.82352942228317, 1)
        clrs[clr.ResizeGripHovered] = ImVec4(0.062745101749897, 0.37254902720451, 0.74509805440903, 1)
        clrs[clr.ResizeGripActive] = ImVec4(0.10196078568697, 0.41176471114159, 0.7843137383461, 1)
        clrs[clr.CloseButton] = ImVec4(0.19607843458652, 0.19607843458652, 0.19607843458652, 0.88235294818878)
        clrs[clr.CloseButtonHovered] = ImVec4(0.19607843458652, 0.19607843458652, 0.19607843458652, 1)
        clrs[clr.CloseButtonActive] = ImVec4(0.19607843458652, 0.19607843458652, 0.19607843458652, 0.60784316062927)
        clrs[clr.PlotLines] = ImVec4(1, 0.99998998641968, 0.99998998641968, 1)
        clrs[clr.PlotLinesHovered] = ImVec4(1, 0.99999779462814, 0.99998998641968, 1)
        clrs[clr.PlotHistogram] = ImVec4(1, 0.99999779462814, 0.99998998641968, 1)
        clrs[clr.PlotHistogramHovered] = ImVec4(1, 0.9999960064888, 0.99998998641968, 1)
        clrs[clr.TextSelectedBg] = ImVec4(9.9998999303352e-07, 9.9998999303352e-07, 9.9999999747524e-07, 0.34999999403954)
        clrs[clr.ModalWindowDarkening] = ImVec4(0.20000000298023, 0.20000000298023, 0.20000000298023, 0.34999999403954)
    elseif styles == 1 then
        clrs[clr.Text] = ImVec4(1, 0.99998998641968, 0.99998998641968, 1)
        clrs[clr.TextDisabled] = ImVec4(0.60000002384186, 0.60000002384186, 0.60000002384186, 1)
        clrs[clr.WindowBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ChildWindowBg] = ImVec4(0, 0, 0, 0)
        clrs[clr.PopupBg] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.Border] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.BorderShadow] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.FrameBg] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.70588237047195)
        clrs[clr.FrameBgHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.58823531866074)
        clrs[clr.FrameBgActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.39215686917305)
        clrs[clr.TitleBg] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.82352942228317)
        clrs[clr.TitleBgActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.TitleBgCollapsed] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.66666668653488)
        clrs[clr.MenuBarBg] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.ScrollbarBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ScrollbarGrab] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.ScrollbarGrabHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.7843137383461)
        clrs[clr.ScrollbarGrabActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.58823531866074)
        clrs[clr.ComboBg] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.7843137383461)
        clrs[clr.CheckMark] = ImVec4(1, 1, 1, 1)
        clrs[clr.SliderGrab] = ImVec4(0.1803921610117, 0.1803921610117, 0.1803921610117, 1)
        clrs[clr.SliderGrabActive] = ImVec4(0.258823543787, 0.258823543787, 0.258823543787, 1)
        clrs[clr.Button] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.ButtonHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.7843137383461)
        clrs[clr.ButtonActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.70588237047195)
        clrs[clr.Header] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.HeaderHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.7843137383461)
        clrs[clr.HeaderActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.70588237047195)
        clrs[clr.Separator] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.SeparatorHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.SeparatorActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.ResizeGrip] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.ResizeGripHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.7843137383461)
        clrs[clr.ResizeGripActive] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 0.70588237047195)
        clrs[clr.CloseButton] = ImVec4(9.9998999303352e-07, 9.9998999303352e-07, 9.9999999747524e-07, 1)
        clrs[clr.CloseButtonHovered] = ImVec4(0.29019609093666, 0.29019609093666, 0.29019609093666, 1)
        clrs[clr.CloseButtonActive] = ImVec4(0.77209305763245, 0.77208530902863, 0.77208530902863, 0.7843137383461)
        clrs[clr.PlotLines] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.PlotLinesHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.PlotHistogram] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.PlotHistogramHovered] = ImVec4(0.52941179275513, 0.70588237047195, 0.011764706112444, 1)
        clrs[clr.TextSelectedBg] = ImVec4(0.25581139326096, 0.25581139326096, 0.25581395626068, 0.34999999403954)
        clrs[clr.ModalWindowDarkening] = ImVec4(0.20000000298023, 0.20000000298023, 0.20000000298023, 0.34999999403954)
    elseif styles == 2 then
        clrs[clr.Text] = ImVec4(1, 0.99998998641968, 0.99998998641968, 1)
        clrs[clr.TextDisabled] = ImVec4(0.60000002384186, 0.60000002384186, 0.60000002384186, 1)
        clrs[clr.WindowBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ChildWindowBg] = ImVec4(0, 0, 0, 0)
        clrs[clr.PopupBg] = ImVec4(0.70588237047195, 0.011764694936574, 0.37980872392654, 1)
        clrs[clr.Border] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.BorderShadow] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.FrameBg] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.70588237047195)
        clrs[clr.FrameBgHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.58823531866074)
        clrs[clr.FrameBgActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.39215686917305)
        clrs[clr.TitleBg] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.82352942228317)
        clrs[clr.TitleBgActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.TitleBgCollapsed] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.66666668653488)
        clrs[clr.MenuBarBg] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.ScrollbarBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ScrollbarGrab] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.ScrollbarGrabHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.7843137383461)
        clrs[clr.ScrollbarGrabActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.58823531866074)
        clrs[clr.ComboBg] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.7843137383461)
        clrs[clr.CheckMark] = ImVec4(1, 1, 1, 1)
        clrs[clr.SliderGrab] = ImVec4(0.1803921610117, 0.1803921610117, 0.1803921610117, 1)
        clrs[clr.SliderGrabActive] = ImVec4(0.258823543787, 0.258823543787, 0.258823543787, 1)
        clrs[clr.Button] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.ButtonHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.7843137383461)
        clrs[clr.ButtonActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.70588237047195)
        clrs[clr.Header] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.HeaderHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.7843137383461)
        clrs[clr.HeaderActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.70588237047195)
        clrs[clr.Separator] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.SeparatorHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.SeparatorActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.ResizeGrip] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.ResizeGripHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.7843137383461)
        clrs[clr.ResizeGripActive] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 0.70588237047195)
        clrs[clr.CloseButton] = ImVec4(9.9998999303352e-07, 9.9998999303352e-07, 9.9999999747524e-07, 1)
        clrs[clr.CloseButtonHovered] = ImVec4(0.29019609093666, 0.29019609093666, 0.29019609093666, 1)
        clrs[clr.CloseButtonActive] = ImVec4(0.77209305763245, 0.77208530902863, 0.77208530902863, 0.7843137383461)
        clrs[clr.PlotLines] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.PlotLinesHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.PlotHistogram] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.PlotHistogramHovered] = ImVec4(0.70588237047195, 0.011764706112444, 0.38039216399193, 1)
        clrs[clr.TextSelectedBg] = ImVec4(0.25581139326096, 0.25581139326096, 0.25581395626068, 0.34999999403954)
        clrs[clr.ModalWindowDarkening] = ImVec4(0.20000000298023, 0.20000000298023, 0.20000000298023, 0.34999999403954)
    elseif styles == 3 then
        clrs[clr.Text] = ImVec4(1, 0.99998998641968, 0.99998998641968, 1)
        clrs[clr.TextDisabled] = ImVec4(0.60000002384186, 0.60000002384186, 0.60000002384186, 1)
        clrs[clr.WindowBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ChildWindowBg] = ImVec4(0, 0, 0, 0)
        clrs[clr.PopupBg] = ImVec4(0.85116279125214, 0.59383445978165, 0, 1)
        clrs[clr.Border] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.BorderShadow] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.FrameBg] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.70588237047195)
        clrs[clr.FrameBgHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.58823531866074)
        clrs[clr.FrameBgActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.39215686917305)
        clrs[clr.TitleBg] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.82352942228317)
        clrs[clr.TitleBgActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.TitleBgCollapsed] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.66666668653488)
        clrs[clr.MenuBarBg] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.ScrollbarBg] = ImVec4(0, 0, 0, 1)
        clrs[clr.ScrollbarGrab] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.ScrollbarGrabHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.7843137383461)
        clrs[clr.ScrollbarGrabActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.58823531866074)
        clrs[clr.ComboBg] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.7843137383461)
        clrs[clr.CheckMark] = ImVec4(1, 1, 1, 1)
        clrs[clr.SliderGrab] = ImVec4(0.1803921610117, 0.1803921610117, 0.1803921610117, 1)
        clrs[clr.SliderGrabActive] = ImVec4(0.258823543787, 0.258823543787, 0.258823543787, 1)
        clrs[clr.Button] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.ButtonHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.7843137383461)
        clrs[clr.ButtonActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.70588237047195)
        clrs[clr.Header] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.HeaderHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.7843137383461)
        clrs[clr.HeaderActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.70588237047195)
        clrs[clr.Separator] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.SeparatorHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.SeparatorActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.ResizeGrip] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.ResizeGripHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.7843137383461)
        clrs[clr.ResizeGripActive] = ImVec4(0.85490196943283, 0.59215688705444, 0, 0.70588237047195)
        clrs[clr.CloseButton] = ImVec4(9.9998999303352e-07, 9.9998999303352e-07, 9.9999999747524e-07, 1)
        clrs[clr.CloseButtonHovered] = ImVec4(0.29019609093666, 0.29019609093666, 0.29019609093666, 1)
        clrs[clr.CloseButtonActive] = ImVec4(0.77209305763245, 0.77208530902863, 0.77208530902863, 0.7843137383461)
        clrs[clr.PlotLines] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.PlotLinesHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.PlotHistogram] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.PlotHistogramHovered] = ImVec4(0.85490196943283, 0.59215688705444, 0, 1)
        clrs[clr.TextSelectedBg] = ImVec4(0.25581139326096, 0.25581139326096, 0.25581395626068, 0.34999999403954)
        clrs[clr.ModalWindowDarkening] = ImVec4(0.20000000298023, 0.20000000298023, 0.20000000298023, 0.34999999403954)
    end
   
    local styles = {u8"Синий стиль", u8"Зеленый стиль", u8"Розовый стиль", u8"Оранджевый стиль"}

    if not main_window_state.v then
        imgui.Process = false
    end

    if main_window_state.v then
        local sw, sh = getScreenResolution()

        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(600, 475), imgui.Cond.FirstUseEver)
        imgui.Begin(u8"Авто Пиар", main_window_state, imgui.WindowFlags.NoResize)
        imgui.SetCursorPosX((imgui.GetWindowWidth() - imgui.CalcTextSize(u8("Пиар в /vr")).x)/2)
        imgui.Text(u8"Пиар в /vr")
        if imgui.Checkbox("##1", vr_check) then
            cfg.interface.vr_checkbox = vr_check.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.SameLine(30)
        imgui.PushItemWidth(560)
        if imgui.InputText("##2", vr) then
            cfg.config.vr = vr.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.PushItemWidth(582)
        if imgui.SliderInt("##3", vr_slider, 1, 10, u8'%.0f мин') then
            cfg.interface.vr_slider = vr_slider.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.Separator()
        imgui.SetCursorPosX((imgui.GetWindowWidth() - imgui.CalcTextSize(u8("Пиар в /fam")).x)/2)
        imgui.Text(u8"Пиар в /fam")
        if imgui.Checkbox("##4", fam_check) then
            cfg.interface.fam_checkbox = fam_check.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.SameLine(30)
        imgui.PushItemWidth(560)
        if imgui.InputText("##5", fam) then
            cfg.config.fam = fam.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.PushItemWidth(582)
        if imgui.SliderInt("##6", fam_slider, 1, 10, u8'%.0f мин') then
            cfg.interface.fam_slider = fam_slider.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.Separator()
        imgui.SetCursorPosX((imgui.GetWindowWidth() - imgui.CalcTextSize(u8("Пиар в /j")).x)/2)
        imgui.Text(u8"Пиар в /j")
        if imgui.Checkbox("##7", j_check) then
            cfg.interface.j_checkbox = j_check.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.SameLine(30)
        imgui.PushItemWidth(560)
        if imgui.InputText("##8", j) then
            cfg.config.j = j.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.PushItemWidth(582)
        if imgui.SliderInt("##9", j_slider, 1, 10, u8'%.0f мин') then
            cfg.interface.j_slider = j_slider.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.Separator()
        imgui.SetCursorPosX((imgui.GetWindowWidth() - imgui.CalcTextSize(u8("Пиар в /s")).x)/2)
        imgui.Text(u8"Пиар в /s")
        if imgui.Checkbox("##10", s_check) then
            cfg.interface.s_checkbox = s_check.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.SameLine(30)
        imgui.PushItemWidth(560)
        if imgui.InputText("##11", s) then
            cfg.config.s = s.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.PushItemWidth(582)
        if imgui.SliderInt("##12", s_slider, 1, 10, u8'%.0f мин') then
            cfg.interface.s_slider = s_slider.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.Separator()
        imgui.SetCursorPosX((imgui.GetWindowWidth() - imgui.CalcTextSize(u8("Пиар в /ad")).x)/2)
        imgui.Text(u8"Пиар в /ad")
        if imgui.Checkbox("##13", ad_check) then
            cfg.interface.ad_checkbox = ad_check.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.SameLine(30)
        imgui.PushItemWidth(560)
        if imgui.InputText("##14", ad) then
            cfg.config.ad = ad.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.PushItemWidth(582)
        if imgui.SliderInt("##15", ad_slider, 1, 10, u8'%.0f мин') then
            cfg.interface.ad_slider = ad_slider.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        if imgui.RadioButton(u8"Обычное объявление", ad_radiobutton, 1) then
            cfg.interface.ad_radiobutton = ad_radiobutton.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.SameLine(470)
        if imgui.RadioButton(u8"VIP объявление", ad_radiobutton, 2) then
            cfg.interface.ad_radiobutton = ad_radiobutton.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.Separator()
        imgui.SetCursorPosX((imgui.GetWindowWidth() - imgui.CalcTextSize(u8("Цветовая тема окна")).x)/2)
        imgui.Text(u8"Цветовая тема окна")
        if imgui.Combo("##16", themes_combo, styles) then
            styles = themes_combo.v
            cfg.interface.theme_id = themes_combo.v
            inicfg.save(cfg, "AutoPiar.ini")
        end
        imgui.Separator()
        if imgui.Button(u8((stat['act'] and 'Остановить' or 'Запустить')..' авто-пиар'), imgui.ImVec2(582, 20)) then
            stat['act'] = not stat['act']
            if stat['act'] then
                piar_vr1 = lua_thread.create(piar_vr)
                piar_fam2 = lua_thread.create(piar_fam)
                piar_j3 = lua_thread.create(piar_j)
                piar_s4 = lua_thread.create(piar_s)
                piar_ad5 = lua_thread.create(piar_ad)
            else
                if piar_vr1 then piar_vr1:terminate() end
                if piar_fam2 then piar_fam2:terminate() end
                if piar_j3 then piar_j3:terminate() end
                if piar_s4 then piar_s4:terminate() end
                if piar_ad5 then piar_ad5:terminate() end
            end
            if vr_check.v == false and fam_check.v == false and j_check.v == false and ad_check.v == false and s_check.v == false then
                sampAddChatMessage("[AutoPiar]: {FFFFFF}Небыло выбрано ниодного варианта пиара!", 0x5CBCFF)
                stat['act'] = false
            else
                sampAddChatMessage(stat['act'] and "[AutoPiar]: {FFFFFF}Пиар активирован!" or "[AutoPiar]: {FFFFFF}Пиар деактивирован!", 0x5CBCFF)
            end
        end
        imgui.End()
    end
end

function ev.onSendCommand(cmd)
    local result = cmd:match("^/vr (.+)")
    if result ~= nil then
        if process ~= nil and result ~= message then
            process:terminate()
            process = nil
        end
        if process == nil then
            finished, try = false, 1
            message = tostring(result)
            process = lua_thread.create(function()
                while not finished do
                    if sampGetGamestate() ~= 3 then
                        finished = true; break
                    end
                    if not sampIsChatInputActive() then
                        local rotate = math.sin(os.clock() * 3) * 90 + 90
                        local el = getStructElement(sampGetInputInfoPtr(), 0x8, 4)
                        local X, Y = getStructElement(el, 0x8, 4), getStructElement(el, 0xC, 4)
                        renderDrawPolygon(X + 10, Y + (renderGetFontDrawHeight(font) / 2), 20, 20, 3, rotate, 0xFFFFFFFF)
                        renderDrawPolygon(X + 10, Y + (renderGetFontDrawHeight(font) / 2), 20, 20, 3, -1 * rotate, 0xFF0090FF)
                        renderFontDrawText(font, message, X + 25, Y, -1)
                        renderFontDrawText(font, string.format(" [x%s]", try), X + 25 + renderGetFontDrawTextLength(font, message), Y, 0x40FFFFFF)
                    end
                    wait(0)
                end
                process = nil
            end)
        end
    end
end

function ev.onServerMessage(color, text)
    if not finished then
        if text:find("^%[Ошибка%].*После последнего сообщения в этом чате нужно подождать") then
            lua_thread.create(function()
                wait(delay * 1000);
                sampSendChat("/vr " .. message)
                try = try + 1  
            end)
            return false
        end

        local id = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
        if text:match("%[%u+%] {%x+}[A-z0-9_]+%[" .. id .. "%]:") then
            finished = true
        end
    end

    if text:find("^Вы заглушены") or text:find("Для возможности повторной отправки сообщения в этот чат") then
        finished = true
    end
end
ыва:
function piar_vr()
    wait(2300)
    while stat['act'] do
        if vr_check.v then
            sampSendChat("/vr " .. vr.v)
            wait(vr_slider.v*60000)
            sampAddChatMessage("Если ты видишь это сообщение, значит отчет работает", -1)
        end
    end
end

замени функцию
 
  • Нравится
  • Влюблен
Реакции: ARMOR и xzavier

Qvim

Известный
10
8
Приветствую всех :)
Есть ли какой-то скрипт, что поможет определить какая modelId используется в текстдраве? Или их следует перебирать вручную?
 

sep

Известный
714
79
Приветствую всех :)
Есть ли какой-то скрипт, что поможет определить какая modelId используется в текстдраве? Или их следует перебирать вручную?

их много
код:
script_name('DrawTextDrawID')

function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local font = renderCreateFont("Arial", 8, 5)
    sampRegisterChatCommand("IDTD", show) 
    while true do
    wait(0)
        if toggle then
            for a = 0, 2304    do
                if sampTextdrawIsExists(a) then
                    x, y = sampTextdrawGetPos(a)
                    x1, y1 = convertGameScreenCoordsToWindowScreenCoords(x, y)
                    renderFontDrawText(font, a, x1, y1, 0xFFBEBEBE)
                end
            end
            
        end
    end
end

function show()
toggle = not toggle
end
 
  • Нравится
Реакции: Qvim

sat0ry

Известный
1,084
301
Приветствую, можно ли как то сделать обратный отсчет с помощью os.date?
 

Rice.

Известный
Модератор
1,757
1,706
Приветствую, в чем проблема?
Lua:
asyncHttpRequest('GET', 'https://api.vk.com/method/users.get', {params = {user_ids = '728895230', fields = 'bdate', access_token = 'ТОКЕН', v = '5.131'}},
function(response)
    print(response)
end,
function(err)
    print(err)
end)

--------------------------

function asyncHttpRequest(method, url, args, resolve, reject)
   local request_thread = effil.thread(function (method, url, args)
      local requests = require 'requests'
      local result, response = pcall(requests.request, method, url, args)
      if result then
         response.json, response.xml = nil, nil
         return true, response
      else
         return false, response
      end
   end)(method, url, args)
   -- Если запрос без функций обработки ответа и ошибок.
   if not resolve then resolve = function() end end
   if not reject then reject = function() end end
   -- Проверка выполнения потока
   lua_thread.create(function()
      local runner = request_thread
      while true do
         local status, err = runner:status()
         if not err then
            if status == 'completed' then
               local result, response = runner:get()
               if result then
                  resolve(response)
               else
                  reject(response)
               end
               return
            elseif status == 'canceled' then
               return reject(status)
            end
         else
            return reject(err)
         end
         wait(0)
      end
   end)
end
1652359119584.png
 

ewin

Известный
672
376
есть функция на подобии printStyledStringNow?
знаю только printStringNow
 

0x73616D

Активный
140
43
How can I get how far away I am from the 3dtext? | Как узнать, насколько далеко я от 3dtext?
 

Sergey_Turner

Участник
102
7
Приветствую. Есть такой код:
Code:
config: InputText=Text1||Text2||Text3

InputText.v = string.gsub(InputText.v, '||', '\n')
i = 0
for v in string.gmatch(InputText.v, '[^\r\n]+') do
    i = i + 1
    text = InputText.v
    string = string.format("{FFFFFF}%d) %s", i, text)
    imgui.Text(string)
end
Он выводит:
Вывод:
1) Text1
Text2
Text3
2) Text1
Text2
Text3
3) Text1
Text2
Text3
А необходимо:
Необходимо:
1) Text1
2) Text2
3) Text3
Как это можно реализовать?
 

chapo

tg/inst: @moujeek
Всефорумный модератор
9,240
12,659
Приветствую. Есть такой код:
Code:
config: InputText=Text1||Text2||Text3

InputText.v = string.gsub(InputText.v, '||', '\n')
i = 0
for v in string.gmatch(InputText.v, '[^\r\n]+') do
    i = i + 1
    text = InputText.v
    string = string.format("{FFFFFF}%d) %s", i, text)
    imgui.Text(string)
end
Он выводит:
Вывод:
1) Text1
Text2
Text3
2) Text1
Text2
Text3
3) Text1
Text2
Text3
А необходимо:
Необходимо:
1) Text1
2) Text2
3) Text3
Как это можно реализовать?
замени text на v
1652436018652.png
 
  • Нравится
Реакции: Sergey_Turner

shrug228

Активный
212
77
How can I get how far away I am from the 3dtext? | Как узнать, насколько далеко я от 3dtext?
Lua:
function getDistanceInWorld3D(pedX, pedY, pedZ, posX, posY, posZ)
    pedX,pedY,pedZ = getCharCoordinates(playerPed)
    distance= math.sqrt( ((posX-pedX)^2) + ((posY-pedY)^2) + ((posZ-pedZ)^2))
    return distance
end

local result = getDistanceInWorld3D(getCharCoordinates(PLAYER_PED)--[[, 3dtext coordinates]])
I have taken this function from this message.

Lua:
printStringNow('~r~Hello world!') -- выведет красный текст
есть функция на подобии printStyledStringNow?
знаю только printStringNow
Lua:
printStringNow('~r~ Hello ~g~world!', 3000) -- выведет красный текст

Приветствую, в чем проблема?
Lua:
asyncHttpRequest('GET', 'https://api.vk.com/method/users.get', {params = {user_ids = '728895230', fields = 'bdate', access_token = 'ТОКЕН', v = '5.131'}},
function(response)
    print(response)
end,
function(err)
    print(err)
end)

--------------------------

function asyncHttpRequest(method, url, args, resolve, reject)
   local request_thread = effil.thread(function (method, url, args)
      local requests = require 'requests'
      local result, response = pcall(requests.request, method, url, args)
      if result then
         response.json, response.xml = nil, nil
         return true, response
      else
         return false, response
      end
   end)(method, url, args)
   -- Если запрос без функций обработки ответа и ошибок.
   if not resolve then resolve = function() end end
   if not reject then reject = function() end end
   -- Проверка выполнения потока
   lua_thread.create(function()
      local runner = request_thread
      while true do
         local status, err = runner:status()
         if not err then
            if status == 'completed' then
               local result, response = runner:get()
               if result then
                  resolve(response)
               else
                  reject(response)
               end
               return
            elseif status == 'canceled' then
               return reject(status)
            end
         else
            return reject(err)
         end
         wait(0)
      end
   end)
end
Посмотреть вложение 147751
Могу посоветовать попробовать: а) использовать строковые ключи для таблиц (пример ниже); б) составить запрос вручную.
Lua:
t = {
    ['test'] = 1,
    ['test2'] = 2
}
 
Последнее редактирование:
  • Нравится
Реакции: 0x73616D

wqaddfs0

Потрачен
12
36
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Есть вот такой код:
Lua:
if imgui.BeginPopupModal(u8'test') then
    imgui.Text(u8'Привет!')
    imgui.EndPopup()
end
Как сделать так, чтобы нельзя было изменить размер Popup'a в мимгуи?
 

ch1ps

Участник
101
3
как получить анимку стана, которая сейчас проигрывается и сбить её?
onApplyPlayerAnimation не вариант, ибо она получает лишь анимки от сервера, а
sampGetPlayerAnimationId отправляет 0
 

moreveal

Известный
988
723
Сколько раз не пытался узнать как сделать, чтобы HTTP запросы не фризили игру - кидали ссылку на асинхронные. Я испробовал обе функции (и с requests, и без) - безрезультатно, каждый запрос происходит фриз, длиной в секунду. Есть вообще возможность отправлять запросы без зависаний, если требуется получить ответ от сервера?
Lua:
local response = httpRequest("POST", {"https://random-site.com", data = data, headers = headers})
assert(response.status_code == 200, "Не установлено соединение с сервером")
local result = decodeJson(response.text)

-- используемая функция
local copas = require 'copas'
local http = require 'copas.http'
local requests = require 'requests'
requests.http_socket, requests.https_socket = http, http
function httpRequest(method, request, args, handler) -- lua-requests
    -- start polling task
    if not copas.running then
        copas.running = true
        lua_thread.create(function()
            wait(0)
            while not copas.finished() do
                local ok, err = copas.step(0)
                if ok == nil then error(err) end
                wait(0)
            end
            copas.running = false
        end)
    end
    -- do request
    if handler then
        return copas.addthread(function(m, r, a, h)
            copas.setErrorHandler(function(err) h(nil, err) end)
            h(requests.request(m, r, a))
        end, method, request, args, handler)
    else
        local results
        local thread = copas.addthread(function(m, r, a)
            copas.setErrorHandler(function(err) results = {nil, err} end)
            results = table.pack(requests.request(m, r, a))
        end, method, request, args)
        while coroutine.status(thread) ~= 'dead' do wait(0) end
        return table.unpack(results)
    end
end