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

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,777
11,226
Как двигать объект в луа с одного места на другое по команде? В самом сампе есть такая функция, но есть ли такая возможность в луа? https://sampwiki.blast.hk/wiki/MoveObject_RU
bool result = setObjectCoordinates(Object object, float atX, float atY, float atZ) -- 01BC
или попробуй это: (не проверял)
Lua:
function moveObject(handle, x, y, z, delay)
    local result, cx, cy, cz = getObjectCoordinates(handle)
    if result then
        for nx = cx, x do
            for ny = cy, y do
                for nz = cz, z do
                    local result = setObjectCoordinates(handle, nx, ny, nz)
                    wait(delay)
                end
            end
        end
    end
end
 
  • Нравится
Реакции: BlackGoblin

BlackGoblin

Известный
519
215
bool result = setObjectCoordinates(Object object, float atX, float atY, float atZ) -- 01BC
или попробуй это: (не проверял)
Lua:
function moveObject(handle, x, y, z, delay)
    local result, cx, cy, cz = getObjectCoordinates(handle)
    if result then
        for nx = cx, x do
            for ny = cy, y do
                for nz = cz, z do
                    local result = setObjectCoordinates(handle, nx, ny, nz)
                    wait(delay)
                end
            end
        end
    end
end
А как после создания объекта сделать, чтобы он плавно перемещался влево/вправо например? Типо до одной координаты и потом назад
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,777
11,226
Как двигать объект в луа с одного места на другое по команде? В самом сампе есть такая функция, но есть ли такая возможность в луа? https://sampwiki.blast.hk/wiki/MoveObject_RU

я выше написал хуйню, нашел нормальную функцию:
Lua:
bool result = slideObject(Object object, float toX, float toY, float toZ, float speedX, float speedY, float speedZ, bool collisionCheck)
А как после создания объекта сделать, чтобы он плавно перемещался влево/вправо например? Типо до одной координаты и потом назад
вот накидал тут говнокода, не тестил, но работать должно
юзай функцию вне цикла
Lua:
local dynamicObjects = {}

