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

_Nelit_

Потрачен
109
39
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Что делает флаг имгуи imgui.Cond.FirstUseEver
 

babyslammer

Новичок
7
2
кто знает как закрыть /stats на arz? Использую sampSendDialogResponse(dialogId, 0) но открываеться только инвентарь
 

#Northn

Police Helper «Reborn» — уже ШЕСТЬ лет!
Всефорумный модератор
2,637
2,487
можно, но не обязательно
если оставить пустым, то будет тот же эффект
1636916410083.png
 
  • Нравится
Реакции: _Nelit_

woodware

Потрачен
Проверенный
4,602
1,277
как сделать в этом скрипте меньше задержку на отправление объявления? подскажите пожалуйста строку
Lua:
script_name('NEWS-HELPER')
script_author("Serhiy_Rubin")

local inicfg, sampev, milisec, vkeys = require 'inicfg', require 'lib.samp.events', require 'socket', require 'lib.vkeys'
require 'lib.sampfuncs'
require 'lib.moonloader'
local antiflood = os.clock() * 1000 ; timer = os.clock() ; adid = 21 ; arrayAD = {} ; ad_check = 0

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    repeat wait(0) until sampGetCurrentServerName() ~= 'SA-MP'
    server = sampGetCurrentServerName():gsub('|', '')
    server = (server:find('02') and 'Two' or (server:find('Revolution') and 'Revolution' or (server:find('Legacy') and 'Legacy' or (server:find('Classic') and 'Classic' or (server:find('02') and 'Two' or (server:find('TEST') and 'Test' or '')) ))))
    if server == '' then thisScript():unload() end
    _, my_id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    my_nick = sampGetPlayerNickname(my_id)
    ini = inicfg.load({
        Settings = {
            send_number = 0,
            mili_time = 100,
            ad_cena = 100
        },
        Activation = {
            [my_nick] = false,
        },
        Auto = {
            [my_nick] = false,
        },
        Render = {
            FontName='Segoe UI',
            FontSize=10,
            FontFlag=15,
            Color='FFFFFF'
        },
        Pos = {
            X = 0,
            Y = 0
        },
        Key = {
            read = 'VK_1',
            send = 'VK_3',
            auto = 'VK_4',
            ad_list = 'VK_N',
            check_ad = 'VK_O'
        }
    })
    inicfg.save(ini)
    font = renderCreateFont(ini.Render.FontName, ini.Render.FontSize, ini.Render.FontFlag)
    -- Auto-Send settings
    last_send = tonumber(os.date("%S")) ; next_second = math.fmod(last_send + 16, 60) ; status = false
    if math.fmod(next_second, 2) ~= ini.Settings.send_number then
        next_second = next_second - 1
    end
    while true do
        wait(0)
        if ini.Activation[my_nick] then
            doAutoSend()
            doRender()
            doKeyCheck()
            doPos()
            doSetKey()
        end
    end
end

-- main
function doAutoSend()
    local this_second = tonumber(os.date("%S"))
    local this_milisecond = tonumber(tostring(milisec.gettime()):sub(12, 14))
    if this_milisecond ~= nil and this_milisecond ~= 999 and this_second  == next_second and this_milisecond > ini.Settings.mili_time then
        status = true
    end
    if ini.Auto[my_nick] and status and (os.clock() * 1000 - antiflood) > 1000 then
        sampSendChat("/adsend "..adid)
    end
end

function doRender()
    if sampIsScoreboardOpen() or not sampIsChatVisible() or isKeyDown(116) or isKeyDown(121) then return end
    local S1 = os.clock() * 1000
    local S2 = timer * 1000
    local S3 = (S1 - S2) / 1000
    local autot = (ini.Auto[my_nick] and '!' or '')
    local rttext = string.format("{%s}%s%0.1f", ini.Render.Color, autot, S3)
    renderFontDrawText(font, rttext, ini.Pos.X, ini.Pos.Y, 0xFFFFFFFF)
end

