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

[SA ARZ]

Известный
392
8



Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(0) end
    sampAddChatMessage("{cdcdcd}LUAc: {f3f3f3}"..thisScript().name.." v"..thisScript().version.." {66cc00}» успешно загрузился.", 0xcdcdcd)
    sampAddChatMessage("{cdcdcd}LUAc: {f3f3f3}Автор данного скрипта {66cc00}SGray.", 0xcdcdcd)
    while not sampIsLocalPlayerSpawned() do wait(0) end
    ServerPlay = sampGetCurrentServerName()
    ServerIP = sampGetCurrentServerAddress()
    if ServerPlay == "Advance RolePlay 9 | Chocolate Server" or    ServerIP == "5.254.104.139" then
        if settings.options.startmessage then
            wait(2000)
            _, myid = sampGetPlayerIdByCharHandle(PLAYER_PED)
            nick = sampGetPlayerNickname(myid)
            color = string.format("%06X", ARGBtoRGB(sampGetPlayerColor(myid)))
            if color == 'CCFF00' then
                sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {F3F3F3}Версия скрипта: {669acc}"..thisScript().version.." {F3F3F3}| Помощь по скрипту: {669acc}/utmn.", 0xf3f3f3)
                ConnectText = u8('['..os.date('%d:%m:%Y')..'] Ник: '..nick..' зашёл на сервер: '..ServerPlay..' [IP сервера: '..ServerIP..']')
                downloadUrlToFile(u8'http://sir.net/UTools/logs-utools.php?Text='..ConnectText, function(id, status)
                    if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                        script.this:unload()
                    end
                end)
                AdminRadio()
                VipRadio()
            dostupUTools = "GOV"
            elseif color == '996633' then
                sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {F3F3F3}Версия скрипта: {669acc}"..thisScript().version.." {F3F3F3}| Помощь по скрипту: {669acc}/utmn.", 0xf3f3f3)
                ConnectText = u8('['..os.date('%d:%m:%Y')..'] Ник: '..nick..' зашёл на сервер: '..ServerPlay..' [IP сервера: '..ServerIP..']')
                downloadUrlToFile(u8'http://sir.net/UTools/logs-utools.php?Text='..ConnectText, function(id, status)
                    if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                        script.this:unload()
                    end
                end)
                AdminRadio()
                VipRadio()
            dostupUTools = "MO"
            else
            ConnectText = u8('['..os.date('%d:%m:%Y')..'] Ник: '..nick..' зашёл на сервер: '..ServerPlay..' [IP сервера: '..ServerIP..']')
            downloadUrlToFile(u8'http://sir.net/UTools/logs-utools.php?Text='..ConnectText, function(id, status)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                    script.this:unload()
                end
            end)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Данный скрипт работает только для:", 0xf3f3f3)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {CCFF00}Правительство и {996633}Министерство Обороны", 0xf3f3f3)
            thisScript():unload()
            while getCharHealth() > 0 do wait(0) end
            end
        else
            _, myid = sampGetPlayerIdByCharHandle(PLAYER_PED)
            color = string.format("%06X", ARGBtoRGB(sampGetPlayerColor(myid)))
            if color == 'CCFF00' then
            dostupUTools = "GOV"
            AdminRadio()
            VipRadio()
            elseif color == '996633' then
            dostupUTools = "MO"
            AdminRadio()
            VipRadio()
            else
            thisScript():unload()
            while getCharHealth() > 0 do wait(0) end
            end
        end
    else
    sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Данный скрипт работает только для:", 0xf3f3f3)
    sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {996633}Advance RolePlay 9 | Chocolate Server", 0xf3f3f3)
    thisScript():unload()
    end
  if settings.options.autoupdate == true then
    update()
    while update ~= false do wait(100) end
  end
  sampRegisterChatCommand('phone', SystemPhone)
  sampRegisterChatCommand("строй", StroiList)
  sampRegisterChatCommand("лекция", Lection)
  sampRegisterChatCommand("shpora", MenuShporaList)
  sampRegisterChatCommand("utmn", scriptmenu)
  sampRegisterChatCommand('hist', HistoryPlayer)
  sampRegisterChatCommand('r', RadioRun)
  sampRegisterChatCommand('f', RadioFun)
  sampRegisterChatCommand('rn', RadioRunNonRP)
  sampRegisterChatCommand('fn', RadioFunNonRP)
  sampRegisterChatCommand("sw", cmdSetWeather)
  sampRegisterChatCommand('free', FreeJail)
  sampRegisterChatCommand('s5', gojail)
  sampRegisterChatCommand('kiss', kiss)
  sampRegisterChatCommand('gg', ggPrivet)
  sampRegisterChatCommand('uds', udsPlayer)
  sampRegisterChatCommand('whois', WhoisPlayer)
  sampRegisterChatCommand('blackupd', BlackUpdate)
  sampRegisterChatCommand('black', blcheckCmd)
  sampRegisterChatCommand('blackhist', blcheckoffCmd)
  sampRegisterChatCommand('unv', UvalPlayer)
  sampRegisterChatCommand('unby', UvalPlayerBy)
  sampRegisterChatCommand('где', GPSPlayer)
  sampRegisterChatCommand('inv', InvitePlayer)
  sampRegisterChatCommand('rang', RangSystem)
  sampRegisterChatCommand('givelic', GiveLicSystem)
  sampRegisterChatCommand('check', CheckStroi)
    menuupdate()
    while true do
        wait(0)
        imgui.Process = first_window.v or mask_window.v
        if menutrigger ~= nil then menu() menutrigger = nil end
        if settings.options.hud == true then
            first_window.v = true
            imgui.ShowCursor = false
        end
        if settings.options.hud == false then
            first_window.v = false
            imgui.ShowCursor = false
        end
        valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
        if valid and doesCharExist(ped) then
        result, id = sampGetPlayerIdByCharHandle(ped)
        if result and wasKeyPressed(key.VK_R) then
            if dostupUTools == "GOV" then
                if settings.SetRang.NameRang == "Адвокат" then
                    submenus_show(PKAdvocate(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
                elseif settings.SetRang.NameRang == "Лицензер" or settings.SetRang.NameRang == "Старший лицензер" then
                    submenus_show(PKLic(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
                else
                    submenus_show(PKGov(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
                end
            elseif dostupUTools == "MO" then
                submenus_show(pkmmenuMO(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
            end
          end
        end
        if wasKeyPressed(settings.vKeyBind.KeyLock) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/lock 1")
        end
        if wasKeyPressed(settings.vKeyBind.KeyTime) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/c 60")
        end
        if wasKeyPressed(settings.vKeyBind.KeyFind) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/find")
        end
        if wasKeyPressed(settings.vKeyBind.KeyGate) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/gate")
        end
        if dostupUTools == "MO" then
            valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            result, id = sampGetPlayerIdByCharHandle(ped)
            if result and wasKeyPressed(key.VK_1) then
                name = sampGetPlayerNickname(id)
                nm1, nm2 = string.match(name, "(%g+)_(%g+)")
                sampSendChat('/todo Поприветствовав военного*Здравия желаю, товарищ '..nm2..'!')
                sampSendChat('/anim 59')
            end
        end
        result, button, list, input = sampHasDialogRespond(1385)
        if result then
        if button == 1 then
            NotFree = 1
            if settings.options.male == true then
            sampSendChat('Хорошо, сейчас заполним бланк освобождения.')
            wait(1000)
            sampSendChat('/do Бланк "Освобождения заключеного И.К.Л.С" в портфеле.')
            wait(1000)
            sampSendChat('/me достал бланк "Освобождения заключеного И.К.Л.С" из портфеля')
            wait(1000)
            sampSendChat('/me достал КПК и подключился к БД И.К.Л.С и ищет УДО №'..id)
            wait(1000)
            sampSendChat('/do КПК выдал имя '..nm1..' фамилию '..nm2..'.')
            wait(1000)
            sampSendChat('/me заполняет бланк "Освобождения заключеного И.К.Л.С"')
            wait(1000)
            sampSendChat('/do УДО: '..id..' | Имя: '..nm1..'. Фамилия: '..nm2..' | Цена: '..input..'$.')
            wait(1000)
            sampSendChat('Вот готовый бланк Вашего освобождения на сумму '..input..'$.')
            wait(1000)
            sampSendChat('/todo Указав пальцем место подписи*Просто подпишите данный бланк вот здесь.')
            sampSendChat('/do Ручка была на бланке "Освобождения заключеного И.К.Л.С".')
            wait(1000)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Продолжить отыгровку скрипта {FF6666}F2", 0xf3f3f3)
            repeat
            wait(0)
            until isKeyJustPressed(VK_F2)
            sampSendChat('/free '..id..' '..input)
            NumberFreeCode = 2
            elseif settings.options.male == false then
            sampSendChat('Хорошо, сейчас заполним бланк освобождения.')
            wait(1000)
            sampSendChat('/do Бланк "Освобождения заключеного И.К.Л.С" в портфеле.')
            wait(1000)
            sampSendChat('/me достала бланк "Освобождения заключеного И.К.Л.С" из портфеля')
            wait(1000)
            sampSendChat('/me достала КПК и подключилась к БД И.К.Л.С и ищет УДО №'..id)
            wait(1000)
            sampSendChat('/do КПК выдал имя '..nm1..' фамилию '..nm2..'.')
            wait(1000)
            sampSendChat('/me заполняет бланк "Освобождения заключеного И.К.Л.С"')
            wait(1000)
            sampSendChat('/do УДО: '..id..' | Имя: '..nm1..' | Фамилия: '..nm2..' | Цена: '..input..'$.')
            wait(1000)
            sampSendChat('Вот готовый бланк Вашего освобождения на сумму '..input..'$.')
            wait(1000)
            sampSendChat('/todo Указав пальцем место подписи*Просто подпишите данный бланк вот здесь.')
            sampSendChat('/do Ручка была на бланке "Освобождения заключеного И.К.Л.С".')
            wait(1000)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Продолжить отыгровку скрипта {FF6666}F2", 0xf3f3f3)
            repeat
            wait(0)
            until isKeyJustPressed(VK_F2)
            sampSendChat('/free '..id..' '..input)
            NumberFreeCode = 2
            end
        end
        if ad then
            wait(60000)
            local rand = math.random(1, 4)
            if rand == 1 then
                sampAddChatMessage("[1] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            elseif rand == 2 then
                sampAddChatMessage("[2] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            elseif rand == 3 then
                sampAddChatMessage("[3] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            elseif rand == 4 then
                sampAddChatMessage("[4] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            end
        end
      end
    end
end
 

ШPEK

Известный
1,474
526
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(0) end
    sampAddChatMessage("{cdcdcd}LUAc: {f3f3f3}"..thisScript().name.." v"..thisScript().version.." {66cc00}» успешно загрузился.", 0xcdcdcd)
    sampAddChatMessage("{cdcdcd}LUAc: {f3f3f3}Автор данного скрипта {66cc00}SGray.", 0xcdcdcd)
    while not sampIsLocalPlayerSpawned() do wait(0) end
    ServerPlay = sampGetCurrentServerName()
    ServerIP = sampGetCurrentServerAddress()
    if ServerPlay == "Advance RolePlay 9 | Chocolate Server" or    ServerIP == "5.254.104.139" then
        if settings.options.startmessage then
            wait(2000)
            _, myid = sampGetPlayerIdByCharHandle(PLAYER_PED)
            nick = sampGetPlayerNickname(myid)
            color = string.format("%06X", ARGBtoRGB(sampGetPlayerColor(myid)))
            if color == 'CCFF00' then
                sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {F3F3F3}Версия скрипта: {669acc}"..thisScript().version.." {F3F3F3}| Помощь по скрипту: {669acc}/utmn.", 0xf3f3f3)
                ConnectText = u8('['..os.date('%d:%m:%Y')..'] Ник: '..nick..' зашёл на сервер: '..ServerPlay..' [IP сервера: '..ServerIP..']')
                downloadUrlToFile(u8'http://sir.net/UTools/logs-utools.php?Text='..ConnectText, function(id, status)
                    if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                        script.this:unload()
                    end
                end)
                AdminRadio()
                VipRadio()
            dostupUTools = "GOV"
            elseif color == '996633' then
                sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {F3F3F3}Версия скрипта: {669acc}"..thisScript().version.." {F3F3F3}| Помощь по скрипту: {669acc}/utmn.", 0xf3f3f3)
                ConnectText = u8('['..os.date('%d:%m:%Y')..'] Ник: '..nick..' зашёл на сервер: '..ServerPlay..' [IP сервера: '..ServerIP..']')
                downloadUrlToFile(u8'http://sir.net/UTools/logs-utools.php?Text='..ConnectText, function(id, status)
                    if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                        script.this:unload()
                    end
                end)
                AdminRadio()
                VipRadio()
            dostupUTools = "MO"
            else
            ConnectText = u8('['..os.date('%d:%m:%Y')..'] Ник: '..nick..' зашёл на сервер: '..ServerPlay..' [IP сервера: '..ServerIP..']')
            downloadUrlToFile(u8'http://sir.net/UTools/logs-utools.php?Text='..ConnectText, function(id, status)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                    script.this:unload()
                end
            end)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Данный скрипт работает только для:", 0xf3f3f3)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {CCFF00}Правительство и {996633}Министерство Обороны", 0xf3f3f3)
            thisScript():unload()
            while getCharHealth() > 0 do wait(0) end
            end
        else
            _, myid = sampGetPlayerIdByCharHandle(PLAYER_PED)
            color = string.format("%06X", ARGBtoRGB(sampGetPlayerColor(myid)))
            if color == 'CCFF00' then
            dostupUTools = "GOV"
            AdminRadio()
            VipRadio()
            elseif color == '996633' then
            dostupUTools = "MO"
            AdminRadio()
            VipRadio()
            else
            thisScript():unload()
            while getCharHealth() > 0 do wait(0) end
            end
        end
    else
    sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Данный скрипт работает только для:", 0xf3f3f3)
    sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {996633}Advance RolePlay 9 | Chocolate Server", 0xf3f3f3)
    thisScript():unload()
    end
  if settings.options.autoupdate == true then
    update()
    while update ~= false do wait(100) end
  end
  sampRegisterChatCommand('phone', SystemPhone)
  sampRegisterChatCommand("строй", StroiList)
  sampRegisterChatCommand("лекция", Lection)
  sampRegisterChatCommand("shpora", MenuShporaList)
  sampRegisterChatCommand("utmn", scriptmenu)
  sampRegisterChatCommand('hist', HistoryPlayer)
  sampRegisterChatCommand('r', RadioRun)
  sampRegisterChatCommand('f', RadioFun)
  sampRegisterChatCommand('rn', RadioRunNonRP)
  sampRegisterChatCommand('fn', RadioFunNonRP)
  sampRegisterChatCommand("sw", cmdSetWeather)
  sampRegisterChatCommand('free', FreeJail)
  sampRegisterChatCommand('s5', gojail)
  sampRegisterChatCommand('kiss', kiss)
  sampRegisterChatCommand('gg', ggPrivet)
  sampRegisterChatCommand('uds', udsPlayer)
  sampRegisterChatCommand('whois', WhoisPlayer)
  sampRegisterChatCommand('blackupd', BlackUpdate)
  sampRegisterChatCommand('black', blcheckCmd)
  sampRegisterChatCommand('blackhist', blcheckoffCmd)
  sampRegisterChatCommand('unv', UvalPlayer)
  sampRegisterChatCommand('unby', UvalPlayerBy)
  sampRegisterChatCommand('где', GPSPlayer)
  sampRegisterChatCommand('inv', InvitePlayer)
  sampRegisterChatCommand('rang', RangSystem)
  sampRegisterChatCommand('givelic', GiveLicSystem)
  sampRegisterChatCommand('check', CheckStroi)
    menuupdate()
    while true do
        wait(0)
        imgui.Process = first_window.v or mask_window.v
        if menutrigger ~= nil then menu() menutrigger = nil end
        if settings.options.hud == true then
            first_window.v = true
            imgui.ShowCursor = false
        end
        if settings.options.hud == false then
            first_window.v = false
            imgui.ShowCursor = false
        end
        valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
        if valid and doesCharExist(ped) then
        result, id = sampGetPlayerIdByCharHandle(ped)
        if result and wasKeyPressed(key.VK_R) then
            if dostupUTools == "GOV" then
                if settings.SetRang.NameRang == "Адвокат" then
                    submenus_show(PKAdvocate(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
                elseif settings.SetRang.NameRang == "Лицензер" or settings.SetRang.NameRang == "Старший лицензер" then
                    submenus_show(PKLic(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
                else
                    submenus_show(PKGov(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
                end
            elseif dostupUTools == "MO" then
                submenus_show(pkmmenuMO(id), '{669acc}UTools {ffffff}» Игрок: {F56666}'..sampGetPlayerNickname(id)..'['..id..']', 'Выбрать', 'Закрыть', 'Назад')
            end
          end
        end
        if wasKeyPressed(settings.vKeyBind.KeyLock) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/lock 1")
        end
        if wasKeyPressed(settings.vKeyBind.KeyTime) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/c 60")
        end
        if wasKeyPressed(settings.vKeyBind.KeyFind) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/find")
        end
        if wasKeyPressed(settings.vKeyBind.KeyGate) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampSendChat("/gate")
        end
        if dostupUTools == "MO" then
            valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
            result, id = sampGetPlayerIdByCharHandle(ped)
            if result and wasKeyPressed(key.VK_1) then
                name = sampGetPlayerNickname(id)
                nm1, nm2 = string.match(name, "(%g+)_(%g+)")
                sampSendChat('/todo Поприветствовав военного*Здравия желаю, товарищ '..nm2..'!')
                sampSendChat('/anim 59')
            end
        end
        result, button, list, input = sampHasDialogRespond(1385)
        if result then
        if button == 1 then
            NotFree = 1
            if settings.options.male == true then
            sampSendChat('Хорошо, сейчас заполним бланк освобождения.')
            wait(1000)
            sampSendChat('/do Бланк "Освобождения заключеного И.К.Л.С" в портфеле.')
            wait(1000)
            sampSendChat('/me достал бланк "Освобождения заключеного И.К.Л.С" из портфеля')
            wait(1000)
            sampSendChat('/me достал КПК и подключился к БД И.К.Л.С и ищет УДО №'..id)
            wait(1000)
            sampSendChat('/do КПК выдал имя '..nm1..' фамилию '..nm2..'.')
            wait(1000)
            sampSendChat('/me заполняет бланк "Освобождения заключеного И.К.Л.С"')
            wait(1000)
            sampSendChat('/do УДО: '..id..' | Имя: '..nm1..'. Фамилия: '..nm2..' | Цена: '..input..'$.')
            wait(1000)
            sampSendChat('Вот готовый бланк Вашего освобождения на сумму '..input..'$.')
            wait(1000)
            sampSendChat('/todo Указав пальцем место подписи*Просто подпишите данный бланк вот здесь.')
            sampSendChat('/do Ручка была на бланке "Освобождения заключеного И.К.Л.С".')
            wait(1000)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Продолжить отыгровку скрипта {FF6666}F2", 0xf3f3f3)
            repeat
            wait(0)
            until isKeyJustPressed(VK_F2)
            sampSendChat('/free '..id..' '..input)
            NumberFreeCode = 2
            elseif settings.options.male == false then
            sampSendChat('Хорошо, сейчас заполним бланк освобождения.')
            wait(1000)
            sampSendChat('/do Бланк "Освобождения заключеного И.К.Л.С" в портфеле.')
            wait(1000)
            sampSendChat('/me достала бланк "Освобождения заключеного И.К.Л.С" из портфеля')
            wait(1000)
            sampSendChat('/me достала КПК и подключилась к БД И.К.Л.С и ищет УДО №'..id)
            wait(1000)
            sampSendChat('/do КПК выдал имя '..nm1..' фамилию '..nm2..'.')
            wait(1000)
            sampSendChat('/me заполняет бланк "Освобождения заключеного И.К.Л.С"')
            wait(1000)
            sampSendChat('/do УДО: '..id..' | Имя: '..nm1..' | Фамилия: '..nm2..' | Цена: '..input..'$.')
            wait(1000)
            sampSendChat('Вот готовый бланк Вашего освобождения на сумму '..input..'$.')
            wait(1000)
            sampSendChat('/todo Указав пальцем место подписи*Просто подпишите данный бланк вот здесь.')
            sampSendChat('/do Ручка была на бланке "Освобождения заключеного И.К.Л.С".')
            wait(1000)
            sampAddChatMessage("{f3f3f3}• [{669acc}UTools{f3f3f3}]: {f3f3f3}Продолжить отыгровку скрипта {FF6666}F2", 0xf3f3f3)
            repeat
            wait(0)
            until isKeyJustPressed(VK_F2)
            sampSendChat('/free '..id..' '..input)
            NumberFreeCode = 2
            end
        end
        if ad then
            wait(60000)
            local rand = math.random(1, 4)
            if rand == 1 then
                sampAddChatMessage("[1] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            elseif rand == 2 then
                sampAddChatMessage("[2] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            elseif rand == 3 then
                sampAddChatMessage("[3] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            elseif rand == 4 then
                sampAddChatMessage("[4] в орифлейм появились новые ароматы покупай пока есть", 0xf3f3f3)
            end
        end
      end
    end
end
Есть ошибка? Если да - кинь
 
  • Нравится
Реакции: [SA ARZ]

Shell :3

Активный
159
32
Я вот хочу вставить картинку в имгуи... Использую этот код чтоб указать путь к файлу, но с ним не открывается окно имгуи, в логе все чисто... Хорошо все. newTexture = imgui.CreateTextureFromFile('\settings\logo\taxi_logo.png') Может ему что-то подключать отдельно надо?
 

Oreshka23

Известный
341
166
Я вот хочу вставить картинку в имгуи... Использую этот код чтоб указать путь к файлу, но с ним не открывается окно имгуи, в логе все чисто... Хорошо все. newTexture = imgui.CreateTextureFromFile('\settings\logo\taxi_logo.png') Может ему что-то подключать отдельно надо?
Lua:
newTexture = imgui.CreateTextureFromFile(getWorkingDirectory()..'\settings\logo\taxi_logo.png')
 

[SA ARZ]

Известный
392
8
Lua:
for w in text:gmatch('[^\r\n]+') do
if string.find(text, "^Работа / должность:%s+(.*)$") then
local NameRang = string.match(text, "^Работа / должность:%s+(.*)$")
break
end
end
что я делаю не так? зависает скрипт


Lua:
function updateSystem()
lua_thread.create(function()
    sampSendChat('/mn')
    while not sampIsDialogActive() do wait(0) end
    sampSetCurrentDialogListItem(0)
    sampCloseCurrentDialogWithButton(1)
    lua_thread.create(function() wait(1000)
        text = sampGetDialogText()
        for w in text:gmatch('[^\r\n]+') do
        if string.find(text, "^Работа / должность:%s+(.*)$") then
        NameRang = string.match(text, "^Работа / должность:%s+(.*)$")
        break
        end
        end
        print(NameRang)
    end)
end)
end
 

ШPEK

Известный
1,474
526
что я делаю не так? зависает скрипт


Lua:
function updateSystem()
lua_thread.create(function()
    sampSendChat('/mn')
    while not sampIsDialogActive() do wait(0) end
    sampSetCurrentDialogListItem(0)
    sampCloseCurrentDialogWithButton(1)
    lua_thread.create(function() wait(1000)
        text = sampGetDialogText()
        for w in text:gmatch('[^\r\n]+') do
        if string.find(w, "^Работа / должность:%s+(.*)$") then
        NameRang = string.match(w, "^Работа / должность:%s+(.*)$")
        break
        end
        end
        print(NameRang)
    end)
end)
end
Lua:
function updateSystem()
lua_thread.create(function()
    sampSendChat('/mn')
    while not sampIsDialogActive() do wait(0) end
    wait(0)
    sampSetCurrentDialogListItem(0)
    wait(0)
    sampCloseCurrentDialogWithButton(1)
    lua_thread.create(function() wait(1000)
        text = sampGetDialogText()
        for w in text:gmatch('[^\r\n]+') do
        wait(0)
        if string.find(w, "^Работа / должность:%s+(.*)$") then
        NameRang = string.match(w, "^Работа / должность:%s+(.*)$")
        break
        end
        end
        print(NameRang)
    end)
end)
end
 
  • Нравится
Реакции: [SA ARZ]

[SA ARZ]

Известный
392
8
Lua:
function updateSystem()
lua_thread.create(function()
    sampSendChat('/mn')
    while not sampIsDialogActive() do wait(0) end
    wait(0)
    sampSetCurrentDialogListItem(0)
    wait(0)
    sampCloseCurrentDialogWithButton(1)
    lua_thread.create(function() wait(1000)
        text = sampGetDialogText()
        for w in text:gmatch('[^\r\n]+') do
        wait(0)
        if string.find(w, "^Работа / должность:%s+(.*)$") then
        NameRang = string.match(w, "^Работа / должность:%s+(.*)$")
        break
        end
        end
        print(NameRang)
    end)
end)
end
и так каждую строку мне if string.find(w, "^Работа / должность:%s+(.*)$") then если вытащить каждую строку инфу?
 

Fuexie

Известный
108
30
[ML] (error) IGFS: attempt to call a nil value
stack traceback:
stack traceback:
[C]: in function 'create'
C:\Games\San Andreas Multiplayer 0.3.7\moonloader\!igfs.lua:493: in function <C:\Games\San Andreas Multiplayer 0.3.7\moonloader\!igfs.lua:484>
[ML] (error) IGFS: Script died due to an error. (01B9313C)

Вот код.

Lua:
-----------------------------------------------
-- System of autoupdate
-----------------------------------------------
function checkUpdate()
    local fpath = os.getenv('TEMP') .. '\\igfs-version.json'
    downloadUrlToFile('https://raw.githubusercontent.com/InfernoGeek/igfs/master/version.json', fpath, function(id, status, p1, p2)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
        local f = io.open(fpath, 'r')
        if f then
            local info = decodeJson(f:read('*a'))
            local updatelink = info.donwloadUrl
            if info and info.latest then
                version = tonumber(info.latest)
                if version > tonumber(thisScript().version) then
                    lua_thread.create(downloadUpdate)
                else
                    checkUpdate = false
                end
            end
        end
    end
end)
end

function donwloadUpdate()
    sampLocalMes('{4326c1}[IgFs] {ffffff}Версия, установленная у вас устарела. Система авто-обновления автоматически установит актуальную.',-1)
    sampLocalMes('{4326c1}[IgFs] {ffffff}Версия, установленная у вас: ' ..thisScript().version.. '. Актуальная версия: ' ..version.. '.',-1)
    wait(300)
    downloadUrlToFile(updatelink, thisScript().path, function(id3, status1, p13, p23)
        if status1 == dlstatus.STATUS_ENDDOWNLOADDATA then
        sampLocalMes('{4326c1}[IgFs] {ffffff}Актуальная версия установлена.',-1)
        thisScript():reload()
    end
    end)
end
 

[SA ARZ]

Известный
392
8
Вот код.

Lua:
-----------------------------------------------
-- System of autoupdate
-----------------------------------------------
function checkUpdate()
    local fpath = os.getenv('TEMP') .. '\\igfs-version.json'
    downloadUrlToFile('https://raw.githubusercontent.com/InfernoGeek/igfs/master/version.json', fpath, function(id, status, p1, p2)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
        local f = io.open(fpath, 'r')
        if f then
            local info = decodeJson(f:read('*a'))
            local updatelink = info.donwloadUrl
            if info and info.latest then
                version = tonumber(info.latest)
                if version > tonumber(thisScript().version) then
                    lua_thread.create(downloadUpdate)
                else
                    checkUpdate = false
                end
            end
        end
    end
end)
end

function donwloadUpdate()
    sampLocalMes('{4326c1}[IgFs] {ffffff}Версия, установленная у вас устарела. Система авто-обновления автоматически установит актуальную.',-1)
    sampLocalMes('{4326c1}[IgFs] {ffffff}Версия, установленная у вас: ' ..thisScript().version.. '. Актуальная версия: ' ..version.. '.',-1)
    wait(300)
    downloadUrlToFile(updatelink, thisScript().path, function(id3, status1, p13, p23)
        if status1 == dlstatus.STATUS_ENDDOWNLOADDATA then
        sampLocalMes('{4326c1}[IgFs] {ffffff}Актуальная версия установлена.',-1)
        thisScript():reload()
    end
    end)
end


У тя тут lua_thread.create(downloadUpdate)
а в function donwloadUpdate() - другое название, из-за этого ошибка :)