function createDynamicObject(model, x1, y1, z1, x2, y2, z2, speedX, speedY, speedZ)
    dynamicObjects[#dynamicObjects + 1] = createObject(model, x1, y1, z1)
    lua_thread.create(function()
        while true do
            wait(0)
            local result, currX, currY, currZ = getObjectCoordinates(dynamicObjects[#dynamicObjects + 1])
            if result then
                if currX == x1 and currY == y1 and currZ == z1 then
                    local result = slideObject(dynamicObjects[#dynamicObjects + 1], x2, y2, z2, speedX, speedY, speedZ, false)
                elseif currX == x2 and currY == y2 and currZ == z2 then
                    local result = slideObject(dynamicObjects[#dynamicObjects + 1], x1, y1, z1, speedX, speedY, speedZ, false)
                end
            end
        end
    end)
end

-- для удаления используй dynamicObjects[номер] = nil
 
  • Нравится
Реакции: BlackGoblin

BlackGoblin

Известный
519
215
я выше написал хуйню, нашел нормальную функцию:
Lua:
bool result = slideObject(Object object, float toX, float toY, float toZ, float speedX, float speedY, float speedZ, bool collisionCheck)

вот накидал тут говнокода, не тестил, но работать должно
юзай функцию вне цикла
Lua:
local dynamicObjects = {}

function createDynamicObject(model, x1, y1, z1, x2, y2, z2, speedX, speedY, speedZ)
    dynamicObjects[#dynamicObjects + 1] = createObject(model, x1, y1, z1)
    lua_thread.create(function()
        while true do
            wait(0)
            local result, currX, currY, currZ = getObjectCoordinates(dynamicObjects[#dynamicObjects + 1])
            if result then
                if currX == x1 and currY == y1 and currZ == z1 then
                    local result = slideObject(dynamicObjects[#dynamicObjects + 1], x2, y2, z2, speedX, speedY, speedZ, false)
                elseif currX == x2 and currY == y2 and currZ == z2 then
                    local result = slideObject(dynamicObjects[#dynamicObjects + 1], x1, y1, z1, speedX, speedY, speedZ, false)
                end
            end
        end
    end)
end

-- для удаления используй dynamicObjects[номер] = nil
До меня не совсем доходит как вообще эту функцию юзать, если честно, можешь вк ответить, если не сложно?
 

Leatington

Известный
258
71
Возможно ли скопировать часть маппинга с сервера и воспроизвести в другом месте на карте с помощью Lua? Если да, подскажите функции. Спасибо.
 

СоМиК

Известный
458
311
[ARZ] Как сделать, чтобы скрипт распознавал на экране тип радара, а если быть точнее, чтобы он сам понимал, какой радар активен у человека, лаунчерский или со сборки
 

Мира

Участник
455
9
есть открытый пример, где через /admins выводят админов в сети?
пример хука нескольких строк из чата и вывода их написанием на экран
 

BlackGoblin

Известный
519
215
Как объекту поменять текстуру в луа? Создаю объект, но хочу, чтобы была другая текстура
 

Мира

Участник
455
9
есть таблица с цифрами и проверка на сообщение в чат. когда ид совпадает с ид с таблицы, то в чат выводится сообщение
не знаю как в проверках взаимодействовать с таблицей
Lua:
local tbah = {

    '561',
    '562',
    '563'

}

if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
    opraId, opraHouseBiz, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
    sampAddChatMessage('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..tbah..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms')
end
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,777
11,226
есть таблица с цифрами и проверка на сообщение в чат. когда ид совпадает с ид с таблицы, то в чат выводится сообщение
не знаю как в проверках взаимодействовать с таблицей
Lua:
local tbah = {

    '561',
    '562',
    '563'

}

if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
    opraId, opraHouseBiz, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
    sampAddChatMessage('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..tbah..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms')
end
Lua:
local tbah = {
    '561',
    '562',
    '563'
}

if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
    for i = 1, #tbah do
        if opraId == tbah[i] then
            opraId, opraHouseBiz, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
            sampAddChatMessage('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..tbah..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms')   
            break
        end
    end
end
 

bratik026

Новичок
13
0
Lua:
Как добавить вот это - unpack(arrGoTo[i], j, j)

Вот сюда -
if stringName:find("%s+СЮДА%s+") then

Не понимаю как работают кавычки.
 

Мира

Участник
455
9
Lua:
local tbah = {
    '561',
    '562',
    '563'
}

if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
    for i = 1, #tbah do
        if opraId == tbah[i] then
            opraId, opraHouseBiz, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
            sampAddChatMessage('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..tbah..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms')  
            break
        end
    end
end
Код:
[21:24:06.874075] (error)    Autoupdate script: ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: attempt to concatenate upvalue 'tbah' (a table value)
stack traceback:
    ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: in function 'callback'
    ... \bin\Arizona\moonloader\lib\samp\events\core.lua:79: in function <... \bin\Arizona\moonloader\lib\samp\events\core.lua:53>
[21:24:06.875182] (error)    Autoupdate script: ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: attempt to concatenate upvalue 'tbah' (a table value)
stack traceback:
    ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: in function 'callback'
    ... \bin\Arizona\moonloader\lib\samp\events\core.lua:79: in function <... \bin\Arizona\moonloader\lib\samp\events\core.lua:53>
[21:24:06.879139] (error)    Autoupdate script: Script died due to an error. (125579FC)
[21:24:06.903131] (error)    imgui_notf.lua: cannot resume non-suspended coroutine
stack traceback:
    [C]: in function 'SetMouseCursor'
    ...ер \bin\Arizona\moonloader\imgui_notf.lua:103: in function <...ер \bin\Arizona\moonloader\imgui_notf.lua:99>
[21:24:06.903131] (error)    imgui_notf.lua: Script died due to an error. (12557D0C)
Lua:
script_name('Autoupdate script') -- название скрипта
script_author('FORMYS') -- автор скрипта
script_description('Autoupdate') -- описание скрипта

require "lib.moonloader" -- подключение библиотеки
local dlstatus = require('moonloader').download_status
local inicfg = require 'inicfg'
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

update_state = false

local script_vers = 2
local script_vers_text = "1.05"

local update_url = "https://raw.githubusercontent.com/thechampguess/scripts/master/update.ini" -- тут тоже свою ссылку
local update_path = getWorkingDirectory() .. "/update.ini" -- и тут свою ссылку

local script_url = "https://github.com/thechampguess/scripts/blob/master/autoupdate_lesson_16.luac?raw=true" -- тут свою ссылку
local script_path = thisScript().path


local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

local sw, sh = getScreenResolution()

local sampev = require 'lib.samp.events'

local hex = ('%x'):format(-1714683649)

local getHereCarId = false

local tpml = false

local tbah = {

    '561',
    '562',
    '563'

}

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    
    sampRegisterChatCommand("update", cmd_update)
    sampRegisterChatCommand('imgui', function()
        main_window_state.v = not main_window_state.v
        imgui.Process = main_window_state.v
    end)
    sampRegisterChatCommand('color', function()
        setClipboardText(hex)
    end)
    sampRegisterChatCommand('test', function()
        sampAddChatMessage(select(2, sampGetPlayerIdByCharHandle(1)), -1)
    end)
    sampRegisterChatCommand('spp', function(arg)
        sampSendChat('/spplayer '..arg, -1)
    end)
    sampRegisterChatCommand('otdal', function(arg)
        sampSendChat('/unjail '..arg..' Возврат слет. имущества', -1)
    end)
    sampRegisterChatCommand('ghc', function()
        getHereCarId = not getHereCarId
        sampAddChatMessage(getHereCarId and '[GHC] Activated!' or '[GHC] Deactivated!', -1)
    end)
    sampRegisterChatCommand('hp', function()
         if isCharInAnyCar(PLAYER_PED) then
            sampSendChat('/flip '..select(2, sampGetPlayerIdByCharHandle(1)))
        else
            sampSendChat('/sethp '..select(2, sampGetPlayerIdByCharHandle(1))..' 100')
        end
    end)
    sampRegisterChatCommand('tpml', function()
        tpml = not tpml
        sampAddChatMessage(tpml and '[TPML] Activated!' or '[TPML] Deactivated!', -1)
    end)
    sampRegisterChatCommand('rsp', cmd_rsp)
    sampRegisterChatCommand('rhp', function()
        lua_thread.create(function()
            for k, v in ipairs(getAllChars()) do
                local res, id = sampGetPlayerIdByCharHandle(v)
                if res then
                    if sampIsPlayerConnected(id) then
                        sampSendChat('/sethp '..id..' 100')
                        wait(0)
                    end
                end
            end
        end)
    end)

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

    downloadUrlToFile(update_url, update_path, function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            updateIni = inicfg.load(nil, update_path)
            if tonumber(updateIni.info.vers) > script_vers then
                sampAddChatMessage("Есть обновление! Версия: " .. updateIni.info.vers_text, -1)
                update_state = true
            end
            os.remove(update_path)
        end
    end)

    imgui.Process = false

    thr = lua_thread.create_suspended(thread_function)
    
    while true do
        wait(0)

        if update_state then
            downloadUrlToFile(script_url, script_path, function(id, status)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                    sampAddChatMessage("Скрипт успешно обновлен!", -1)
                    thisScript():reload()
                end
            end)
            break
        end

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

        if isKeyJustPressed(VK_O)
            and not sampIsChatInputActive()
            and not sampIsDialogActive()
        then
            sampSendChat('/ot')
        end
        if isKeyJustPressed(VK_BACK)
            and not sampIsChatInputActive()
            and not sampIsDialogActive()
        then
            sampSendChat('/reoff')
        end

        imgui.Process = main_window_state.v

        if isKeyJustPressed(VK_H)
            and not sampIsChatInputActive()
            and not sampIsDialogActive()
        then
            for i=0, 2048 do
                if sampIs3dTextDefined(i) then
                    local positionX, positionY, positionZ = getCharCoordinates(PLAYER_PED)
                    local text, color, posX, posY, posZ, distance, ignoreWalls, playerId, vehicleId = sampGet3dTextInfoById(i)
                    local distance = getDistanceBetweenCoords3d(positionX, positionY, positionZ, posX, posY, posZ)
                    if distance <= 20 then
                        if text:find('271') then
                            sampAddChatMessage(distance, -1)
                        end
                    end
                end
            end
        end

        for i=0, 2048 do
            if sampIs3dTextDefined(i) then
                local text, color, posX, posY, posZ, distance, ignoreWalls, playerId, vehicleId = sampGet3dTextInfoById(i)
                if text:find('271') then
                    --sampAddChatMessage(text, -1)
                end
            end
        end

    end
end

function cmd_update(arg)
    sampShowDialog(1000, "Автообновление v2.0", "{FFFFFF}Это урок по обновлению\n{FFF000}Новая версия", "Закрыть", "", 0)
end

function imgui.OnDrawFrame()

    --[[
    
    imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    
    imgui.Begin(u8'Привет', main_window_state)

        imgui.InputText(u8'Вводить текст сюда', text_buffer)
        
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text(u8('Позиция игрока: X: '..math.floor(x)..' | Y: '..math.floor(y)..' | Z: '..math.floor(z)))

        if imgui.Button('Press me') then
            sampAddChatMessage(u8:decode(text_buffer.v), -1)
        end
    
    imgui.End()

    ]]

    imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)--
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    
    imgui.Begin(u8'Привет', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove + imgui.WindowFlags.NoTitleBar)
    
        if isKeyJustPressed(VK_RBUTTON) then
            imgui.ShowCursor = not imgui.ShowCursor
        end
    
        --[[
        
        imgui.InputText(u8'Вводить текст сюда', text_buffer)
        
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text(u8('Позиция игрока: X: '..math.floor(x)..' | Y: '..math.floor(y)..' | Z: '..math.floor(z)))

        if imgui.Button('Press me') then
            sampAddChatMessage(spectatId, -1)
        end

        if imgui.Button('KICK') then
            sampSetChatInputText("/kick "..id..'  // Лоуренс')
            sampSetChatInputCursor(8)
            sampSetChatInputEnabled(true)
        end
        imgui.SameLine()
        imgui.Button('MUTE')
        imgui.SameLine()
        imgui.Button('JAIL')

        imgui.Button(u8'Помочь (Вода)')

        ]]
    
    imgui.End()

end

function sampSetChatInputCursor(start, finish)
    local finish = finish or start
    local start, finish = tonumber(start), tonumber(finish)
    local mem = require 'memory'
    local chatInfoPtr = sampGetInputInfoPtr()
    local chatBoxInfo = getStructElement(chatInfoPtr, 0x8, 4)
    mem.setint8(chatBoxInfo + 0x11E, start)
    mem.setint8(chatBoxInfo + 0x119, finish)
    return true
end

function sampev.onTogglePlayerSpectating(state)

    spectat = state

    --[[
    if state then
        main_window_state.v = not main_window_state.v
        imgui.Process = main_window_state.v
    elseif not state then
        main_window_state.v = false
        imgui.Process = main_window_state.v
    end
    ]]

end

function sampev.onSpectatePlayer(playerId, camType)

    spectatId = playerId

    if spectat then
        --sampAddChatMessage(playerId, -1)
    end

end

function sampev.onServerMessage(color, text)

    --sampAddChatMessage(color, -1)

    if text:find('%[Ошибка%] %{cccccc%}У Вас нет доступа к этой команде%.') and color == -1104335361 then
        --sampAddChatMessage('++', -1)
    end
    if text:find('(.+)') and color == -1714683649 then
        atext = text:match('(.+)')
        --sampAddChatMessage(atext, 0x99cc00)
    end

    --[[
    if tonumber(os.date( "!%M", os.time())) >= 0 and tonumber(os.date( "!%M", os.time())) <= 4 then
        if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: (%d+) по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
            opraId, opraHouseBiz, opraHouseBizId, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: (%d+) по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
            sampSendChat('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..opraHouseBizId..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms')
        end
    end
    ]]

    if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
        for i = 1, #tbah do
            if opraId == tbah[i] then
                opraId, opraHouseBiz, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
                sampAddChatMessage('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..tbah..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms', -1)   
                break
            end
        end
    end

    if getHereCarId then
        if text:find('%{FFFFFF%}%a+%_%a+%[%d+%] говорит%:%{B7AFAF%}  (%d+)') then
            getHereCarId = text:match('%{FFFFFF%}%a+%_%a+%[%d+%] говорит%:%{B7AFAF%}  (%d+)')
            sampSendChat('/getherecar '..getHereCarId)
        end
    end

    if tpml then
        if text:find('%{.+%}%[.+%]%{FFFFFF%} %a+%_%a+%[(%d+)%]%{FFFFFF%}%: %/tpml') then
            tpmlid = text:match('%{.+%}%[.+%]%{FFFFFF%} %a+%_%a+%[(%d+)%]%{FFFFFF%}%: %/tpml')
            sampSendChat('/gethere '..tpmlid)
        end
    end

end

function sampev.onShowDialog(dialogId, style, title, button1, button2, text)

    if text:find('%{FFFFFF%}Введите админ%-пароль') then
        sampSendDialogResponse(dialogId, 1, -1, 25890)
        return false
    end
    if text:find('Нет%, это временный ответ') and text:find('Да%, этот ответ может использоватся как быстрый ответ') then
        sampSendDialogResponse(dialogId, 1, -1, _)
        return false
    end

end

function thread_function()
    for k, v in ipairs(getAllChars()) do
    local res, id = sampGetPlayerIdByCharHandle(v)
        if res then
            if sampIsPlayerConnected(id) then
                score = sampGetPlayerScore(id)
                if sampGetPlayerScore(id) <= 19 then
                    sampSendChat('/spplayer '..id)
                    wait(0)
                end
            end
        end
    end
end

function cmd_rsp(arg)
    thr:run()
end

--[[

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

214
215
216
217

18
19
20
28
29
30
236
239
241
274
275

0
1
124
125
132

38
39
40
41
52
127
143

119
120
121
122

53
54
55
56
57

3
4
5
50
131
135

139

85
86
89
90
91
128
154

15
142

174
175
184
186
187
261

]]

--[[

124
255
307
413
478
491
495
624

858
859

541

441
616

205
207
208
209
226
238
239
240
241
242
243
713

435
438

495
852
855
1166

]]
 

Skezziwe1337

Участник
29
4
help, при закрытии imgui крашит игру
1634574503080.png
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,777
11,226
Код:
[21:24:06.874075] (error)    Autoupdate script: ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: attempt to concatenate upvalue 'tbah' (a table value)
stack traceback:
    ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: in function 'callback'
    ... \bin\Arizona\moonloader\lib\samp\events\core.lua:79: in function <... \bin\Arizona\moonloader\lib\samp\events\core.lua:53>
[21:24:06.875182] (error)    Autoupdate script: ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: attempt to concatenate upvalue 'tbah' (a table value)
stack traceback:
    ... \bin\Arizona\moonloader\autoupdate_lesson_16.lua:300: in function 'callback'
    ... \bin\Arizona\moonloader\lib\samp\events\core.lua:79: in function <... \bin\Arizona\moonloader\lib\samp\events\core.lua:53>
[21:24:06.879139] (error)    Autoupdate script: Script died due to an error. (125579FC)
[21:24:06.903131] (error)    imgui_notf.lua: cannot resume non-suspended coroutine
stack traceback:
    [C]: in function 'SetMouseCursor'
    ...ер \bin\Arizona\moonloader\imgui_notf.lua:103: in function <...ер \bin\Arizona\moonloader\imgui_notf.lua:99>
[21:24:06.903131] (error)    imgui_notf.lua: Script died due to an error. (12557D0C)
Lua:
script_name('Autoupdate script') -- название скрипта
script_author('FORMYS') -- автор скрипта
script_description('Autoupdate') -- описание скрипта

require "lib.moonloader" -- подключение библиотеки
local dlstatus = require('moonloader').download_status
local inicfg = require 'inicfg'
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

update_state = false

local script_vers = 2
local script_vers_text = "1.05"

local update_url = "https://raw.githubusercontent.com/thechampguess/scripts/master/update.ini" -- тут тоже свою ссылку
local update_path = getWorkingDirectory() .. "/update.ini" -- и тут свою ссылку

local script_url = "https://github.com/thechampguess/scripts/blob/master/autoupdate_lesson_16.luac?raw=true" -- тут свою ссылку
local script_path = thisScript().path


local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

local sw, sh = getScreenResolution()

local sampev = require 'lib.samp.events'

local hex = ('%x'):format(-1714683649)

local getHereCarId = false

local tpml = false

local tbah = {

    '561',
    '562',
    '563'

}

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
   
    sampRegisterChatCommand("update", cmd_update)
    sampRegisterChatCommand('imgui', function()
        main_window_state.v = not main_window_state.v
        imgui.Process = main_window_state.v
    end)
    sampRegisterChatCommand('color', function()
        setClipboardText(hex)
    end)
    sampRegisterChatCommand('test', function()
        sampAddChatMessage(select(2, sampGetPlayerIdByCharHandle(1)), -1)
    end)
    sampRegisterChatCommand('spp', function(arg)
        sampSendChat('/spplayer '..arg, -1)
    end)
    sampRegisterChatCommand('otdal', function(arg)
        sampSendChat('/unjail '..arg..' Возврат слет. имущества', -1)
    end)
    sampRegisterChatCommand('ghc', function()
        getHereCarId = not getHereCarId
        sampAddChatMessage(getHereCarId and '[GHC] Activated!' or '[GHC] Deactivated!', -1)
    end)
    sampRegisterChatCommand('hp', function()
         if isCharInAnyCar(PLAYER_PED) then
            sampSendChat('/flip '..select(2, sampGetPlayerIdByCharHandle(1)))
        else
            sampSendChat('/sethp '..select(2, sampGetPlayerIdByCharHandle(1))..' 100')
        end
    end)
    sampRegisterChatCommand('tpml', function()
        tpml = not tpml
        sampAddChatMessage(tpml and '[TPML] Activated!' or '[TPML] Deactivated!', -1)
    end)
    sampRegisterChatCommand('rsp', cmd_rsp)
    sampRegisterChatCommand('rhp', function()
        lua_thread.create(function()
            for k, v in ipairs(getAllChars()) do
                local res, id = sampGetPlayerIdByCharHandle(v)
                if res then
                    if sampIsPlayerConnected(id) then
                        sampSendChat('/sethp '..id..' 100')
                        wait(0)
                    end
                end
            end
        end)
    end)

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

    downloadUrlToFile(update_url, update_path, function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            updateIni = inicfg.load(nil, update_path)
            if tonumber(updateIni.info.vers) > script_vers then
                sampAddChatMessage("Есть обновление! Версия: " .. updateIni.info.vers_text, -1)
                update_state = true
            end
            os.remove(update_path)
        end
    end)

    imgui.Process = false

    thr = lua_thread.create_suspended(thread_function)
   
    while true do
        wait(0)

        if update_state then
            downloadUrlToFile(script_url, script_path, function(id, status)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                    sampAddChatMessage("Скрипт успешно обновлен!", -1)
                    thisScript():reload()
                end
            end)
            break
        end

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

        if isKeyJustPressed(VK_O)
            and not sampIsChatInputActive()
            and not sampIsDialogActive()
        then
            sampSendChat('/ot')
        end
        if isKeyJustPressed(VK_BACK)
            and not sampIsChatInputActive()
            and not sampIsDialogActive()
        then
            sampSendChat('/reoff')
        end

        imgui.Process = main_window_state.v

        if isKeyJustPressed(VK_H)
            and not sampIsChatInputActive()
            and not sampIsDialogActive()
        then
            for i=0, 2048 do
                if sampIs3dTextDefined(i) then
                    local positionX, positionY, positionZ = getCharCoordinates(PLAYER_PED)
                    local text, color, posX, posY, posZ, distance, ignoreWalls, playerId, vehicleId = sampGet3dTextInfoById(i)
                    local distance = getDistanceBetweenCoords3d(positionX, positionY, positionZ, posX, posY, posZ)
                    if distance <= 20 then
                        if text:find('271') then
                            sampAddChatMessage(distance, -1)
                        end
                    end
                end
            end
        end

        for i=0, 2048 do
            if sampIs3dTextDefined(i) then
                local text, color, posX, posY, posZ, distance, ignoreWalls, playerId, vehicleId = sampGet3dTextInfoById(i)
                if text:find('271') then
                    --sampAddChatMessage(text, -1)
                end
            end
        end

    end
end

function cmd_update(arg)
    sampShowDialog(1000, "Автообновление v2.0", "{FFFFFF}Это урок по обновлению\n{FFF000}Новая версия", "Закрыть", "", 0)
end

function imgui.OnDrawFrame()

    --[[
   
    imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   
    imgui.Begin(u8'Привет', main_window_state)

        imgui.InputText(u8'Вводить текст сюда', text_buffer)
       
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text(u8('Позиция игрока: X: '..math.floor(x)..' | Y: '..math.floor(y)..' | Z: '..math.floor(z)))

        if imgui.Button('Press me') then
            sampAddChatMessage(u8:decode(text_buffer.v), -1)
        end
   
    imgui.End()

    ]]

    imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)--
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   
    imgui.Begin(u8'Привет', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove + imgui.WindowFlags.NoTitleBar)
   
        if isKeyJustPressed(VK_RBUTTON) then
            imgui.ShowCursor = not imgui.ShowCursor
        end
   
        --[[
       
        imgui.InputText(u8'Вводить текст сюда', text_buffer)
       
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text(u8('Позиция игрока: X: '..math.floor(x)..' | Y: '..math.floor(y)..' | Z: '..math.floor(z)))

        if imgui.Button('Press me') then
            sampAddChatMessage(spectatId, -1)
        end

        if imgui.Button('KICK') then
            sampSetChatInputText("/kick "..id..'  // Лоуренс')
            sampSetChatInputCursor(8)
            sampSetChatInputEnabled(true)
        end
        imgui.SameLine()
        imgui.Button('MUTE')
        imgui.SameLine()
        imgui.Button('JAIL')

        imgui.Button(u8'Помочь (Вода)')

        ]]
   
    imgui.End()

end

function sampSetChatInputCursor(start, finish)
    local finish = finish or start
    local start, finish = tonumber(start), tonumber(finish)
    local mem = require 'memory'
    local chatInfoPtr = sampGetInputInfoPtr()
    local chatBoxInfo = getStructElement(chatInfoPtr, 0x8, 4)
    mem.setint8(chatBoxInfo + 0x11E, start)
    mem.setint8(chatBoxInfo + 0x119, finish)
    return true
end

function sampev.onTogglePlayerSpectating(state)

    spectat = state

    --[[
    if state then
        main_window_state.v = not main_window_state.v
        imgui.Process = main_window_state.v
    elseif not state then
        main_window_state.v = false
        imgui.Process = main_window_state.v
    end
    ]]

end

function sampev.onSpectatePlayer(playerId, camType)

    spectatId = playerId

    if spectat then
        --sampAddChatMessage(playerId, -1)
    end

end

function sampev.onServerMessage(color, text)

    --sampAddChatMessage(color, -1)

    if text:find('%[Ошибка%] %{cccccc%}У Вас нет доступа к этой команде%.') and color == -1104335361 then
        --sampAddChatMessage('++', -1)
    end
    if text:find('(.+)') and color == -1714683649 then
        atext = text:match('(.+)')
        --sampAddChatMessage(atext, 0x99cc00)
    end

    --[[
    if tonumber(os.date( "!%M", os.time())) >= 0 and tonumber(os.date( "!%M", os.time())) <= 4 then
        if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: (%d+) по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
            opraId, opraHouseBiz, opraHouseBizId, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: (%d+) по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
            sampSendChat('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..opraHouseBizId..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms')
        end
    end
    ]]

    if text:find('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)') and color == -1104335361 then
        for i = 1, #tbah do
            if opraId == tbah[i] then
                opraId, opraHouseBiz, secondsHouseBiz1, secondsHouseBiz2 = text:match('%a+%_%a+ %[(%d+)%] купил (%W+) ID%: '..tbah..' по гос%. цене за (%d+)%.(%d+) ms%! Капча%: %(%d+ %| %d+%)')
                sampAddChatMessage('/jail '..opraId..' 2999 Опра '..opraHouseBiz..' №'..tbah..' | '..secondsHouseBiz1..'.'..secondsHouseBiz2..' ms', -1)  
                break
            end
        end
    end

    if getHereCarId then
        if text:find('%{FFFFFF%}%a+%_%a+%[%d+%] говорит%:%{B7AFAF%}  (%d+)') then
            getHereCarId = text:match('%{FFFFFF%}%a+%_%a+%[%d+%] говорит%:%{B7AFAF%}  (%d+)')
            sampSendChat('/getherecar '..getHereCarId)
        end
    end

    if tpml then
        if text:find('%{.+%}%[.+%]%{FFFFFF%} %a+%_%a+%[(%d+)%]%{FFFFFF%}%: %/tpml') then
            tpmlid = text:match('%{.+%}%[.+%]%{FFFFFF%} %a+%_%a+%[(%d+)%]%{FFFFFF%}%: %/tpml')
            sampSendChat('/gethere '..tpmlid)
        end
    end

end

function sampev.onShowDialog(dialogId, style, title, button1, button2, text)

    if text:find('%{FFFFFF%}Введите админ%-пароль') then
        sampSendDialogResponse(dialogId, 1, -1, 25890)
        return false
    end
    if text:find('Нет%, это временный ответ') and text:find('Да%, этот ответ может использоватся как быстрый ответ') then
        sampSendDialogResponse(dialogId, 1, -1, _)
        return false
    end

end

function thread_function()
    for k, v in ipairs(getAllChars()) do
    local res, id = sampGetPlayerIdByCharHandle(v)
        if res then
            if sampIsPlayerConnected(id) then
                score = sampGetPlayerScore(id)
                if sampGetPlayerScore(id) <= 19 then
                    sampSendChat('/spplayer '..id)
                    wait(0)
                end
            end
        end
    end
end

function cmd_rsp(arg)
    thr:run()
end

--[[

261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279

214
215
216
217

18
19
20
28
29
30
236
239
241
274
275

0
1
124
125
132

38
39
40
41
52
127
143

119
120
121
122

53
54
55
56
57

3
4
5
50
131
135

139

85
86
89
90
91
128
154

15
142

174
175
184
186
187
261

]]

--[[

124
255
307
413
478
491
495
624

858
859

541

441
616

205
207
208
209
226
238
239
240
241
242
243
713

435
438

495
852
855
1166

]]
в text:find() замени ..tbah.. на регулярку