function doKeyCheck()
    if (not sampIsDialogActive() or (sampGetCurrentDialogType() ~= 1 and sampGetCurrentDialogType() ~= 3)) and not sampIsChatInputActive() then
        if wasKeyPressed(vkeys[ini.Key.read]) then
            sampSendChat("/adedit "..adid)
        end
        if wasKeyPressed(vkeys[ini.Key.send]) then
            sampSendChat("/adsend "..adid)
        end
        if wasKeyPressed(vkeys[ini.Key.auto]) then
            ini.Auto[my_nick] = not ini.Auto[my_nick]
            inicfg.save(ini)
        end
        if wasKeyPressed(vkeys[ini.Key.ad_list]) then
            list_ad = 1
            lua_thread.create(function()
                repeat
                    wait(0)
                    if list_ad == 1 and (os.clock() * 1000) - antiflood > 1100 then
                        list_ad = -1
                        sampSendChat('/n')
                    end
                until list_ad == 0
            end)
        end
        if wasKeyPressed(vkeys[ini.Key.check_ad]) then
            ad_check = 1
            lua_thread.create(function()
                repeat
                    wait(0)
                    if ad_check == 1 and (os.clock() * 1000) - antiflood > 1100 then
                        ad_check = -1
                        sampSendChat('/n')
                    end
                until ad_check == 0
            end)
        end
    end
end

function doPos()
    if setpos ~= nil then
        sampSetCursorMode(3)
        curX, curY = getCursorPos()
        ini.Pos.X = curX
        ini.Pos.Y = curY
        if isKeyJustPressed(1) then
            sampSetCursorMode(0)
            setpos = nil
            inicfg.save(ini)
        end
    end
end

function doSetKey()
    if setkey ~= nil then
        local key = ""
        for k, v in pairs(vkeys) do
            if wasKeyPressed(v) and k ~= "VK_ESCAPE" and k ~= "VK_RETURN" then
                key = k
            end
        end
        if key ~= '' then
            ini.Key[setkey] = key
            inicfg.save(ini)
            setkey = nil
            Dialog()
            start_dialog(dialog[1])  
        end
    end
end

-- HOOK

function sampev.onSendChat(message) antiflood = os.clock() * 1000 end
function sampev.onSendCommand(cmd) antiflood = os.clock() * 1000
    if cmd:lower() == "/nn" then
        lua_thread.create(function()
            Dialog()
            start_dialog(dialog[1])  
        end)
        return false
    end
end

function sampev.onServerMessage(color, message)
    if message:find("сотрудник News (.*): (.*)") and my_nick ~= nil then
        if message:find(my_nick) and ini.Auto[my_nick] then
            ini.Auto[my_nick] = false
            inicfg.save(ini)
        end
        last_send = tonumber(os.date("%S"))
        next_second = math.fmod(last_send + 16, 60)
        if math.fmod(next_second, 2) ~= ini.Settings.send_number then
            next_second = next_second - 1
        end
        timer = os.clock()
        status = false
    end
    if message:find('Добавлено новое объявление от .+. Номер объявления (%d+)') then
        local id = tonumber(message:match('Добавлено новое объявление от .+. Номер объявления (%d+)'))
        arrayAD[id] = nil
    end
    if status and message == " Объявления с таким ID не существует" or message == ' Объявление больше не существует' then
        status = false
    end
    if message == ' Не флуди!' then
        if ad_check == -1 then
            ad_check = 1
        end
        if list_ad == -1 then
            list_ad = 1
        end
    end
    if message == ' Вы не репортер' then
        ad_check = 0
        list_ad = 0
        ini.Auto[my_nick] = false
    end
end

