Вопросы по 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
 
Последнее редактирование:
464
827
Lua:
local phv = os.getenv('TEMP') .. '\\testaVERSION.json'
local dlstatus = require('moonloader').download_status
local fpath = os.getenv('TEMP') .. '\\testalua'
local key = require "vkeys"
local vkeys = require 'vkeys'
local wm = require 'lib.windows.message'
local imgui = require 'imgui'
local encoding = require 'encoding'
local sampev = require 'lib.samp.events'
local rkeys = require 'rkeys'
imgui.ShowCursor = false
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
local dlstatus = require('moonloader').download_status
imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar
encoding.default = 'CP1251'
u8 = encoding.UTF8
show_main_window1 = imgui.ImBool(false)

local window = imgui.ImBool(false)
local ActiveMenu = {
    v = {vkeys.VK_F2}
}
local bindID = 0

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end -- проверяем загружен ли SAMP и сам SampFuncs, если нет, то сбрасываем соединение
    while not isSampAvailable() do wait(0) end -- проверяем доступен ли SAMP, если нет, то жде
    sampRegisterChatCommand("testa", function ()
        window.v = true
    end)
    sampRegisterChatCommand("inv", function ()
      lua_thread.create(function ()
        sampSendChat('Поздравляю, Вы нам подходите. Осталось пару действий.')
          wait(1500)
          sampSendChat('/me достал папку с полки для нового рабочего')
          wait(1500)
          sampSendChat('/do Папка в руке.')
          wait(1500)
          sampSendChat('/me положил папку в развернутом виде перед человеком напротив')
          wait(1500)
          sampSendChat('/me передал ручку человеку напротив')
          wait(1500)
          sampSendChat('Пожалуйста распишитесь для полного трудоустройства.')
          wait(1500)
          sampSendChat('/do Пакет с формой рацией и бейджем под столом.')
          wait(1500)
          sampSendChat('/me нагнувшись поднял пакет')
          wait(1500)
          sampSendChat('/do Пакет в левой руке.')
          wait(1500)
          sampSendChat('/me передал пакет с формой рацией и бейджем человеку напротив')
          sampAddChatMessage('{00FF00}[Помощник]: {FFFFFF}/invite [id]', -1)
      end)
    end)
    bindID = rkeys.registerHotKey(ActiveMenu.v, true, function ()
        window.v = not window.v
    end)
    while true do
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
        if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
          local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
          if result then -- проверить, прошло ли получение ида успешно
            if valid and doesCharExist(ped) and isKeyJustPressed(88) then
               nickname = sampGetPlayerNickname(id)
            end
          end 
        end
        if wasKeyPressed(key.VK_X) then
            bool, player = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if bool then
                _, id = sampGetPlayerIdByCharHandle(player)
            end
        end
        wait(0)
        imgui.Process = window.v
    end
end

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

colors[clr.Text] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[clr.TextDisabled] = ImVec4(0.60, 0.60, 0.60, 1.00)
colors[clr.WindowBg] = ImVec4(0.11, 0.10, 0.11, 1.00)
colors[clr.ChildWindowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PopupBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.Border] = ImVec4(0.86, 0.86, 0.86, 1.00)
colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.FrameBg] = ImVec4(0.21, 0.20, 0.21, 0.60)
colors[clr.FrameBgHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.FrameBgActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBg] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBgCollapsed] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBgActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.MenuBarBg] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ScrollbarBg] = ImVec4(0.00, 0.46, 0.65, 0.00)
colors[clr.ScrollbarGrab] = ImVec4(0.00, 0.46, 0.65, 0.44)
colors[clr.ScrollbarGrabHovered] = ImVec4(0.00, 0.46, 0.65, 0.74)
colors[clr.ScrollbarGrabActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ComboBg] = ImVec4(0.15, 0.14, 0.15, 1.00)
colors[clr.CheckMark] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.SliderGrab] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.SliderGrabActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.Button] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ButtonHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ButtonActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.Header] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.HeaderHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.HeaderActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ResizeGrip] = ImVec4(1.00, 1.00, 1.00, 0.30)
colors[clr.ResizeGripHovered] = ImVec4(1.00, 1.00, 1.00, 0.60)
colors[clr.ResizeGripActive] = ImVec4(1.00, 1.00, 1.00, 0.90)
colors[clr.CloseButton] = ImVec4(1.00, 0.10, 0.24, 0.00)
colors[clr.CloseButtonHovered] = ImVec4(0.00, 0.10, 0.24, 0.00)
colors[clr.CloseButtonActive] = ImVec4(1.00, 0.10, 0.24, 0.00)
colors[clr.PlotLines] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotLinesHovered] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotHistogram] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotHistogramHovered] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.TextSelectedBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.ModalWindowDarkening] = ImVec4(0.00, 0.00, 0.00, 0.00)
end
apply_custom_style()

