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

meowprd

Тот самый Котовский
Проверенный
1,283
710
есть, идет в moonloader 0.27
я юзаю 026.5, как и большинство, наверное
актуал (Котовский помоги)
изменил в твоем коде:
local clipper = imgui.ImGuiListClipper(#messages) - перенес в imgui.OnDrawFrame() перед while clipper:step() do (потому что клиппер нужно пересоздавать, массив ведь изменяется)
убрал очистку массива messages = {} в hook.onServerMessage() (она там не нужна, потому что ты заносишь информацию и сразу очищаешь ее, зачем?
name, id, message = text:match('(.+)%[(%d+)%]: (.+)') - стоит использовать локальные переменные, заменил на local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
name = text:match('Имя: {......}(%S+)') - также заменил на local name = text:match('Имя: {......}(%S+)')
изменил часть кода в main(), а именно:
1. убрал imgui.Process = imguiokno.v
2. убрал imgui.Process = false
3. убрал while true do wait(0) if imguiokno.v == false then imgui.Process = false end end

эти три пункта можно уместить в одну строчку кода
while true do wait(0) imgui.Process = imguiokno.v end

итог:
Lua:
require 'lib.moonloader'

local hook = require 'lib.samp.events'
local encoding = require 'encoding'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local messages = {}
local imguiokno = imgui.ImBool(false)
local sw, sh = getScreenResolution()

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

    sampRegisterChatCommand('lua.j', function()
        imguiokno.v = not imguiokno.v
    end)

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

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

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0

    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.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.CheckMark]              = 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)
    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.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.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    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.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    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.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    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.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
blue()

function hook.onShowDialog(dialogId, style, title, button1, button2, text)
        if dialogId == 235 then
            --[[if text:find('Статус: {......}(.+)') then
                status = text:match('Статус: {......}(%S+)')
                sampAddChatMessage('Status: ' .. status,-1)
            end--]]
            if text:find('Имя: {......}(%S+)') then
                local name = text:match('Имя: {......}(%S+)')
                sampAddChatMessage(name,-1)
            end
        end
end

