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

Dmitriy Makarov

25.05.2021
Проверенный
2,508
1,136
Я немного запутался..
Вот у меня массив
Lua:
local vla = {
    'Aztec',
    'Aztecas',
    'VLA',
    'vla',
    'aztec',
    'aztecas',
    'ацтек',
    'азтек',
    'Ацтек',
    'Азтек',
}

local lsv = {
    'Vagos',
    'vagos',
    'LSV',
    'lsv',
    'Вагос',
    'вагос',
}

local grovestreet = {
    'Grove',
    'grove',
    'Грув',
    'грув',
}

local therifa = {
    'Rifa',
    'rifa',
    'Рифа',
    'рифа',
}

local theballas = {
    'Ballas',
    'ballas',
    'Баллас',
    'баллас',
}
Хочу сделать проверку, когда варнят чела с причиной в конце с одним из этих слов, то прибавлять + 1
Как мне хукать текст и находить через elseif?
Lua:
function sampev.onServerMessage(color, text)
    lua_thread.create(function()
        for i = 1, #vla do
            if text:find(vla[i]) then
                wait(10)
                vagos = vagos + 1
            end
        end
        -- ...
 

skarzer999

Известный
24
2
Есть диалог 100001,но когда в нем выбираю 1 пункт то он не открывает диалог 100003,подскажите в чем проблема?
И как в будущем сделать так что бы после выбора в диалоге 100003 открывался следующий диалог или сразу отправлялась команда в чат через sampSendChat,заранее благодарен.

Lua:
function dialog()
    sampShowDialog(100001, tag.. ' {ffffff}' ..playername.. ' | Меню взаимодействия',fmhelperList,'Выбрать','Закрыть',2)
    lua_thread.create(cheker)
end

function cheker()
    while sampIsDialogActive() do
        wait(0)
        local result,button,list,input = sampHasDialogRespond(100001)
        if result and list == 0 then
            sampShowDialog(100003, tag.. ' {ffffff}' ..playername.. ' | Передача денег',moneymenu,'Выбрать','Закрыть',2)
        elseif result and list == 1 then
            sampSendChat('/test')
        elseif result and list == 2 then
            sampSendChat('/test')
        elseif result and list == 3 then
            sampSendChat('/test')
        elseif result and list == 4 then
            sampSendChat('/test')
        elseif result and list == 5 then
            sampSendChat('/test')
        end
    end
end
 

astynk

Известный
Проверенный
741
533
Есть диалог 100001,но когда в нем выбираю 1 пункт то он не открывает диалог 100003,подскажите в чем проблема?
И как в будущем сделать так что бы после выбора в диалоге 100003 открывался следующий диалог или сразу отправлялась команда в чат через sampSendChat,заранее благодарен.

Lua:
function dialog()
    sampShowDialog(100001, tag.. ' {ffffff}' ..playername.. ' | Меню взаимодействия',fmhelperList,'Выбрать','Закрыть',2)
    lua_thread.create(cheker)
end

function cheker()
    while sampIsDialogActive() do
        wait(0)
        local result,button,list,input = sampHasDialogRespond(100001)
        if result and list == 0 then
            sampShowDialog(100003, tag.. ' {ffffff}' ..playername.. ' | Передача денег',moneymenu,'Выбрать','Закрыть',2)
        elseif result and list == 1 then
            sampSendChat('/test')
        elseif result and list == 2 then
            sampSendChat('/test')
        elseif result and list == 3 then
            sampSendChat('/test')
        elseif result and list == 4 then
            sampSendChat('/test')
        elseif result and list == 5 then
            sampSendChat('/test')
        end
    end
end

У диалога не может быть ID больше 32768
 

Fott

Простреленный
3,470
2,388
Как сделать чтобы при помощи print выводился абсолютно весь чат?
 

Dmitriy Makarov

25.05.2021
Проверенный
2,508
1,136
Есть диалог 100001,но когда в нем выбираю 1 пункт то он не открывает диалог 100003,подскажите в чем проблема?
И как в будущем сделать так что бы после выбора в диалоге 100003 открывался следующий диалог или сразу отправлялась команда в чат через sampSendChat,заранее благодарен.

Lua:
function dialog()
    sampShowDialog(100001, tag.. ' {ffffff}' ..playername.. ' | Меню взаимодействия',fmhelperList,'Выбрать','Закрыть',2)
    lua_thread.create(cheker)
end

function cheker()
    while sampIsDialogActive() do
        wait(0)
        local result,button,list,input = sampHasDialogRespond(100001)
        if result and list == 0 then
            sampShowDialog(100003, tag.. ' {ffffff}' ..playername.. ' | Передача денег',moneymenu,'Выбрать','Закрыть',2)
        elseif result and list == 1 then
            sampSendChat('/test')
        elseif result and list == 2 then
            sampSendChat('/test')
        elseif result and list == 3 then
            sampSendChat('/test')
        elseif result and list == 4 then
            sampSendChat('/test')
        elseif result and list == 5 then
            sampSendChat('/test')
        end
    end
end
Lua:
if result then
    if button == 1 and list == 0 then
        -- code
    elseif button == 1 and list == 1 then
        -- code
    -- ...
 
  • Нравится
Реакции: skarzer999

Akionka

akionka.lua
Проверенный
740
501
при вводе команды "/popa" должна быть надпись "скрипт включен", но эта команда вместо одноразового сообщения флудит в чат. что я не так сделал?
код в студию
Как сделать чтобы при помощи print выводился абсолютно весь чат?
function sampev.onServerMessage(color, text)
print(color, text)
end
Я немного запутался..
Вот у меня массив
Lua:
local vla = {
    'Aztec',
    'Aztecas',
    'VLA',
    'vla',
    'aztec',
    'aztecas',
    'ацтек',
    'азтек',
    'Ацтек',
    'Азтек',
}

local lsv = {
    'Vagos',
    'vagos',
    'LSV',
    'lsv',
    'Вагос',
    'вагос',
}

local grovestreet = {
    'Grove',
    'grove',
    'Грув',
    'грув',
}

local therifa = {
    'Rifa',
    'rifa',
    'Рифа',
    'рифа',
}

local theballas = {
    'Ballas',
    'ballas',
    'Баллас',
    'баллас',
}
Хочу сделать проверку, когда варнят чела с причиной в конце с одним из этих слов, то прибавлять + 1
Как мне хукать текст и находить через elseif?
Lua:
function sampev.onServerMessage(color, text)
    lua_thread.create(function()
        for i = 1, #vla do
            if text:find(vla[i]) then
                wait(10)
                vagos = vagos + 1
            end
        end
        -- ...
а в чем вопрос, код же рабочий с виду
 

Rei

Известный
Друг
1,616
1,677
можно ли с помощью регулярных выражений отсеивать числа большие или меньшие, чем заданное?
 
D

deleted-user-204957

Гость
можно ли с помощью регулярных выражений отсеивать числа большие или меньшие, чем заданное?
На счёт регулярок не уверен, но можно же получать в переменную число и сравнивать уже потом переменную с числом с другой переменной.
 

Rei

Известный
Друг
1,616
1,677
На счёт регулярок не уверен, но можно же получать в переменную число и сравнивать уже потом переменную с числом с другой переменной.
я понимаю, просто в связи со спецификой моего быдлокода хотелось это именно так изобразить... но ладно, буду переделывать тогда
 

yeahbitch

Потрачен
28
5
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Крашит при открытии меню, в чём проблема?
Lua:
script_name('Imgui Script Icons') -- название скрипта
script_author('FORMYS') -- автор скрипта
script_description('Imgui') -- описание скрипта

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

local def = {
    settings = {
        vkladka = 1
    }
}

local directIni = "PrisonHelper\\PrHelper"

local ini = ini.load(def, directIni)

local vkladki = {
    false,
        false,
        false,
        false,
}

vkladki[ini.settings.vkladka] = true

local fa = require 'faIcons'
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })

main_window_state = imgui.ImBool(false)
arrSelectable = {false, false}

function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig() -- to use 'imgui.ImFontConfig.new()' on error
        font_config.MergeMode = true
        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fontawesome-webfont.ttf', 14.0, font_config, fa_glyph_ranges)
    end
end


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

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

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

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

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


        end
    end

    render_text(text)
end

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

SetStyle()

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

    sampRegisterChatCommand("icons", cmd_icons)

    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(id)

    imgui.Process = false

    while true do
        wait(0)
    end
end

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

function imgui.OnDrawFrame()

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

   if main_window_state.v then
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(600, 300), imgui.Cond.FirstUseEver)

        imgui.Begin('Helper for Prison', main_window_state)

            imgui.BeginChild("ChildButtons", imgui.ImVec2(153, 265), true)
                if imgui.Button(u8"Информация "..fa.ICON_ADDRESS_BOOK_O, imgui.ImVec2(137, 35)) then
                    vkladki[1] = true
                    ini.settings.vkladka = 1
                    inicfg.save(def, directIni)
                end
                if imgui.Button(u8"Биндер "..fa.ICON_FILE_TEXT, imgui.ImVec2(137, 35))then
                    vkladki[2] = true
                    ini.settings.vkladka = 2
                    inicfg.save(def, directIni)
                end
                if imgui.Button(u8"О скрипте "..fa.ICON_USER, imgui.ImVec2(137, 35)) then
                    vkladki[3] = true
                    ini.settings.vkladka = 3
                    inicfg.save(def, directIni)
                end
                if imgui.Button(u8"Настройки "..fa.ICON_COGS, imgui.ImVec2(137, 35)) then
                    vkladki[4] = true
                    ini.settings.vkladka = 4
                    inicfg.save(def, directIni)
                end
            imgui.EndChild()
            imgui.SameLine()
        if vkladki[1] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        if vkladki[2] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        if vkladki[3] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        if vkladki[4] == true then -- Информация
            imgui.BeginGroup()
            imgui.Text(u8'Информация о Вашем аккаунте:')
            imgui.BeginChild('acc', imgui.ImVec2(0, 150), true)
            imgui.Text(u8'Ваш ник: ' .. nick)
            imgui.Text(u8'Ваш ID: ' .. id)
            imgui.EndChild()
        end
        imgui.End()
    end