function sampev.onShowDialog(dialogId, style, title, button1, button2, text)
    if title == 'Репортеры' and text:find('%[3%] Объявления') then -- Меню /n
        if ad_check == -1 then
            ad_check = 2
            ThreadSendDialog(90, dialogId, 1, 3, '[3] Объявления')
            lua_thread.create(function()
                checking, checkall = 0, 0
                repeat wait(0)
                    local text = 'Checking '..checking..'/'..checkall
                    local x, y = getScreenResolution()
                    x = x - renderGetFontDrawTextLength(font, text)
                    y = y - renderGetFontDrawHeight(font)
                    renderFontDrawText(font, text, x, y, -1)
                until ad_check == 0
            end)
            return false
        end
        if list_ad == -1 then
            list_ad = 0
            ThreadSendDialog(90, dialogId, 1, 3, '[3] Объявления')
            return false
        end
    end  
    if title == 'Объявления' and text:find('%[id: ') then -- Объявления
        local array = split(text, '\n')
        local dialogText = ''
        if ad_check == 2 then
            dialogArray = {}
        end
        for k,v in pairs(array) do
            local id = tonumber(v:match('%[id: (%d+)%]'))
            if id ~= nil then
                if ad_check == 2 and not v:find('Проверил') and arrayAD[id] == nil then
                    checkall = checkall + 1
                    dialogArray[#dialogArray + 1] = { text = v, list = k-1, id = id}
                end
                if arrayAD[id] ~= nil then
                    v = v:gsub('%[id', string.format('{59de00}[%s$]{FFFFFF} [id', arrayAD[id]))
                end
                dialogText = string.format('%s%s\n', dialogText, v)
            end
        end
        if ad_check == 2 then ad_check = -2 end
        if ad_check == -2 or ad_check == 3 then
            if dialogArray[#dialogArray] ~= nil then
                adstring = dialogArray[#dialogArray].text
                adid = dialogArray[#dialogArray].id
                ad_check = 3
                ThreadSendDialog(90, 22, 1, dialogArray[#dialogArray].list, adstring)
                dialogArray[#dialogArray] = nil
                return false
            else
                ad_check = 0
            end
        end
        return {dialogId, style, title, button1, button2, dialogText}
    end
    if title == 'Меню' and text:find('%[0%] Читать') then -- Меню редактировать, отправить
        ShowNewsMenu = 1
        if ad_check == 3 then
            ad_check = -3
            ThreadSendDialog(90, dialogId, 1, 0, '[0] Читать')
            return false
        end
        if ad_check == 4 then
            ad_check = -2
            ThreadSendDialog(90, dialogId, 0, 0, '[0] Читать')
            return false
        end
    end
    if title == 'Сообщение' or title == 'Ввод параметра' and ShowNewsMenu ~= nil then -- Диалог с текстом объявления
        ShowNewsMenu = nil
        if adstring ~= nil and not adstring:find('Проверил') then
            arrayAD[adid] = ((#text * ini.Settings.ad_cena) / 100) * 60
        end
        if ad_check == -3 then
            ad_check = 4
            checking = checking + 1
            ThreadSendDialog(90, dialogId, 0, 0, '')
            return false
        end
    end
end

function ThreadSendDialog(sleep, id, button, listitem, input)
    lua_thread.create(function(sleep, id, button, listitem, input)
        wait(sleep)
        sampSendDialogResponse(id, button, listitem, input)
    end, sleep, id, button, listitem, input)
end

function sampev.onSendDialogResponse(dialogId, button, listboxId, input)
    -- Получаем ID последнего открытого объявления.
    if string.find(sampGetDialogCaption(), "Объявления") and button == 1 then
        local array = split(sampGetDialogText(), '\n')
        for k,v in pairs(array) do
            if listboxId == (k - 1) then
                adid = tonumber(string.match(v, "%[id: (%d+)%]"))
                adstring = input
            end
        end
    end
end


-- Dialog
function Dialog()
dialog = {
    {
        settings = {title = "NEWS-HELPER" ,style = 4 ,btn1 = "Далее" ,btn2 = "Закрыть" ,forward =  "{ffffff}" ,backwards = "\n" ,score = true},
        {
            {
                title = "Таймер объявлений\t"..ON_OFF(ini.Activation[my_nick]),
                click = function(button, list, input , outs)
                    if button == 1 then
                        ini.Activation[my_nick] = not ini.Activation[my_nick]
                        inicfg.save(ini)
                        Dialog()
                        return dialog[1]  
                    end
                end
            },
            {
                title = "Сменить позицию таймера\t",
                click = function(button, list, input , outs)
                    if button == 1 then
                        setpos = 1
                        Dialog()
                        return dialog[1]  
                    end
                end
            },
            {
                title = "[AUTO] Условие 1\t"..(ini.Settings.send_number == 0 and 'Чётные' or 'Нечётные'),
                click = function(button, list, input , outs)
                    if button == 1 then
                        ini.Settings.send_number = (ini.Settings.send_number == 0 and 1 or 0)
                        inicfg.save(ini)
                        Dialog()
                        return dialog[1]  
                    end
                end
            },
            {
                title = "[AUTO] Условие 2\t"..ini.Settings.mili_time..' мс.',
                click = function(button, list, input , outs)
                    if button == 1 then
                        return dialog[2]  
                    end
                end
            },
            {
                title = "Кнопка для проверки\t"..ini.Key.read:gsub("VK_", ''),
                click = function(button, list, input , outs)
                    if button == 1 then
                        setkey = 'read'
                        sampShowDialog(584, "SET POS", "{FFFFFF}Нажмите на нужную клавишу", "Сохранить", "Назад", 0)
                    end
                end
            },
            {
                title = "Кнопка для отправки\t"..ini.Key.send:gsub("VK_", ''),
                click = function(button, list, input , outs)
                    if button == 1 then
                        setkey = 'send'
                        sampShowDialog(584, "SET POS", "{FFFFFF}Нажмите на нужную клавишу", "Сохранить", "Назад", 0)
                    end
                end
            },
            {
                title = "Кнопка для авто-отправки\t"..ini.Key.auto:gsub("VK_", ''),
                click = function(button, list, input , outs)
                    if button == 1 then
                        setkey = 'auto'
                        sampShowDialog(584, "SET POS", "{FFFFFF}Нажмите на нужную клавишу", "Сохранить", "Назад", 0)
                    end
                end
            },
            {
                title = "Кнопка для открытия списка объявлений\t"..ini.Key.ad_list:gsub("VK_", ''),
                click = function(button, list, input , outs)
                    if button == 1 then
                        setkey = 'ad_list'
                        sampShowDialog(584, "SET POS", "{FFFFFF}Нажмите на нужную клавишу", "Сохранить", "Назад", 0)
                    end
                end
            },
            {
                title = "Кнопка для проверки стоимости объявлений\t"..ini.Key.check_ad:gsub("VK_", ''),
                click = function(button, list, input , outs)
                    if button == 1 then
                        setkey = 'check_ad'
                        sampShowDialog(584, "SET POS", "{FFFFFF}Нажмите на нужную клавишу", "Сохранить", "Назад", 0)
                    end
                end
            },
        },
    },
    {
        settings = {title = "NEWS-TIMER" ,style = 1 ,btn1 = "Сохранить",btn2 = "Назад",forward =  "{ff0000}" ,backwards = "\n" ,score = false},
        {
            text = "{ffffff}Введите миллисекунды от 0 до 1000.",
            {
                click = function(button, list, input , outs)
                    if button == 0 then
                        return dialog[1]
                    else
                        sampAddChatMessage("Вы написали в диалог вот это: "..input, 0xffcecece)
                        if input:find('%d+') then
                            ini.Settings.mili_time = tonumber(input:match('%d+'))
                            inicfg.save(ini)
                            Dialog()
                            return dialog[1]
                        else
                            sampAddChatMessage("Ошибка. Введите число от 0 до 1000.", 0xffcecece)  
                            return dialog[2]
                        end
                    end
                end
            }
        }
    },
}
end

function ON_OFF(bool)
    return (bool and '{45d900}ON' or '{ff0000}OFF')
end

-- Function Dialog
function start_dialog(menu)
    function _dialog(menu, id,  outs)
        sampShowDialog(id, menu.settings.title, tbl_split(menu.settings.style, menu, menu.settings.forward ,menu.settings.backwards ,menu.settings.score), menu.settings.btn1, (menu.settings.btn2 ~= nil and menu.settings.btn2 or _), menu.settings.style)
            repeat
                wait(0)
                local result, button, list, input = sampHasDialogRespond(id)
                if result then
                    local out, outs = menu[((menu.settings.style == 0 or menu.settings.style == 1 or menu.settings.style == 3) and 1 or ((list + 1) > #menu[1] and 2 or 1))][((menu.settings.style == 0 or menu.settings.style == 1 or menu.settings.style == 3) and 1 or ((list + 1) > #menu[1] and (list - #menu[1]) + 1  or list + 1))].click(button, list, input, outs)
                    if type(out) == "table" then
                        return _dialog(out, id - 1, outs)
                    elseif type(out) == "boolean" then
                        if not out then
                            return out
                        end
                            return _dialog(menu, id, outs)
                    end
                end
            until result
    end

    function tbl_split(style, tbl, forward ,backwards ,score)
        if style == 2 or style == 4 or style == 5 then
            text = (style == 5 and tbl[1].text.."\n" or "")
            for i, val in ipairs(tbl[1]) do
                text = text..""..forward..""..(score and "["..i.."]{ffffff} " or "")..""..val.title..""..backwards
            end
            if tbl[2] ~= nil then
                for _, val in ipairs(tbl[2]) do
                    text = text..""..forward..""..val.title..""..backwards
                end
            end
            return text
        end
        return tbl[1].text
    end

    return _dialog(menu, 1337, outs)
end


--- Function split
function split(str, delim, plain)
    local tokens, pos, plain = {}, 1, not (plain == false) --[[ delimiter is plain text by default ]]
    repeat
        local npos, epos = string.find(str, delim, pos, plain)
        table.insert(tokens, string.sub(str, pos, npos and npos - 1))
        pos = epos and epos + 1
    until not pos
    return tokens
end
up
 

_Nelit_

Потрачен
109
39
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Каким образом можно обойти лицензию по серийному номеру жёсткого диска, если дата и жёсткий диск хранятся в май скьюл базе данных? Нужны способы, что бы можно было защитить скрипт

Сделал я автоматическую подгрузку библиотеки faIcons если это разрешит пользователь. Но скрипт даёт ошибку на этапе подключения скрипта faIcons.lua. Можно как то продолжить работу скрипта не обращая ошибку. Вот код

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

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

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

function imgui.OnDrawFrame()
        if download_faicons_window.v then
        imgui.SetNextWindowSize(imgui.ImVec2(300, 120), imgui.Cond.Always)
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.Always, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8'State-Assistant | ' .. u8(licenseType), confirm_off_window, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoScrollbar)

        imgui.CenterTextColoredRGB('У Вас отсутствует библиотека faIcons.lua')
        imgui.CenterTextColoredRGB('Скачать её прямо сейчас?')

        if imgui.Button(u8'Да', imgui.ImVec2(70, 25)) then
            downloadUrlToFile('https://license.s-studio.su/libs/faIcons.lua', getWorkingDirectory()..'/lib/faIcons.lua', function(id, status)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                    sampAddChatMessage(tag .. 'Установлено 1/2 файлов', mc)

                    if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                        downloadUrlToFile('https://license.s-studio.su/libs/fontawesome-webfont.ttf', getWorkingDirectory()..'/resource/fontawesome-webfont.ttf', function(id, status)
                            sampAddChatMessage(tag .. 'Установка завершена!', mc)
                        end)
                    end
                end
            end)
        end
        imgui.SameLine(160)
        if imgui.Button(u8'Нет', imgui.ImVec2(70, 25)) then
            confirm_off_window.v = false
            main_window.v = not main_window.v
        end

        imgui.End()
    end
end

function downloadFaicons()
    print('[ Проверка на наличие faIcons.lua... ]')
    if doesFileExist(getWorkingDirectory()..'/lib/faIcons.lua') and doesFileExist(getWorkingDirectory()..'/resource/fonts/fontawesome-webfont.ttf') then
        print('[ faIcons.lua найдена... ]')
    else
        download_faicons_window.v = not download_faicons_window.v
    end
end
 
Последнее редактирование:

Rice.

Известный
Модератор
1,698
1,466
Последнее редактирование:

_Nelit_

Потрачен
109
39
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Каким образом можно обойти лицензию по серийному номеру жёсткого диска, если дата и жёсткий диск хранятся в май скьюл базе данных? Нужны способы, что бы можно было защитить скрипт

Сделал я автоматическую подгрузку библиотеки faIcons если это разрешит пользователь. Но скрипт даёт ошибку на этапе подключения скрипта faIcons.lua. Можно как то продолжить работу скрипта не обращая ошибку. Вот код

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

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

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

function imgui.OnDrawFrame()
        if download_faicons_window.v then
        imgui.SetNextWindowSize(imgui.ImVec2(300, 120), imgui.Cond.Always)
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.Always, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8'State-Assistant | ' .. u8(licenseType), confirm_off_window, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoScrollbar)

        imgui.CenterTextColoredRGB('У Вас отсутствует библиотека faIcons.lua')
        imgui.CenterTextColoredRGB('Скачать её прямо сейчас?')

        if imgui.Button(u8'Да', imgui.ImVec2(70, 25)) then
            downloadUrlToFile('https://license.s-studio.su/libs/faIcons.lua', getWorkingDirectory()..'/lib/faIcons.lua', function(id, status)
                if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                    sampAddChatMessage(tag .. 'Установлено 1/2 файлов', mc)

                    if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                        downloadUrlToFile('https://license.s-studio.su/libs/fontawesome-webfont.ttf', getWorkingDirectory()..'/resource/fontawesome-webfont.ttf', function(id, status)
                            sampAddChatMessage(tag .. 'Установка завершена!', mc)
                        end)
                    end
                end
            end)
        end
        imgui.SameLine(160)
        if imgui.Button(u8'Нет', imgui.ImVec2(70, 25)) then
            confirm_off_window.v = false
            main_window.v = not main_window.v
        end

        imgui.End()
    end
end

function downloadFaicons()
    print('[ Проверка на наличие faIcons.lua... ]')
    if doesFileExist(getWorkingDirectory()..'/lib/faIcons.lua') and doesFileExist(getWorkingDirectory()..'/resource/fonts/fontawesome-webfont.ttf') then
        print('[ faIcons.lua найдена... ]')
    else
        download_faicons_window.v = not download_faicons_window.v
    end
end
Ап
 

samuraiJT

Новичок
2
0
В чём проблема хотел написать скрипт на LUA но не получилось где ошибка
Lua:
require "lib.moonloader"
loca keys = require "vkeys"
function main () 
    if not isSampLoaded () or not isSampLoaded()
    then return
     end
  while not isSampAvailable ()
end
    sampAddChatMessage ('Скрипт успешно запущен запуск /helper', 0xF8F8FF) 
    while true
    wait true
    vait (0)
    and isKeyJustPressed (VK_9)
    then
    sampSendChat ("/ot")
end 
    ifKeyJustFressed (VK_M)
    then
    sampSendChat ("style")
     end
   end 
end
 
Последнее редактирование модератором:

_Nelit_

Потрачен
109
39
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
В чём проблема хотел написать скрипт на LUA но не получилось где ошибка
Lua:
require "lib.moonloader"
loca keys = require "vkeys"
function main ()
    if not isSampLoaded () or not isSampLoaded()
    then return
     end
  while not isSampAvailable ()
end
    sampAddChatMessage ('Скрипт успешно запущен запуск /helper', 0xF8F8FF)
    while true
    wait true
    vait (0)
    and isKeyJustPressed (VK_9)
    then
    sampSendChat ("/ot")
end
    ifKeyJustFressed (VK_M)
    then
    sampSendChat ("style")
     end
   end
end
Lua:
require "lib.moonloader"

local keys = require "vkeys"

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

    sampAddChatMessage ('Скрипт успешно запущен запуск /helper', 0xF8F8FF)

    while true do
        wait(0)

        if isKeyJustPressed (VK_9) then
            sampSendChat ("/ot")
        elseif isKeyJustPressed (VK_M) then
            sampSendChat ("style")
        end

    end
end

На луа наверное не твоё писать.
 

auf.exe

Участник
40
12
Вот код:
require 'lib.moonloader'

local rk = require 'rkeys'
local imgui = require 'imgui'
local sampev = require 'lib.samp.events'
local vk = require 'vkeys'
local imadd = require 'imgui_addons'
local inicfg = require 'inicfg'
local noctf = import 'imgui_notf.lua'
local directini = 'moonloader\\settings.ini'
imgui.HotKey = require('imgui_addons').HotKey


local mainini = inicfg.load(nil, directini)

if mainini.HotKey == nil then
    mainini.HotKey = {
        bind1 = "[18, 82]",
        bind2 = "[18, 83]"
    }
end

local tLastKeys = { }

local ActiveClockKeys = {
    v = decodeJson(mainini.HotKey.bind1)
}
local ActiveClockKeys2 = {
    v = decodeJson(mainini.HotKey.bind2)
}

local main_window = imgui.ImBool(false)
local textbuffer = imgui.ImBuffer(256)
local textbuffer2 = imgui.ImBuffer(256)

local sw, sr = getScreenResolution()

function main()
    while not isSampAvailable() do wait(0) end
    sampAddChatMessage('qq Binder tuta', -1)
    sampRegisterChatCommand('Lox', imgui1)

    bindClock = rk.registerHotKey(ActiveClockKeys, true, bind)
    bindClock1 = rk.registerHotKey(ActiveClockKeys2, true, bind2)

    while true do
        wait(0)
        if isKeyJustPressed(VK_M) then
            main_window.v = not main_window.v
            imgui.Process = main_window.v
        end
    end
end

function bind()
    sampSendChat(textbuffer.v)
    noctf.addNotifon("Задача выполнена!", 5, 3)
end
function bind2()
    sampSendChat(textbuffer2.v)
    noctf.addNotifon("Задача выполнена!", 5, 3)
end

function imgui.OnDrawFrame()

    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sr / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(300, 250), imgui.Cond.FirstUseEver)

    if not main_window.v then
        imgui.Process = false
    end
    imgui.Begin("Binder by auf.exe", main_window)

   

    if imgui.HotKey('##2', ActiveClockKeys, tLastKeys, 100) then
        rk.changeHotKey(bindClock2, ActiveClockKeys.v)
        mainini.HotKey.bind1 = encodeJson(ActiveClockKeys.v)
        mainini.HotKey.bind2 = encodeJson(ActiveClockKeys.v)
        inicfg.save(mainini, directini)
    end
    imgui.SameLine()
    imgui.InputText('Some Text', textbuffer)
    imgui.Separator()
    if imgui.HotKey('##2', ActiveClockKeys2, tLastKeys, 100) then
        rk.changeHotKey(bindClock2, ActiveClockKeys.v)
        mainini.HotKey.bind1 = encodeJson(ActiveClockKeys.v)
        mainini.HotKey.bind2 = encodeJson(ActiveClockKeys2.v)
        inicfg.save(mainini, directini)
    end
    imgui.SameLine()
    imgui.InputText('Bind 2', textbuffer2)
   
    mainini.HotKey.bind1 = encodeJson(ActiveClockKeys.v)
    mainini.HotKey.bind2 = encodeJson(ActiveClockKeys2.v)
    inicfg.save(mainini, directini)
    imgui.End()
end
Блять скрипт работает хоткеи меняются но НЕ выполняется задача.Пашет дальше не криашит, но хоткеи не выполняются
Помогити!!
 

eqzzz

Участник
126
19
Приветствую, помогите.
SMOOTH AIMBOT работает, но после того, как я сделал сохранение inicfg, он перестал работать. Никакие ошибки не выдает, просто доводит, остальные функции, которые также взаимодействованы с inicfg работают. Что это может быть вообще?