function hook.onServerMessage(color, text)
    --[[if text:find('%[Таксист%] .+%[%d+%]: .+') then
        name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
        --sampAddChatMessage("{15edc9}" .. name .. '[' ..id .. ']' .. ': ' .. message, 0x15edc9)
        print('\n' .. name .. '[' .. id .. ']' .. ': ' .. message)
        return false
    end--]]
    --[[if text:find('(.+)') then
        message = text:match('(.+)')
        print('\n\n' .. message)
        return false
    end--]]
    if text:find('%[Таксист%] .+%[%d+%]: .+') then
        local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
        table.insert(messages,{
            name = name,
            id = id,
            message = message
        })
        return false
    end
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(300, 150), imgui.Cond.FirstUseEver)

    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

    imgui.Begin('Taxi-Chat', imguiokno, imgui.WindowFlags.NoResize)
    imgui.BeginChild('##chatj', imgui.ImVec2(-1, -1), true)
    local clipper = imgui.ImGuiListClipper(#messages)
    while clipper:Step() do
        for i = clipper.DisplayStart + 1, clipper.DisplayEnd do
            imgui.Text(messages[i])
         end
    end
    imgui.EndChild()
    imgui.End()
end

update:
заметил только потом.
код выше работать не будет, так как ты в хуке onServerMessage в массив messages заносишь еще один массив (получается двумерный массив)
чтобы клиппер нормально показывал сообщения, надо заносить в таблицу уже формированное сообщение, так как clipper это тот же самый цикл for, который просто учитывает высоту строк для imgui

замени часть кода:
Lua:
if text:find('%[Таксист%] .+%[%d+%]: .+') then
    local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
    table.insert(messages,{
        name = name,
        id = id,
        message = message
    })
    return false
end

на
Lua:
if text:find('%[Таксист%] .+%[%d+%]: .+') then
    local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
    table.insert(messages, string.format("%s [id: %d]: %s", name, id, message))
    return false
end
 
Последнее редактирование:
  • Нравится
Реакции: Sanchez.

Sanchez.

Известный
704
186
я юзаю 026.5, как и большинство, наверное

изменил в твоем коде:
local clipper = imgui.ImGuiListClipper(#messages) - перенес в imgui.OnDrawFrame() перед while clipper:step() do (потому что клиппер нужно пересоздавать, массив ведь изменяется)
убрал очистку массива messages = {} в hook.onServerMessage() (она там не нужна, потому что ты заносишь информацию и сразу очищаешь ее, зачем?
name, id, message = text:match('(.+)%[(%d+)%]: (.+)') - стоит использовать локальные переменные, заменил на local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
name = text:match('Имя: {......}(%S+)') - также заменил на local name = text:match('Имя: {......}(%S+)')
изменил часть кода в main(), а именно:
1. убрал imgui.Process = imguiokno.v
2. убрал imgui.Process = false
3. убрал while true do wait(0) if imguiokno.v == false then imgui.Process = false end end

эти три пункта можно уместить в одну строчку кода
while true do wait(0) imgui.Process = imguiokno.v end

итог:
Lua:
require 'lib.moonloader'

local hook = require 'lib.samp.events'
local encoding = require 'encoding'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local messages = {}
local imguiokno = imgui.ImBool(false)
local sw, sh = getScreenResolution()

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

    sampRegisterChatCommand('lua.j', function()
        imguiokno.v = not imguiokno.v
    end)

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

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

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0

    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.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.CheckMark]              = 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)
    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.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.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    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.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    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.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    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.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
blue()

function hook.onShowDialog(dialogId, style, title, button1, button2, text)
        if dialogId == 235 then
            --[[if text:find('Статус: {......}(.+)') then
                status = text:match('Статус: {......}(%S+)')
                sampAddChatMessage('Status: ' .. status,-1)
            end--]]
            if text:find('Имя: {......}(%S+)') then
                local name = text:match('Имя: {......}(%S+)')
                sampAddChatMessage(name,-1)
            end
        end
end

function hook.onServerMessage(color, text)
    --[[if text:find('%[Таксист%] .+%[%d+%]: .+') then
        name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
        --sampAddChatMessage("{15edc9}" .. name .. '[' ..id .. ']' .. ': ' .. message, 0x15edc9)
        print('\n' .. name .. '[' .. id .. ']' .. ': ' .. message)
        return false
    end--]]
    --[[if text:find('(.+)') then
        message = text:match('(.+)')
        print('\n\n' .. message)
        return false
    end--]]
    if text:find('%[Таксист%] .+%[%d+%]: .+') then
        local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
        table.insert(messages,{
            name = name,
            id = id,
            message = message
        })
        return false
    end
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(300, 150), imgui.Cond.FirstUseEver)

    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

    imgui.Begin('Taxi-Chat', imguiokno, imgui.WindowFlags.NoResize)
    imgui.BeginChild('##chatj', imgui.ImVec2(-1, -1), true)
    local clipper = imgui.ImGuiListClipper(#messages)
    while clipper:Step() do
        for i = clipper.DisplayStart + 1, clipper.DisplayEnd do
            imgui.Text(messages[i])
         end
    end
    imgui.EndChild()
    imgui.End()
end

update:
заметил только потом.
код выше работать не будет, так как ты в хуке onServerMessage в массив messages заносишь еще один массив (получается двумерный массив)
чтобы клиппер нормально показывал сообщения, надо заносить в таблицу уже формированное сообщение, так как clipper это тот же самый цикл for, который просто учитывает высоту строк для imgui

замени часть кода:
Lua:
if text:find('%[Таксист%] .+%[%d+%]: .+') then
    local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
    table.insert(messages,{
        name = name,
        id = id,
        message = message
    })
    return false
end

на
Lua:
if text:find('%[Таксист%] .+%[%d+%]: .+') then
    local name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
    table.insert(messages, string.format("%s [id: %d]: %s", name, id, message))
    return false
end
Спасибо, все хорошо, только в окне не отображаются сообщения игроков:

Lua:
require 'lib.moonloader'

local hook = require 'lib.samp.events'
local encoding = require 'encoding'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local messages = {}
local imguiokno = imgui.ImBool(false)
local sw, sh = getScreenResolution()

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

    sampRegisterChatCommand('lua.j', function()
        imguiokno.v = not imguiokno.v
    end)

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

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

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0

    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.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.CheckMark]              = 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)
    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.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.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    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.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    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.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    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.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