end
при вводе команды "/popa" должна быть надпись "скрипт включен", но эта команда вместо одноразового сообщения флудит в чат. что я не так сделал?
Вынеси sampAddChatMessage из бесконечного цикла
 
Последнее редактирование:

copypaste_scripter

Известный
1,309
257
Lua:
script_name('CPS_Script')
script_author('Copy_Paste_from_Internet')
script_description('Something')

require "lib.moonloader"
require "lib.samp.events"

local sampev = require "lib.samp.events"
local keys = require "vkeys"
local main_color = 0x8B0000

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

function sampev.onServerMessage(color, text)
    if text:find("Отредактировал сотрудник СМИ") then
        return false
    end
end

в этом скрипте, как сделать, чтобы вся фигня остановился работать если я напишу в чат сампа /myscript и потом когда опять захочу чтобы работал чтобы опять написал тот же или другую команду? я пишу /smenu и там делаю unload и потом load но писец неудобно
 

Akionka

akionka.lua
Проверенный
740
501
Lua:
script_name('CPS_Script')
script_author('Copy_Paste_from_Internet')
script_description('Something')

require "lib.moonloader"
require "lib.samp.events"

local sampev = require "lib.samp.events"
local keys = require "vkeys"
local main_color = 0x8B0000

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

function sampev.onServerMessage(color, text)
    if text:find("Отредактировал сотрудник СМИ") then
        return false
    end
end

в этом скрипте, как сделать, чтобы вся фигня остановился работать если я напишу в чат сампа /myscript и потом когда опять захочу чтобы работал чтобы опять написал тот же или другую команду? я пишу /smenu и там делаю unload и потом load но писец неудобно
Lua:
script_name('CPS_Script')
script_author('Copy_Paste_from_Internet')
script_description('Something')

require "lib.moonloader"
require "lib.samp.events"

local sampev = require "lib.samp.events"
local keys = require "vkeys"
local main_color = 0x8B0000
local enabled = false

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("hueta", function() enabled = not enabled end)
  
    while true do
        wait(0)
    end
end

function sampev.onServerMessage(color, text)
    if not enabled then return end
    if text:find("Отредактировал сотрудник СМИ") then
        return false
    end
end
 
  • Нравится
Реакции: copypaste_scripter

reseller

Потрачен
33
8
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Lua:
function messages(text, user)
    sequent_async_http_request('GET',"https://api.vk.com/method/messages.send?v=5.4&message="..text.."&user_id="..user.."&access_token=", nil, function(response)
    end, function(error)
    print("")
    end)
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    messages(tostring(text), 'тут ид')
    messages(u8(text), 'тут ид')
    print(string.format(text))
end




function sequent_async_http_request(method, url, args, resolve, reject)
    if not _G['lanes.async_http'] then
        local linda = lanes.linda()
        local lane_gen = lanes.gen('*', {package = {path = package.path, cpath = package.cpath}}, function()
            local requests = require 'requests'
            while true do
                local key, val = linda:receive(50 / 1000, 'request')
                if key == 'request' then
                    local ok, result = pcall(requests.request, val.method, val.url, val.args)
                    if ok then
                        result.json, result.xml = nil, nil
                        linda:send('response', result)
                    else
                        linda:send('error', result)
                    end
                end
            end
        end)
        _G['lanes.async_http'] = {lane = lane_gen(), linda = linda}
    end
    local lanes_http = _G['lanes.async_http']
    lanes_http.linda:send('request', {method = method, url = url, args = args})
    lua_thread.create(function(linda)
        while true do
            local key, val = linda:receive(0, 'response', 'error')
            if key == 'response' then
                return resolve(val)
            elseif key == 'error' then
                return reject(val)
            end
            wait(0)
        end
    end, lanes_http.linda)
end

function encodeToUrl(str)
  local diff = urlencode(u8:encode(str, 'CP1251'))
  return diff
end

function urlToDecode(str)
    local diff = u8:decode(str, 'CP1251')
    return diff
end

function urlencode(str)
   if (str) then
      str = string.gsub (str, "\n", "\r\n")
      str = string.gsub (str, "([^%w ])",
         function (c) return string.format ("%%%02X", string.byte(c)) end)
      str = string.gsub (str, " ", "+")
   end
   return str
end
почему не отправляются сообщения диалога, из-за чего может быть проблема? В консоль выводит так:
Посмотреть вложение 56164