local imBool = imgui.ImBool(false)
local imBool2 = imgui.ImBool(false)
local imBool3 = imgui.ImBool(false)
local imBool4 = imgui.ImBool(false)
local menu1 = imgui.ImBool(false)
local menu2 = imgui.ImBool(false)

function imgui.OnDrawFrame()
    local iScreenWidth, iScreenHeight = getScreenResolution()
    local tLastKeys = {}

   imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2, iScreenHeight / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   imgui.SetNextWindowSize(imgui.ImVec2(400, 450), imgui.Cond.FirstUseEver)
 
   imgui.Begin(u8"testa", window, imgui.WindowFlags.NoResize)
        if imgui.Selectable(u8('Information of helper'), false) then end

   if imgui.HotKey("##active", ActiveMenu, tLastKeys, 100) then
      rkeys.changeHotKey(bindID, ActiveMenu.v)
      sampAddChatMessage("Успешно! Старое значение: " .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. " | Новое: " .. table.concat(rkeys.getKeysName(ActiveMenu.v), " + "), -1)
   end
    if imgui.Button('press') then
        menu2.v = not menu2.v
    end
    imgui.End()
    if menu2.v then
        imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2.2, iScreenHeight / 2.2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(400, 200), imgui.Cond.FirstUseEver)
        imgui.Begin("testa", menu2)
        imgui.BeginChild('left pane', imgui.ImVec2(380, 0), true)
        if not selected then selected = 1 end
        if imgui.Selectable(u8('33333'), false) then selected = 1 end
        if imgui.Selectable(u8('12345'), false) then
             show_main_window1.v = not show_main_window1.v
        end
 
        if show_main_window1.v then
           imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver,         imgui.ImVec2(0.5, 0.5))
           imgui.SetNextWindowSize(imgui.ImVec2(330, 300), imgui.Cond.FirstUseEver)
           imgui.Begin('hello', show_imgui_example1)
           imgui.Text('New Okno')
           imgui.End()
        end     
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginGroup()
        imgui.EndGroup()
        imgui.End()
    end
end
Lua:
local phv = os.getenv('TEMP') .. '\\testaVERSION.json'
local dlstatus = require('moonloader').download_status
local fpath = os.getenv('TEMP') .. '\\testalua'
local key = require "vkeys"
local vkeys = require 'vkeys'
local wm = require 'lib.windows.message'
local imgui = require 'imgui'
local encoding = require 'encoding'
local sampev = require 'lib.samp.events'
local rkeys = require 'rkeys'
imgui.ShowCursor = false
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
local dlstatus = require('moonloader').download_status
imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar
encoding.default = 'CP1251'
u8 = encoding.UTF8
show_main_window1 = imgui.ImBool(false)

local window = imgui.ImBool(false)
local ActiveMenu = {
    v = {vkeys.VK_F2}
}
local bindID = 0

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end -- проверяем загружен ли SAMP и сам SampFuncs, если нет, то сбрасываем соединение
    while not isSampAvailable() do wait(0) end -- проверяем доступен ли SAMP, если нет, то жде
    sampRegisterChatCommand("testa", function ()
        window.v = true
    end)
    sampRegisterChatCommand("inv", function ()
      lua_thread.create(function ()
        sampSendChat('Поздравляю, Вы нам подходите. Осталось пару действий.')
          wait(1500)
          sampSendChat('/me достал папку с полки для нового рабочего')
          wait(1500)
          sampSendChat('/do Папка в руке.')
          wait(1500)
          sampSendChat('/me положил папку в развернутом виде перед человеком напротив')
          wait(1500)
          sampSendChat('/me передал ручку человеку напротив')
          wait(1500)
          sampSendChat('Пожалуйста распишитесь для полного трудоустройства.')
          wait(1500)
          sampSendChat('/do Пакет с формой рацией и бейджем под столом.')
          wait(1500)
          sampSendChat('/me нагнувшись поднял пакет')
          wait(1500)
          sampSendChat('/do Пакет в левой руке.')
          wait(1500)
          sampSendChat('/me передал пакет с формой рацией и бейджем человеку напротив')
          sampAddChatMessage('{00FF00}[Помощник]: {FFFFFF}/invite [id]', -1)
      end)
    end)
    bindID = rkeys.registerHotKey(ActiveMenu.v, true, function ()
        window.v = not window.v
    end)
    while true do
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
        if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
          local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
          if result then -- проверить, прошло ли получение ида успешно
            if valid and doesCharExist(ped) and isKeyJustPressed(88) then
               nickname = sampGetPlayerNickname(id)
            end
          end
        end
        if wasKeyPressed(key.VK_X) then
            bool, player = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if bool then
                _, id = sampGetPlayerIdByCharHandle(player)
            end
        end
        wait(0)
        imgui.Process = window.v
    end