blue()

function hook.onShowDialog(dialogId, style, title, button1, button2, text)
        if dialogId == 235 then
            --[[if text:find('Статус: {......}(.+)') then
                status = text:match('Статус: {......}(%S+)')
                sampAddChatMessage('Status: ' .. status,-1)
            end--]]
            if text:find('Имя: {......}(%S+)') then
                local name = text:match('Имя: {......}(%S+)')
                sampAddChatMessage(name,-1)
            end
        end
end

function hook.onServerMessage(color, text)
    --[[if text:find('%[Таксист%] .+%[%d+%]: .+') then
        name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
        --sampAddChatMessage("{15edc9}" .. name .. '[' ..id .. ']' .. ': ' .. message, 0x15edc9)
        print('\n' .. name .. '[' .. id .. ']' .. ': ' .. message)
        return false
    end--]]
    --[[if text:find('(.+)') then
        message = text:match('(.+)')
        print('\n\n' .. message)
        return false
    end--]]
    if text:find('%[Таксист%] .+%[%d+%]: .+') then
        local name, id, message = text:match('%[Таксист%] (.+)%[(%d+)%]: (.+)')
        table.insert(messages, string.format("%s [%d]: %s", name, id, u8:decode(message)))
    end
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(300, 150), imgui.Cond.FirstUseEver)

    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

    imgui.Begin('Taxi-Chat', imguiokno, imgui.WindowFlags.NoResize)
    imgui.BeginChild('##chatj', imgui.ImVec2(-1, -1), true)
    local clipper = imgui.ImGuiListClipper(#messages)
    while clipper:Step() do
        for i = clipper.DisplayStart + 1, clipper.DisplayEnd do
            imgui.Text(u8:decode(messages[i]))
         end
    end
    imgui.EndChild()
    imgui.End()
end
 

meowprd

Тот самый Котовский
Проверенный
1,283
710
Спасибо, все хорошо, только в окне не отображаются сообщения игроков:

Lua:
require 'lib.moonloader'

local hook = require 'lib.samp.events'
local encoding = require 'encoding'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local messages = {}
local imguiokno = imgui.ImBool(false)
local sw, sh = getScreenResolution()

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

    sampRegisterChatCommand('lua.j', function()
        imguiokno.v = not imguiokno.v
    end)

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

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

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0

    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.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.CheckMark]              = 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)
    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.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.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    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.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    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.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    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.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
blue()

function hook.onShowDialog(dialogId, style, title, button1, button2, text)
        if dialogId == 235 then
            --[[if text:find('Статус: {......}(.+)') then
                status = text:match('Статус: {......}(%S+)')
                sampAddChatMessage('Status: ' .. status,-1)
            end--]]
            if text:find('Имя: {......}(%S+)') then
                local name = text:match('Имя: {......}(%S+)')
                sampAddChatMessage(name,-1)
            end
        end
end

