[ML] (error) Monitoring.lua: ...a Games Launcher\bin\arizona\moonloader\lib\encoding.lua:60: assertion failed!
stack traceback:
[C]: in function 'assert'
...a Games Launcher\bin\arizona\moonloader\lib\encoding.lua:60: in function 'u8'
...ona Games Launcher\bin\arizona\moonloader\Monitoring.lua:55: in function 'OnDrawFrame'
...zona Games Launcher\bin\arizona\moonloader\lib\imgui.lua:1378: in function <...zona Games Launcher\bin\arizona\moonloader\lib\imgui.lua:1367>
[ML] (error) Monitoring.lua: Script died due to an error. (0E8EFD74)
lua
local imgui = require'imgui'
local cef = require'lib.CEF Events'
local encoding = require'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local monitoring = {
enabled = false,
paused = false,
filter = '',
packets = {},
max_packets = 200,
auto_scroll = true,
show_window = imgui.ImBool(true),
}
-- Добавление пакета в историю
local function add_packet(direction, data)
if #monitoring.packets >= monitoring.max_packets then table.remove(monitoring.packets, 1) end
table.insert(monitoring.packets, {
time = os.date('%H:%M:%S'),
direction = direction,
size = #data,
data = data,
})
end
-- Колбеки для CEF
cef.addOnDisplayCEFCallback(function(str) if monitoring.enabled and not monitoring.paused then add_packet('IN', str) end end)
cef.addOnSendCEFCallback(function(str) if monitoring.enabled and not monitoring.paused then add_packet('OUT', str) end end)
-- Фильтрация пакетов
local function is_packet_visible(packet)
if monitoring.filter == '' then return true end
return packet.data:lower():find(monitoring.filter:lower(), 1, true) ~= nil
end
-- Копировать в буфер обмена
local function copy_to_clipboard(text)
setClipboardText(text)
end
-- ImGui окно
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
imgui.SetNextWindowSize(imgui.ImVec2(700, 400), imgui.Cond.FirstUseEver)
if imgui.Begin(u8'Мониторинг CEF', monitoring.show_window) then
-- Панель управления
if imgui.Button(monitoring.enabled and u8'Остановить' or u8'Начать мониторинг', imgui.ImVec2(150, 0)) then monitoring.enabled = not monitoring.enabled end
imgui.SameLine()
if imgui.Button(monitoring.paused and u8'Продолжить' or u8'Пауза', imgui.ImVec2(100, 0)) then monitoring.paused = not monitoring.paused end
imgui.SameLine()
if imgui.Button(u8'Очистить', imgui.ImVec2(80, 0)) then monitoring.packets = {} end
imgui.SameLine()
imgui.Checkbox(u8'Автопрокрутка', imgui.ImBool(monitoring.auto_scroll))
imgui.SameLine()
imgui.Text(u8('Всего: %d', #monitoring.packets))
-- Фильтр
imgui.PushItemWidth(200)
local changed, filter = imgui.InputText(u8' Фильтр', monitoring.filter, 128)
if changed then monitoring.filter = filter end
imgui.PopItemWidth()
imgui.Separator()
-- Таблица пакетов
if imgui.BeginChild('packets', imgui.ImVec2(0, -40), true) then
imgui.Columns(5, 'packets_columns', true)
imgui.Text(u8'Время')
imgui.NextColumn()
imgui.Text(u8'Тип')
imgui.NextColumn()
imgui.Text(u8'Размер')
imgui.NextColumn()
imgui.Text(u8'Данные (обрезано)')
imgui.NextColumn()
imgui.Text(u8'Действия')
imgui.NextColumn()
imgui.Separator()
local scroll_to_bottom = false
for i, packet in ipairs(monitoring.packets) do
if is_packet_visible(packet) then
imgui.Text(packet.time)
imgui.NextColumn()
imgui.Text(packet.direction)
imgui.NextColumn()
imgui.Text(tostring(packet.size))
imgui.NextColumn()
local preview = packet.data:gsub('[\r\n]', ' '):sub(1, 80)
imgui.Text(preview)
imgui.NextColumn()
if imgui.SmallButton(u8('Подробнее##' .. i)) then packet.show_details = not packet.show_details end
imgui.SameLine()
if imgui.SmallButton(u8('Копировать##' .. i)) then copy_to_clipboard(packet.data) end
imgui.NextColumn()
if packet.show_details then
imgui.Columns(1)
imgui.TextColored(imgui.ImVec4(0.8, 0.8, 1, 1), u8'Детали пакета:')
imgui.TextWrapped(u8('Время: %s\nТип: %s\nРазмер: %d\nДанные:\n%s', packet.time, packet.direction, packet.size, packet.data))
imgui.Separator()
imgui.Columns(5)
end
if monitoring.auto_scroll then scroll_to_bottom = true end
end
end
imgui.Columns(1)
if scroll_to_bottom then imgui.SetScrollHereY(1.0) end
end
imgui.EndChild()
end
imgui.End()
end
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
if monitoring.show_window.v then
imgui.Process = true -- Всегда включаем процессинг ImGui при открытии окна
end
end
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('cefmon', toggle_monitoring_window)
while true do
wait(0)
end
end
указывает, что в encoding.u8(...) вызвана с аргументом, который не удовлетворяет встроенной проверке assert в библиотеке encoding. Чаще всего такое происходит, когда передаётся либо nil, либо не строка.
Разбор вашего кода и ошибка:
В вашем скрипте u8 — это обёртка над encoding.UTF8, и у вас есть много вызовов вида:
imgui.Button(monitoring.enabled and u8'Остановить' or u8'Начать мониторинг', imgui.ImVec2(150, 0))
и т.п.
Первая проблема — Lua не поддерживает литералы u8'...'. Это синтаксический сахар для строк в некоторых языках (C++20 и др.), но в Lua такое не работает.
Вы должны вызывать u8('строка') как функцию, иначе u8'строка' — это обращение к индексу таблицы или попытка обращения к методу, но u8 — функция, и такой вызов приводит к ошибке.
Эта ошибка синтаксиса (или неправильного вызова функции) приводит к передаче неправильных аргументов в encoding.UTF8, что и вызывает assert с ошибкой.
Обязательно заменить все вызовы u8'...' на u8('...')
В вашем коде нужно сделать во всех местах:
u8'Мониторинг CEF' → u8('Мониторинг CEF')
u8'Остановить' → u8('Остановить')
и т.д.
Например:
lua
User
lua
Assistant
Проблема с тем, что интерфейс не показывается, скорее всего связана с состоянием переменной imgui.Process. В MoonLoader/ImGui обычно есть глобальный флаг imgui.Process (логично, что так вы его используете), который должен быть выставлен в true, чтобы imgui.OnDrawFrame() вызывался и окно отрисовывалось.
Анализ вашей проблемы
Вы включаете imgui.Process = true только в функции toggle_monitoring_window, когда окно открывается, что хорошо.
Но изначально при запуске скрипта imgui.Process может быть равен false.
Если вы вводите /cefmon еще раз и окно закрывается (monitoring.show_window.v = false), то imgui.Process не выключается, что обычно нормально, но если у вас другой код или если imgui.Process где-то сбрасывается, тогда окно не нарисуется при show_window.v == true.
Возможно, окно скрывается или не открывается, потому что monitoring.show_window.v изначально true (что верно), но imgui.Process не выставлен.
Что можно сделать, чтобы исправить и проверить
Гарантировать imgui.Process = true при старте скрипта.
Добавьте в main функцию:
lua
function main()
while not isSampAvailable() do wait(0) end
sampRegisterChatCommand('cefmon', toggle_monitoring_window)
imgui.Process = true -- Включаем ImGui по умолчанию
while true do wait(0) end
end
Попробуйте так, чтобы ImGui обрабатывался всегда, а окно рендерилось по условию.
Правильный вызов toggle_monitoring_window
Вы делаете:
lua
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
if monitoring.show_window.v then
imgui.Process = true -- Всегда включаем процессинг ImGui при открытии окна
end
end
User
Ну вот пример imgui кода:
lua
local imgui = require('imgui')
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local window = imgui.ImBool(false)
function main()
while not isSampAvailable() do wait(200) end
imgui.Process = false
window.v = true --show window on start
while true do
wait(0)
imgui.Process = window.v
end
end
function imgui.OnDrawFrame()
if window.v then
local resX, resY = getScreenResolution()
local sizeX, sizeY = 300, 300 -- WINDOW SIZE
imgui.SetNextWindowPos(imgui.ImVec2(resX / 2 - sizeX / 2, resY / 2 - sizeY / 2), imgui.Cond.FirstUseEver)
imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
imgui.Begin('Window Title', window)
--window code
imgui.End()
end
end
Исправь мой код с парсингом
Assistant
Спасибо за пример рабочего кода! На его основе исправим ваш скрипт для корректного отображения окна с учётом:
правильного вызова u8('строка') вместо u8'строка'
управления imgui.Process = window.v в главном цикле
правильного хранения ImBool в monitoring.auto_scroll
общего улучшения кода, чтобы он работал
Исправленный и рабочий вариант:
lua
User
Почему тут пустой if:
lua
if imgui.Checkbox(u8('Автопрокрутка'), monitoring.auto_scroll) then
-- monitoring.auto_scroll.v уже изменился
end
Assistant
Отличный вопрос!
Почему if imgui.Checkbox(...) then ... end может быть пустым?
В MoonLoader ImGui Lua-обертке функция imgui.Checkbox(label, imbool)возвращает true, если состояние чекбокса изменилось (то есть пользователь переключил галочку), иначе false.
lua
local changed = imgui.Checkbox(label, imbool)
Соответственно:
Если changed == true, значит пользователь кликнул и состояние imbool.v изменилось.
Если changed == false, значит состояние не трогали.
В вашем коде:
lua
if imgui.Checkbox(u8('Автопрокрутка'), monitoring.auto_scroll) then
-- monitoring.auto_scroll.v уже изменился
end
Вы проверяете, изменилось ли состояние чекбокса. Если изменилось, то внутри if мог бы быть код для реагирования на изменение, например логика, сохранение настроек, запуск каких-то действий и т.п.
Почему в примере тело if пустое?
Потому что:
Сейчас скрипт просто принимает изменение состояния monitoring.auto_scroll.v (которое модифицируется автоматически внутри Checkbox).
Дополнительные действия при изменении не нужны, либо их планируют добавить позже.
Комментарий внутри if напоминает, что переменная уже обновлена в момент захода внутрь.
Это стандартная практика: поставить if для отслеживания изменения, а внутри добавить логику, если потребуется.
и в дальнейшем добавить реакцию, если потребуется.
User
[ML] (error) Monitoring.lua: ...ona Games Launcher\bin\arizona\moonloader\Monitoring.lua:64: stack index 2, expected userdata, received string: value is not a valid userdata (bad argument into 'bool(const char*, ImBuffer*, sol::optional, sol::optional<ImCallback *>)')
stack traceback:
[C]: in function 'InputText'
...ona Games Launcher\bin\arizona\moonloader\Monitoring.lua:64: in function 'OnDrawFrame'
...zona Games Launcher\bin\arizona\moonloader\lib\imgui.lua:1378: in function <...zona Games Launcher\bin\arizona\moonloader\lib\imgui.lua:1367>
[ML] (error) Monitoring.lua: Script died due to an error. (4CB308FC)
Assistant
Ошибка указывает на проблему в вызове imgui.InputText:
code
stack index 2, expected userdata, received string: value is not a valid userdata (bad argument into 'bool(const char*, ImBuffer*, sol::optional<int>, sol::optional<ImCallback *>)')
Это значит, что функция InputText в ImGui Lua-обертке ожидает на втором аргументе не обычную строку, а userdata, обычно это объект ImBuffer или аналог. В текущем вашем коде вы передаёте туда Lua-строку, что и вызывает ошибку.
В чем суть проблемы?
imgui.InputText в MoonLoader (lua-binding imgui) устроена немного по-другому по сравнению с Lua-имплементациями ImGui.
Второй аргумент — должен быть объект типа ImBuffer, который управляет буфером текста для редактирования.
При вызове InputText вы должны передать именно этот объект, а не стандартную строку.
Как это исправить?
1. Создайте поле ImBuffer для поля фильтра
В вашем скрипте:
lua
local monitoring = {
...
filter = '',
filter_buffer = imgui.ImBuffer(128), -- размер буфера 128 символов
...
}
Вместо использования plain string monitoring.filter для редактирования — используйте monitoring.filter_buffer.
2. Синхронизируйте значения filter и filter_buffer
При инициализации можно установить буфер из строки:
lua
monitoring.filter_buffer._data = monitoring.filter -- если доступно
После вызова InputText обновляйте строку monitoring.filter из буфера.
3. Вызов InputText с ImBuffer:
Замените строку
lua
local changed, filter = imgui.InputText(u8(' Фильтр'), monitoring.filter, 128)
if changed then monitoring.filter = filter end
User
lua
Assistant
Спасибо за подробный код! Давайте разберёмся с ошибками, которые могут появляться при запуске.
Основные предположительные причины ошибок
1) Неправильное использование imgui.InputText
Из вашего примера видно, что поле фильтра создается как monitoring.filter = imgui.ImBuffer(128), а затем используется так:
lua
imgui.InputText(u8(' Данные'), monitoring.filter)
Это правильно. Однако проблемы могут возникать если свойство фильтра затем пытается использоваться как строка, например здесь:
lua
local data_ok = monitoring.filter.v == '' or packet.data:lower():find(monitoring.filter.v:lower(), 1, true) ~= nil
Проблема:imgui.ImBuffer не имеет поля .v, у него поле .data с типом строка.
Исправление: заменить все monitoring.filter.v на monitoring.filter.data. Например:
lua
local data_ok = monitoring.filter.data == '' or packet.data:lower():find(monitoring.filter.data:lower(), 1, true) ~= nil
2) Некорректно используемые цвета для imgui.PushStyleColor
if imgui.Button(monitoring.enabled and u8('Остановить') or u8('Начать мониторинг'), imgui.ImVec2(150, 0)) then ...
Дополнительные замечания:
Функция imgui.InputText использует фильтр monitoring.filter, который является строкой. В исходном MoonLoader InputText для текста с изменением возвращает булево и новую строку, но в вашем коде вы пишете:
lua
local changed, filter = imgui.InputText(u8(' Фильтр'), monitoring.filter, 128)
if changed then monitoring.filter = filter end
Это выглядит правильно, если InputText возвращает (bool, string).
Здесь вы создаёте новый ImBool на каждый вызов. Лучше создать один ImBool для monitoring.auto_scroll и привязывать его.
Итоговое исправление (пример первых строк окна):
lua
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
imgui.SetNextWindowSize(imgui.ImVec2(700, 400), imgui.Cond.FirstUseEver)
if imgui.Begin(u8('Мониторинг CEF'), monitoring.show_window) then
if imgui.Button(monitoring.enabled and u8('Остановить') or u8('Начать мониторинг'), imgui.ImVec2(150, 0)) then
monitoring.enabled = not monitoring.enabled
end
imgui.SameLine()
if imgui.Button(monitoring.paused and u8('Продолжить') or u8('Пауза'), imgui.ImVec2(100, 0)) then
monitoring.paused = not monitoring.paused
end
-- и так далее
Резюме
Ошибка вызвана использованием неверного синтаксиса:
lua
u8'строка'
нужно заменить на
lua
u8('строка')
Обязательно проверьте весь скрипт и исправьте все подобные вызовы.
Если останутся вопросы — пишите.
local imgui = require'imgui'
local cef = require'lib.CEF Events'
local encoding = require'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local monitoring = {
enabled = false,
paused = false,
filter = '',
packets = {},
max_packets = 200,
auto_scroll = true,
show_window = imgui.ImBool(true),
}
-- Добавление пакета в историю
local function add_packet(direction, data)
if #monitoring.packets >= monitoring.max_packets then table.remove(monitoring.packets, 1) end
table.insert(monitoring.packets, {
time = os.date('%H:%M:%S'),
direction = direction,
size = #data,
data = data,
})
end
-- Колбеки для CEF
cef.addOnDisplayCEFCallback(function(str) if monitoring.enabled and not monitoring.paused then add_packet('IN', str) end end)
cef.addOnSendCEFCallback(function(str) if monitoring.enabled and not monitoring.paused then add_packet('OUT', str) end end)
-- Фильтрация пакетов
local function is_packet_visible(packet)
if monitoring.filter == '' then return true end
return packet.data:lower():find(monitoring.filter:lower(), 1, true) ~= nil
end
-- Копировать в буфер обмена
local function copy_to_clipboard(text)
setClipboardText(text)
end
-- ImGui окно
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
imgui.SetNextWindowSize(imgui.ImVec2(700, 400), imgui.Cond.FirstUseEver)
if imgui.Begin(u8'Мониторинг CEF', monitoring.show_window) then
-- Панель управления
if imgui.Button(monitoring.enabled and u8('Остановить') or u8('Начать мониторинг'), imgui.ImVec2(150, 0)) then monitoring.enabled = not monitoring.enabled end
imgui.SameLine()
if imgui.Button(monitoring.paused and u8('Продолжить') or u8('Пауза'), imgui.ImVec2(100, 0)) then monitoring.paused = not monitoring.paused end
imgui.SameLine()
if imgui.Button(u8'Очистить', imgui.ImVec2(80, 0)) then monitoring.packets = {} end
imgui.SameLine()
imgui.Checkbox(u8'Автопрокрутка', imgui.ImBool(monitoring.auto_scroll))
imgui.SameLine()
imgui.Text(u8('Всего: %d', #monitoring.packets))
-- Фильтр
imgui.PushItemWidth(200)
local changed, filter = imgui.InputText(u8' Фильтр', monitoring.filter, 128)
if changed then monitoring.filter = filter end
imgui.PopItemWidth()
imgui.Separator()
-- Таблица пакетов
if imgui.BeginChild('packets', imgui.ImVec2(0, -40), true) then
imgui.Columns(5, 'packets_columns', true)
imgui.Text(u8'Время')
imgui.NextColumn()
imgui.Text(u8'Тип')
imgui.NextColumn()
imgui.Text(u8'Размер')
imgui.NextColumn()
imgui.Text(u8'Данные (обрезано)')
imgui.NextColumn()
imgui.Text(u8'Действия')
imgui.NextColumn()
imgui.Separator()
local scroll_to_bottom = false
for i, packet in ipairs(monitoring.packets) do
if is_packet_visible(packet) then
imgui.Text(packet.time)
imgui.NextColumn()
imgui.Text(packet.direction)
imgui.NextColumn()
imgui.Text(tostring(packet.size))
imgui.NextColumn()
local preview = packet.data:gsub('[\r\n]', ' '):sub(1, 80)
imgui.Text(preview)
imgui.NextColumn()
if imgui.SmallButton(u8('Подробнее##' .. i)) then packet.show_details = not packet.show_details end
imgui.SameLine()
if imgui.SmallButton(u8('Копировать##' .. i)) then copy_to_clipboard(packet.data) end
imgui.NextColumn()
if packet.show_details then
imgui.Columns(1)
imgui.TextColored(imgui.ImVec4(0.8, 0.8, 1, 1), u8'Детали пакета:')
imgui.TextWrapped(u8('Время: %s\nТип: %s\nРазмер: %d\nДанные:\n%s', packet.time, packet.direction, packet.size, packet.data))
imgui.Separator()
imgui.Columns(5)
end
if monitoring.auto_scroll then scroll_to_bottom = true end
end
end
imgui.Columns(1)
if scroll_to_bottom then imgui.SetScrollHereY(1.0) end
end
imgui.EndChild()
end
imgui.End()
end
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
if monitoring.show_window.v then
imgui.Process = true -- Всегда включаем процессинг ImGui при открытии окна
end
end
function main()
while not isSampAvailable() do
wait(0)
end
sampRegisterChatCommand('cefmon', toggle_monitoring_window)
while true do
wait(0)
end
end
Интерфейс не видно когда ввожу команду
Если окно закрывается, imgui.Process остаётся true, что нормально. Но если хочется, можно делать так:
lua
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
imgui.Process = monitoring.show_window.v
end
Чтобы выключать процессинг, когда окно закрыто.
Напишите в imgui.OnDrawFrame отладочную информацию
Добавьте в начало:
lua
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
-- Для отладки
-- print("OnDrawFrame called, show_window.v == true")
...
Проверьте, вызывается ли эта функция. Если нет, значит, проблема с imgui.Process.
Так же везде, где u8'строка' — заменить на u8('строка').
Если это не исправить, при вызове imgui.Begin произойдет ошибка и окно не отрисуется.
Итог
Исправьте все вызовы u8'строка' → u8('строка').
Задайте imgui.Process = true в начале main.
Управляйте видимостью окна и imgui.Process вместе или заставьте imgui.Process всегда быть true, если хотите постоянно обрабатывать ImGui.
Добавьте отладочное сообщение, чтобы убедиться, что imgui.OnDrawFrame вызывается.
Пример исправленного кода начала imgui.OnDrawFrame и main:
lua
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
imgui.SetNextWindowSize(imgui.ImVec2(700, 400), imgui.Cond.FirstUseEver)
if imgui.Begin(u8('Мониторинг CEF'), monitoring.show_window) then
-- Весь ваш интерфейс тут
end
imgui.End()
end
function main()
while not isSampAvailable() do wait(0) end
sampRegisterChatCommand('cefmon', toggle_monitoring_window)
imgui.Process = true -- Включаем ImGui отрисовку
while true do wait(0) end
end
Если хотите, чтобы ImGui процессинг включался/выключался вместе с окном:
lua
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
imgui.Process = monitoring.show_window.v
end
Если после этих изменений окно так и не отображается — напишите, какие ошибки выдает MoonLoader, или добавьте отладочный вывод вида print("tick") внутри imgui.OnDrawFrame.
local imgui = require 'imgui'
local cef = require 'lib.CEF Events'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local monitoring = {
enabled = false,
paused = false,
filter = '',
packets = {},
max_packets = 200,
auto_scroll = imgui.ImBool(true), -- ImBool для чекбокса
show_window = imgui.ImBool(true),
}
-- Добавление пакета в историю
local function add_packet(direction, data)
if #monitoring.packets >= monitoring.max_packets then
table.remove(monitoring.packets, 1)
end
table.insert(monitoring.packets, {
time = os.date('%H:%M:%S'),
direction = direction,
size = #data,
data = data,
show_details = false,
})
end
-- Колбеки для CEF
cef.addOnDisplayCEFCallback(function(str)
if monitoring.enabled and not monitoring.paused then
add_packet('IN', str)
end
end)
cef.addOnSendCEFCallback(function(str)
if monitoring.enabled and not monitoring.paused then
add_packet('OUT', str)
end
end)
-- Фильтрация пакетов
local function is_packet_visible(packet)
if monitoring.filter == '' then return true end
return packet.data:lower():find(monitoring.filter:lower(), 1, true) ~= nil
end
-- Копировать в буфер обмена
local function copy_to_clipboard(text)
setClipboardText(text)
end
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
local resX, resY = getScreenResolution()
local sizeX, sizeY = 700, 400
imgui.SetNextWindowPos(imgui.ImVec2(resX/2 - sizeX/2, resY/2 - sizeY/2), imgui.Cond.FirstUseEver)
imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
if imgui.Begin(u8('Мониторинг CEF'), monitoring.show_window) then
-- Панель управления
if imgui.Button(monitoring.enabled and u8('Остановить') or u8('Начать мониторинг'), imgui.ImVec2(150, 0)) then
monitoring.enabled = not monitoring.enabled
end
imgui.SameLine()
if imgui.Button(monitoring.paused and u8('Продолжить') or u8('Пауза'), imgui.ImVec2(100, 0)) then
monitoring.paused = not monitoring.paused
end
imgui.SameLine()
if imgui.Button(u8('Очистить'), imgui.ImVec2(80, 0)) then
monitoring.packets = {}
end
imgui.SameLine()
if imgui.Checkbox(u8('Автопрокрутка'), monitoring.auto_scroll) then
-- monitoring.auto_scroll.v уже изменился
end
imgui.SameLine()
imgui.Text(u8(string.format('Всего: %d', #monitoring.packets)))
-- Фильтр
imgui.PushItemWidth(200)
local changed, filter = imgui.InputText(u8(' Фильтр'), monitoring.filter, 128)
if changed then monitoring.filter = filter end
imgui.PopItemWidth()
imgui.Separator()
-- Таблица пакетов
if imgui.BeginChild('packets', imgui.ImVec2(0, -40), true) then
imgui.Columns(5, 'packets_columns', true)
imgui.Text(u8('Время')); imgui.NextColumn()
imgui.Text(u8('Тип')); imgui.NextColumn()
imgui.Text(u8('Размер')); imgui.NextColumn()
imgui.Text(u8('Данные (обрезано)')); imgui.NextColumn()
imgui.Text(u8('Действия')); imgui.NextColumn()
imgui.Separator()
local scroll_to_bottom = false
for i, packet in ipairs(monitoring.packets) do
if is_packet_visible(packet) then
imgui.Text(packet.time); imgui.NextColumn()
imgui.Text(packet.direction); imgui.NextColumn()
imgui.Text(tostring(packet.size)); imgui.NextColumn()
local preview = packet.data:gsub('[\r\n]', ' '):sub(1, 80)
imgui.Text(preview); imgui.NextColumn()
if imgui.SmallButton(u8('Подробнее##' .. i)) then
packet.show_details = not packet.show_details
end
imgui.SameLine()
if imgui.SmallButton(u8('Копировать##' .. i)) then
copy_to_clipboard(packet.data)
end
imgui.NextColumn()
if packet.show_details then
imgui.Columns(1)
imgui.TextColored(imgui.ImVec4(0.8, 0.8, 1, 1), u8('Детали пакета:'))
imgui.TextWrapped(u8(string.format(
'Время: %s\nТип: %s\nРазмер: %d\nДанные:\n%s',
packet.time,
packet.direction,
packet.size,
packet.data
)))
imgui.Separator()
imgui.Columns(5)
end
if monitoring.auto_scroll.v then
scroll_to_bottom = true
end
end
end
imgui.Columns(1)
if scroll_to_bottom then
imgui.SetScrollHereY(1.0)
end
imgui.EndChild()
end
imgui.End()
end
end
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
end
function main()
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('cefmon', toggle_monitoring_window)
-- Управляем обработкой imgui по состоянию окна:
while true do
wait(0)
imgui.Process = monitoring.show_window.v
end
end
Ключевые моменты исправления:
Везде вызовы u8 через круглые скобки u8('текст').
auto_scroll теперь imgui.ImBool(true), передаётся в Checkbox по ссылке.
В функции main() в бесконечном цикле выставляется imgui.Process = monitoring.show_window.v — это позволит ImGui работать когда окно открыто.
Запрос на setClipboardText реализован через встроенную в MoonLoader функцию.
Немного улучшена читаемость.
Если encoding.UTF8 работает не с string.format напрямую (т.е. не форматирует строку), то можно заменить:
Если проблемы сохранятся — дайте знать, с какими именно, я помогу поправить!
на
lua
local changed = imgui.InputText(u8(' Фильтр'), monitoring.filter_buffer)
if changed then
monitoring.filter = monitoring.filter_buffer.data
end
Где .data — это поле с содержимым буфера.
Полный пример для вашей части с фильтром:
lua
local monitoring = {
...
filter = '',
filter_buffer = imgui.ImBuffer(128),
...
}
function imgui.OnDrawFrame()
...
imgui.PushItemWidth(200)
local changed = imgui.InputText(u8(' Фильтр'), monitoring.filter_buffer)
if changed then
monitoring.filter = monitoring.filter_buffer.data
end
imgui.PopItemWidth()
...
end
Почему так?
imgui.InputText на уровне C++ библиотек работает с указателем на буфер текста (char* или ImBuffer). Lua binding в MoonLoader сделан с использованием специальных userdata объектов буфера, на которые он ссылается. Поэтому нельзя напрямую подставлять обычную Lua-строку, надо оборачивать её в ImBuffer.
Как проверить?
Посмотрите примеры с imgui.InputText для MoonLoader.
Ваше исправление с ImBuffer должно снять ошибку.
Если нужна помощь с базовой инициализацией ImBuffer из строки и обратно — напишите, помогу с этим тоже!
local imgui = require'imgui'
local cef = require'lib.CEF Events'
local encoding = require'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local monitoring = {
enabled = false,
filter = imgui.ImBuffer(128),
filter_type = imgui.ImInt(0), -- 0: все, 1: IN, 2: OUT
filter_size_min = imgui.ImInt(0),
filter_size_max = imgui.ImInt(0),
packets = {},
max_packets = 200,
auto_scroll = imgui.ImBool(true),
show_window = imgui.ImBool(true),
expand_all = imgui.ImBool(false),
}
local function add_packet(direction, data)
if #monitoring.packets >= monitoring.max_packets then table.remove(monitoring.packets, 1) end
table.insert(monitoring.packets, {
time = os.date('%H:%M:%S'),
direction = direction,
size = #data,
data = data,
show_details = false,
})
end
cef.addOnDisplayCEFCallback(function(str) if monitoring.enabled then add_packet('IN', str) end end)
cef.addOnSendCEFCallback(function(str) if monitoring.enabled then add_packet('OUT', str) end end)
local function is_packet_visible(packet)
local type_ok = monitoring.filter_type.v == 0 or (monitoring.filter_type.v == 1 and packet.direction == 'IN') or (monitoring.filter_type.v == 2 and packet.direction == 'OUT')
local size_ok = (monitoring.filter_size_min.v == 0 or packet.size >= monitoring.filter_size_min.v) and (monitoring.filter_size_max.v == 0 or packet.size <= monitoring.filter_size_max.v)
local data_ok = monitoring.filter.v == '' or packet.data:lower():find(monitoring.filter.v:lower(), 1, true) ~= nil
return type_ok and size_ok and data_ok
end
local function copy_to_clipboard(text)
setClipboardText(text)
end
local function export_packets_to_file(filename, only_visible, as_json)
local file = io.open(filename, 'w')
if not file then return false end
local list = only_visible and {} or monitoring.packets
if only_visible then
for _, p in ipairs(monitoring.packets) do
if is_packet_visible(p) then table.insert(list, p) end
end
end
if as_json then
file:write(encodeJson(list))
else
for _, p in ipairs(list) do
file:write(string.format('[%s] %s (%d): %s\n', p.time, p.direction, p.size, p.data:gsub('[\r\n]', ' ')))
end
end
file:close()
return true
end
local function copy_visible_packets()
local buf = {}
for _, p in ipairs(monitoring.packets) do
if is_packet_visible(p) then
table.insert(buf, string.format('[%s] %s (%d): %s', p.time, p.direction, p.size, p.data:gsub('[\r\n]', ' ')))
end
end
setClipboardText(table.concat(buf, '\n'))
end
local function clear_visible_packets()
local new = {}
for _, p in ipairs(monitoring.packets) do
if not is_packet_visible(p) then table.insert(new, p) end
end
monitoring.packets = new
end
local function reset_filters()
monitoring.filter_type.v = 0
monitoring.filter_size_min.v = 0
monitoring.filter_size_max.v = 0
monitoring.filter.v = ''
end
local function get_stats()
local in_count, out_count, total, min, max, sum = 0, 0, 0, math.huge, 0, 0
for _, p in ipairs(monitoring.packets) do
if is_packet_visible(p) then
total = total + 1
sum = sum + p.size
if p.size < min then min = p.size end
if p.size > max then max = p.size end
if p.direction == 'IN' then in_count = in_count + 1 end
if p.direction == 'OUT' then out_count = out_count + 1 end
end
end
return in_count, out_count, total, (total > 0 and math.floor(sum / total) or 0), (min == math.huge and 0 or min), max
end
function imgui.OnDrawFrame()
if not monitoring.show_window.v then return end
local resX, resY = getScreenResolution()
local sizeX, sizeY = 800, 500
imgui.SetNextWindowPos(imgui.ImVec2(resX / 2 - sizeX / 2, resY / 2 - sizeY / 2), imgui.Cond.FirstUseEver)
imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
imgui.PushStyleVar(imgui.StyleVar.WindowRounding, 8)
imgui.PushStyleColor(imgui.Col.TitleBgActive, 0xFF3A6EA5)
imgui.PushStyleColor(imgui.Col.TitleBg, 0xFF2B4C6F)
imgui.PushStyleColor(imgui.Col.WindowBg, 0xFF1B232A)
if imgui.Begin(u8('🌐 Мониторинг CEF'), monitoring.show_window, imgui.WindowFlags.NoCollapse) then
-- Панель управления
imgui.PushStyleVar(imgui.StyleVar.FrameRounding, 6)
if imgui.Button(monitoring.enabled and u8('■ Остановить') or u8('▶ Начать мониторинг'), imgui.ImVec2(180, 0)) then monitoring.enabled = not monitoring.enabled end
imgui.SameLine()
if imgui.Button(u8('🧹 Очистить всё'), imgui.ImVec2(120, 0)) then monitoring.packets = {} end
imgui.SameLine()
if imgui.Button(u8('🧹 Очистить видимые'), imgui.ImVec2(140, 0)) then clear_visible_packets() end
imgui.SameLine()
if imgui.Button(u8('⭳ Копировать видимые'), imgui.ImVec2(170, 0)) then copy_visible_packets() end
imgui.SameLine()
if imgui.Button(u8('💾 Экспорт TXT'), imgui.ImVec2(120, 0)) then export_packets_to_file('cef_packets.txt', true, false) end
imgui.SameLine()
if imgui.Button(u8('💾 Экспорт JSON'), imgui.ImVec2(130, 0)) then export_packets_to_file('cef_packets.json', true, true) end
imgui.SameLine()
if imgui.Button(u8('🔄 Сбросить фильтры'), imgui.ImVec2(150, 0)) then reset_filters() end
imgui.PopStyleVar()
imgui.Separator()
-- Фильтры
imgui.Text(u8('Фильтр по:'))
imgui.SameLine()
imgui.Combo(u8('Тип'), monitoring.filter_type, {u8('Все'), u8('IN'), u8('OUT')}, 3)
imgui.SameLine()
imgui.PushItemWidth(80)
imgui.InputInt(u8('Мин. размер'), monitoring.filter_size_min)
imgui.SameLine()
imgui.InputInt(u8('Макс. размер'), monitoring.filter_size_max)
imgui.PopItemWidth()
imgui.SameLine()
imgui.PushItemWidth(200)
imgui.InputText(u8(' Данные'), monitoring.filter)
imgui.PopItemWidth()
imgui.SameLine()
if imgui.Button(u8('⭳ Вниз')) then monitoring.auto_scroll.v = true end
imgui.SameLine()
if imgui.Button(u8('⭱ Вверх')) then imgui.SetScrollHere(0.0) end
imgui.SameLine()
if imgui.Button(monitoring.expand_all.v and u8('⯆ Свернуть все') or u8('⯈ Развернуть все')) then
monitoring.expand_all.v = not monitoring.expand_all.v
for _, p in ipairs(monitoring.packets) do p.show_details = monitoring.expand_all.v end
end
imgui.Separator()
-- Статистика
local in_count, out_count, total, avg, min, max = get_stats()
imgui.Text(u8(string.format('Всего: %d | IN: %d | OUT: %d | Средний размер: %d | Мин: %d | Макс: %d', total, in_count, out_count, avg, min, max)))
imgui.Separator()
-- Таблица пакетов
if imgui.BeginChild('packets', imgui.ImVec2(0, -40), true) then
imgui.Columns(5, 'packets_columns', true)
imgui.TextColored(imgui.ImVec4(1,1,0.6,1), u8('Время'))
imgui.NextColumn()
imgui.TextColored(imgui.ImVec4(1,1,0.6,1), u8('Тип'))
imgui.NextColumn()
imgui.TextColored(imgui.ImVec4(1,1,0.6,1), u8('Размер'))
imgui.NextColumn()
imgui.TextColored(imgui.ImVec4(1,1,0.6,1), u8('Данные (обрезано)'))
imgui.NextColumn()
imgui.TextColored(imgui.ImVec4(1,1,0.6,1), u8('Действия'))
imgui.NextColumn()
imgui.Separator()
local scroll_to_bottom = false
for i, packet in ipairs(monitoring.packets) do
if is_packet_visible(packet) then
if packet.direction == 'IN' then
imgui.PushStyleColor(imgui.Col.Text, 0xFFB0FFB0)
else
imgui.PushStyleColor(imgui.Col.Text, 0xFFFFB0B0)
end
imgui.Text(packet.time)
imgui.PopStyleColor()
imgui.NextColumn()
imgui.Text(packet.direction)
imgui.NextColumn()
imgui.Text(tostring(packet.size))
imgui.NextColumn()
local preview = packet.data:gsub('[\r\n]', ' '):sub(1, 80)
imgui.Text(preview)
imgui.NextColumn()
if imgui.SmallButton(u8('🔍 Подробнее##' .. i)) then packet.show_details = not packet.show_details end
imgui.SameLine()
if imgui.SmallButton(u8('📋 Копировать##' .. i)) then copy_to_clipboard(packet.data) end
imgui.NextColumn()
if packet.show_details then
imgui.Columns(1)
imgui.TextColored(imgui.ImVec4(0.8, 0.8, 1, 1), u8('Детали пакета:'))
imgui.TextWrapped(u8(string.format('Время: %s\nТип: %s\nРазмер: %d\nДанные:\n%s', packet.time, packet.direction, packet.size, packet.data)))
imgui.Separator()
imgui.Columns(5)
end
if monitoring.auto_scroll.v then scroll_to_bottom = true end
end
end
imgui.Columns(1)
if scroll_to_bottom then imgui.SetScrollHere() end
imgui.EndChild()
end
imgui.PopStyleColor(3)
imgui.PopStyleVar()
imgui.End()
end
imgui.PopStyleColor(3)
imgui.PopStyleVar()
end
function toggle_monitoring_window()
monitoring.show_window.v = not monitoring.show_window.v
end
function main()
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('cefmon', toggle_monitoring_window)
while true do
wait(0)
imgui.Process = monitoring.show_window.v
end
end
u8 — это функция, конвертирующая строку из CP1251 в UTF8.
Lua string.format возвращает строку, которая передается в u8, что корректно.
Но если использовать u8('Строка') .. tostring(...) — опасайтесь, что u8 нужно использовать только для строк.
4) Вызов imgui.PopStyleColor и PopStyleVar
В конце imgui.OnDrawFrame вызывается:
lua
imgui.PopStyleColor(3)
imgui.PopStyleVar()
а также после imgui.End()
Если до imgui.End() уже вызвали PopStyleColor(3) и PopStyleVar(), то повторные вызовы после End() — ошибка: так можно "перепопать" стиль, где счетчик стиля уже к нулю.
5) Управление imgui.Process
У вас корректно стоит:
lua
imgui.Process = monitoring.show_window.v
Конкретные корректировки для вашего кода
Исправьте в is_packet_visible:
lua
local data_ok = monitoring.filter.data == '' or packet.data:lower():find(monitoring.filter.data:lower(), 1, true) ~= nil
Если хотите использовать 32-бит цвет (например 0xFF3A6EA5), MoonLoader может не поддерживать, или поддерживать не так.
Проверьте вызовы PopStyleColor / PopStyleVar
Перед imgui.End():
lua
imgui.PopStyleColor(3)
imgui.PopStyleVar()
И после imgui.End() уже не вызывайте PopStyleColor и PopStyleVar, то есть удалите
lua
imgui.PopStyleColor(3)
imgui.PopStyleVar()
на самом конце функции.
Полезное — добавьте отладочный вывод
В начале OnDrawFrame вставьте:
lua
if not monitoring.show_window.v then
return
end
print("OnDrawFrame running, packets count:", #monitoring.packets)
чтобы убедиться, что функция вызывается.
Пример исправленных фрагментов кода:
lua
local function is_packet_visible(packet)
local type_ok = monitoring.filter_type.v == 0 or
(monitoring.filter_type.v == 1 and packet.direction == 'IN') or
(monitoring.filter_type.v == 2 and packet.direction == 'OUT')
local size_ok = (monitoring.filter_size_min.v == 0 or packet.size >= monitoring.filter_size_min.v) and
(monitoring.filter_size_max.v == 0 or packet.size <= monitoring.filter_size_max.v)
local data_ok = monitoring.filter.data == '' or
packet.data:lower():find(monitoring.filter.data:lower(), 1, true) ~= nil
return type_ok and size_ok and data_ok
end
-- После всего интерфейса перед End():
imgui.PopStyleColor(3)
imgui.PopStyleVar()
imgui.End()
-- Уберите вызовы PopStyleColor и PopStyleVar после End()
Заключение
Ошибки скорее всего вызывают:
Неправильное обращение к .v или .data в буферах и переменных ImGui
Неподдерживаемый формат цвета в PushStyleColor
Лишние вызовы PopStyleColor/PopStyleVar
Поправьте их — ошибки исчезнут и окно отобразится корректно.
Если будет нужна помощь с конкретными ошибками, выведенными MoonLoader, покажите текст и я помогу подробно.