end

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

colors[clr.Text] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[clr.TextDisabled] = ImVec4(0.60, 0.60, 0.60, 1.00)
colors[clr.WindowBg] = ImVec4(0.11, 0.10, 0.11, 1.00)
colors[clr.ChildWindowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PopupBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.Border] = ImVec4(0.86, 0.86, 0.86, 1.00)
colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.FrameBg] = ImVec4(0.21, 0.20, 0.21, 0.60)
colors[clr.FrameBgHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.FrameBgActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBg] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBgCollapsed] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBgActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.MenuBarBg] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ScrollbarBg] = ImVec4(0.00, 0.46, 0.65, 0.00)
colors[clr.ScrollbarGrab] = ImVec4(0.00, 0.46, 0.65, 0.44)
colors[clr.ScrollbarGrabHovered] = ImVec4(0.00, 0.46, 0.65, 0.74)
colors[clr.ScrollbarGrabActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ComboBg] = ImVec4(0.15, 0.14, 0.15, 1.00)
colors[clr.CheckMark] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.SliderGrab] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.SliderGrabActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.Button] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ButtonHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ButtonActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.Header] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.HeaderHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.HeaderActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ResizeGrip] = ImVec4(1.00, 1.00, 1.00, 0.30)
colors[clr.ResizeGripHovered] = ImVec4(1.00, 1.00, 1.00, 0.60)
colors[clr.ResizeGripActive] = ImVec4(1.00, 1.00, 1.00, 0.90)
colors[clr.CloseButton] = ImVec4(1.00, 0.10, 0.24, 0.00)
colors[clr.CloseButtonHovered] = ImVec4(0.00, 0.10, 0.24, 0.00)
colors[clr.CloseButtonActive] = ImVec4(1.00, 0.10, 0.24, 0.00)
colors[clr.PlotLines] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotLinesHovered] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotHistogram] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotHistogramHovered] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.TextSelectedBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.ModalWindowDarkening] = ImVec4(0.00, 0.00, 0.00, 0.00)
end
apply_custom_style()

local imBool = imgui.ImBool(false)
local imBool2 = imgui.ImBool(false)
local imBool3 = imgui.ImBool(false)
local imBool4 = imgui.ImBool(false)
local menu1 = imgui.ImBool(false)
local menu2 = imgui.ImBool(false)

function imgui.OnDrawFrame()
    local iScreenWidth, iScreenHeight = getScreenResolution()
    local tLastKeys = {}

   imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2, iScreenHeight / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   imgui.SetNextWindowSize(imgui.ImVec2(400, 450), imgui.Cond.FirstUseEver)

   imgui.Begin(u8"testa", window, imgui.WindowFlags.NoResize)
        if imgui.Selectable(u8('Information of helper'), false) then end

   if imgui.HotKey("##active", ActiveMenu, tLastKeys, 100) then
      rkeys.changeHotKey(bindID, ActiveMenu.v)
      sampAddChatMessage("Успешно! Старое значение: " .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. " | Новое: " .. table.concat(rkeys.getKeysName(ActiveMenu.v), " + "), -1)
   end
    if imgui.Button('press') then
        menu2.v = not menu2.v
    end
    imgui.End()
    if menu2.v then
        imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2.2, iScreenHeight / 2.2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(400, 200), imgui.Cond.FirstUseEver)
        imgui.Begin("testa", menu2)
        imgui.BeginChild('left pane', imgui.ImVec2(380, 0), true)
        if not selected then selected = 1 end
        if imgui.Selectable(u8('33333'), false) then selected = 1 end
        if imgui.Selectable(u8('12345'), false) then
             show_main_window1.v = not show_main_window1.v
        end

        if show_main_window1.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(150, 150), imgui.Cond.FirstUseEver)
                     imgui.Begin('hello', show_imgui_example1)
                     imgui.Text('New Okno')
                     imgui.End()
        end
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginGroup()
        imgui.EndGroup()
        imgui.End()
    end