function hook.onServerMessage(color, text)
    --[[if text:find('%[Таксист%] .+%[%d+%]: .+') then
        name, id, message = text:match('(.+)%[(%d+)%]: (.+)')
        --sampAddChatMessage("{15edc9}" .. name .. '[' ..id .. ']' .. ': ' .. message, 0x15edc9)
        print('\n' .. name .. '[' .. id .. ']' .. ': ' .. message)
        return false
    end--]]
    --[[if text:find('(.+)') then
        message = text:match('(.+)')
        print('\n\n' .. message)
        return false
    end--]]
    if text:find('%[Таксист%] .+%[%d+%]: .+') then
        local name, id, message = text:match('%[Таксист%] (.+)%[(%d+)%]: (.+)')
        table.insert(messages, string.format("%s [%d]: %s", name, id, u8:decode(message)))
    end
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(300, 150), imgui.Cond.FirstUseEver)

    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))

    imgui.Begin('Taxi-Chat', imguiokno, imgui.WindowFlags.NoResize)
    imgui.BeginChild('##chatj', imgui.ImVec2(-1, -1), true)
    local clipper = imgui.ImGuiListClipper(#messages)
    while clipper:Step() do
        for i = clipper.DisplayStart + 1, clipper.DisplayEnd do
            imgui.Text(u8:decode(messages[i]))
         end
    end
    imgui.EndChild()
    imgui.End()
end
u8:decode - убери это из imgui.Text и из хука, зачем ты это сделал
в imgui.Text сделай просто imgui.Text(u8(messages)), все.

+ проверяй работает ли у тебя проверка в хуке


update:
imgui.BeginChild('##chatj', imgui.ImVec2(-1, -1), true) замени на imgui.BeginChild('##chaj', imgui.ImVec2(-0.1, 0), true)
 
  • Нравится
Реакции: Sanchez.

barjik

Известный
464
190
Почему не работает notify? В чем проблема?
code:
script_author('barjik')

require 'lib.moonloader'
local keys = require 'vkeys'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
local notify = import 'imgui_notf.lua'

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    
    sampRegisterChatcommand('notify', not_notify)
    
    while true do
        wait(0)
    end
end

function not_notify(arg)
    notify.addNotify("Текст1", "Текст2", 2, 1, 5)
end
 

meowprd

Тот самый Котовский
Проверенный
1,283
710
Почему не работает notify? В чем проблема?
code:
script_author('barjik')

require 'lib.moonloader'
local keys = require 'vkeys'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
local notify = import 'imgui_notf.lua'

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
   
    sampRegisterChatcommand('notify', not_notify)
   
    while true do
        wait(0)
    end
end

function not_notify(arg)
    notify.addNotify("Текст1", "Текст2", 2, 1, 5)
end
скинь сюда imgui_notf.lua
 

meowprd

Тот самый Котовский
Проверенный
1,283
710
Почему не работает notify? В чем проблема?
code:
script_author('barjik')

require 'lib.moonloader'
local keys = require 'vkeys'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
local notify = import 'imgui_notf.lua'

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
   
    sampRegisterChatcommand('notify', not_notify)
   
    while true do
        wait(0)
    end
end

function not_notify(arg)
    notify.addNotify("Текст1", "Текст2", 2, 1, 5)
end
Lua:
addNotification(text, time)

function not_notify(arg)
    notify.addNotification("Текст", 1000)
end
 

Legion13

Участник
42
4
Кто знает?
почему когда я ставлю кодировку в атоме, то у меня в сампе появляются какие-то непонятные символы?
 

barjik

Известный
464
190
Lua:
addNotification(text, time)

function not_notify(arg)
    notify.addNotification("Текст", 1000)
end
Все равно выдает ошибку(
Lua:
script_author('barjik')

require 'lib.moonloader'
local keys = require 'vkeys'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
local notify = import 'lib_imgui_notf.lua'

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
   
    sampRegisterChatcommand('notify', test_notify)
   
    while true do
        wait(0)
    end
end

function not_notify(arg)
    notify.addNotification("Текст", 1000)
end
 

meowprd

Тот самый Котовский
Проверенный
1,283
710
Все равно выдает ошибку(
Lua:
script_author('barjik')

require 'lib.moonloader'
local keys = require 'vkeys'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
local notify = import 'lib_imgui_notf.lua'

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
  
    sampRegisterChatcommand('notify', test_notify)
  
    while true do
        wait(0)
    end
end

function not_notify(arg)
    notify.addNotification("Текст", 1000)
end
какую ошибку именно выдает?
 

#Kai-

Известный
705
291
инглиш в школе вери бэд?

У меня в корочке написано Deutsch и то могу перевести " 'lib_imgui_notf.lua' не найден".