end
 

sdfaw

Активный
717
150
Lua:
local phv = os.getenv('TEMP') .. '\\testaVERSION.json'
local dlstatus = require('moonloader').download_status
local fpath = os.getenv('TEMP') .. '\\testalua'
local key = require "vkeys"
local vkeys = require 'vkeys'
local wm = require 'lib.windows.message'
local imgui = require 'imgui'
local encoding = require 'encoding'
local sampev = require 'lib.samp.events'
local rkeys = require 'rkeys'
imgui.ShowCursor = false
local style = imgui.GetStyle()
local colors = style.Colors
local clr = imgui.Col
local ImVec4 = imgui.ImVec4
local dlstatus = require('moonloader').download_status
imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar
encoding.default = 'CP1251'
u8 = encoding.UTF8
show_main_window1 = imgui.ImBool(false)

local window = imgui.ImBool(false)
local ActiveMenu = {
    v = {vkeys.VK_F2}
}
local bindID = 0

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end -- проверяем загружен ли SAMP и сам SampFuncs, если нет, то сбрасываем соединение
    while not isSampAvailable() do wait(0) end -- проверяем доступен ли SAMP, если нет, то жде
    sampRegisterChatCommand("testa", function ()
        window.v = true
    end)
    sampRegisterChatCommand("inv", function ()
      lua_thread.create(function ()
        sampSendChat('Поздравляю, Вы нам подходите. Осталось пару действий.')
          wait(1500)
          sampSendChat('/me достал папку с полки для нового рабочего')
          wait(1500)
          sampSendChat('/do Папка в руке.')
          wait(1500)
          sampSendChat('/me положил папку в развернутом виде перед человеком напротив')
          wait(1500)
          sampSendChat('/me передал ручку человеку напротив')
          wait(1500)
          sampSendChat('Пожалуйста распишитесь для полного трудоустройства.')
          wait(1500)
          sampSendChat('/do Пакет с формой рацией и бейджем под столом.')
          wait(1500)
          sampSendChat('/me нагнувшись поднял пакет')
          wait(1500)
          sampSendChat('/do Пакет в левой руке.')
          wait(1500)
          sampSendChat('/me передал пакет с формой рацией и бейджем человеку напротив')
          sampAddChatMessage('{00FF00}[Помощник]: {FFFFFF}/invite [id]', -1)
      end)
    end)
    bindID = rkeys.registerHotKey(ActiveMenu.v, true, function ()
        window.v = not window.v
    end)
    while true do
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
        if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
          local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
          if result then -- проверить, прошло ли получение ида успешно
            if valid and doesCharExist(ped) and isKeyJustPressed(88) then
               nickname = sampGetPlayerNickname(id)
            end
          end
        end
        if wasKeyPressed(key.VK_X) then
            bool, player = getCharPlayerIsTargeting(PLAYER_HANDLE)
            if bool then
                _, id = sampGetPlayerIdByCharHandle(player)
            end
        end
        wait(0)
        imgui.Process = window.v
    end
end

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

colors[clr.Text] = ImVec4(1.00, 1.00, 1.00, 1.00)
colors[clr.TextDisabled] = ImVec4(0.60, 0.60, 0.60, 1.00)
colors[clr.WindowBg] = ImVec4(0.11, 0.10, 0.11, 1.00)
colors[clr.ChildWindowBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PopupBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.Border] = ImVec4(0.86, 0.86, 0.86, 1.00)
colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.FrameBg] = ImVec4(0.21, 0.20, 0.21, 0.60)
colors[clr.FrameBgHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.FrameBgActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBg] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBgCollapsed] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.TitleBgActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.MenuBarBg] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ScrollbarBg] = ImVec4(0.00, 0.46, 0.65, 0.00)
colors[clr.ScrollbarGrab] = ImVec4(0.00, 0.46, 0.65, 0.44)
colors[clr.ScrollbarGrabHovered] = ImVec4(0.00, 0.46, 0.65, 0.74)
colors[clr.ScrollbarGrabActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ComboBg] = ImVec4(0.15, 0.14, 0.15, 1.00)
colors[clr.CheckMark] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.SliderGrab] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.SliderGrabActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.Button] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ButtonHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ButtonActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.Header] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.HeaderHovered] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.HeaderActive] = ImVec4(0.00, 0.46, 0.65, 1.00)
colors[clr.ResizeGrip] = ImVec4(1.00, 1.00, 1.00, 0.30)
colors[clr.ResizeGripHovered] = ImVec4(1.00, 1.00, 1.00, 0.60)
colors[clr.ResizeGripActive] = ImVec4(1.00, 1.00, 1.00, 0.90)
colors[clr.CloseButton] = ImVec4(1.00, 0.10, 0.24, 0.00)
colors[clr.CloseButtonHovered] = ImVec4(0.00, 0.10, 0.24, 0.00)
colors[clr.CloseButtonActive] = ImVec4(1.00, 0.10, 0.24, 0.00)
colors[clr.PlotLines] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotLinesHovered] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotHistogram] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.PlotHistogramHovered] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.TextSelectedBg] = ImVec4(0.00, 0.00, 0.00, 0.00)
colors[clr.ModalWindowDarkening] = ImVec4(0.00, 0.00, 0.00, 0.00)
end
apply_custom_style()

local imBool = imgui.ImBool(false)
local imBool2 = imgui.ImBool(false)
local imBool3 = imgui.ImBool(false)
local imBool4 = imgui.ImBool(false)
local menu1 = imgui.ImBool(false)
local menu2 = imgui.ImBool(false)

function imgui.OnDrawFrame()
    local iScreenWidth, iScreenHeight = getScreenResolution()
    local tLastKeys = {}

   imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2, iScreenHeight / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   imgui.SetNextWindowSize(imgui.ImVec2(400, 450), imgui.Cond.FirstUseEver)

   imgui.Begin(u8"testa", window, imgui.WindowFlags.NoResize)
        if imgui.Selectable(u8('Information of helper'), false) then end

   if imgui.HotKey("##active", ActiveMenu, tLastKeys, 100) then
      rkeys.changeHotKey(bindID, ActiveMenu.v)
      sampAddChatMessage("Успешно! Старое значение: " .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. " | Новое: " .. table.concat(rkeys.getKeysName(ActiveMenu.v), " + "), -1)
   end
    if imgui.Button('press') then
        menu2.v = not menu2.v
    end
    imgui.End()
    if menu2.v then
        imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2.2, iScreenHeight / 2.2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(400, 200), imgui.Cond.FirstUseEver)
        imgui.Begin("testa", menu2)
        imgui.BeginChild('left pane', imgui.ImVec2(380, 0), true)
        if not selected then selected = 1 end
        if imgui.Selectable(u8('33333'), false) then selected = 1 end
        if imgui.Selectable(u8('12345'), false) then
             show_main_window1.v = not show_main_window1.v
        end

        if show_main_window1.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(150, 150), imgui.Cond.FirstUseEver)
                     imgui.Begin('hello', show_imgui_example1)
                     imgui.Text('New Okno')
                     imgui.End()
        end
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginGroup()
        imgui.EndGroup()
        imgui.End()
    end
end
spasibo
 

LinkelnAweil

Участник
122
7
Подскажите, как правильно пользоваться string.format? У меня есть десятичное число, это %d, нужно преобразовать в %s но почему-то все равно %d остается.
 

sdfaw

Активный
717
150
как сделать чтобы когда вводишь в imgui.InputText например 123456 то в чат выводится "Вы успешно вошли!", а если что-то другое написать то в чат выводится "Неверный пароль!" ?
 

trefa

3d print
Всефорумный модератор
2,117
1,282
как сделать чтобы когда вводишь в imgui.InputText например 123456 то в чат выводится "Вы успешно вошли!", а если что-то другое написать то в чат выводится "Неверный пароль!" ?
Lua:
if param1 == param2 then
--code
end
 

trefa

3d print
Всефорумный модератор
2,117
1,282
Безуспешно. Число все также остается, хотя если в CLEO использовать такой же код и с помощью format, то все отлично работает, на Lua же - нет.
Тебе надо число перевести в строку или я вообще не понял?