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

hol0s

Участник
152
23
а как сделать когда у чела в руках дигл чтобы менялась картинка (и другие оружия)
 

хромиус)

спокойно, это всего лишь слива
Друг
4,950
3,226
а как сделать когда у чела в руках дигл чтобы менялась картинка (и другие оружия)
Тебе же сверху скинули функцию получения номера оружия,смотришь номер и по нему сравниваешь епта
 

Corrygan228

Участник
132
9
В чем ошибка? Отправляется просто команда /invite без id
Мне надо, чтобы после отправки инпут очистился
Lua:
if imgui.BeginPopupModal('##invite_human', _, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove) then
    imgui.SetNextWindowSize(imgui.ImVec2(350, 150))
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.CenterText(u8'Введите ID игрока, которого хотите принять.')
    imgui.SetCursorPosX((350-90)/2)
    imgui.PushItemWidth(90)
    imgui.InputText(u8'##ID', invite_id)
    imgui.PopItemWidth()
    imgui.NewLine()
    imgui.SetCursorPosX(35)
    if imgui.Button(u8'Принять', imgui.ImVec2(120, 30)) then
        if invite_id.v == '' then
            imgui.CloseCurrentPopup()
            sampAddChatMessage('{0099FF}[Prison Helper]:' .. white_color .. ' Вы не ввели ID!', -1)
        else
            imgui.CloseCurrentPopup()
            lua_thread.create(function()
                wait(1500)
                sampAddChatMessage('Вы нам подходите!', -1)
                wait(1500)
                sampAddChatMessage('/do В руках пакет с формой и ключом от шкафчика.', -1)
                wait(1500)
                sampAddChatMessage('/todo Передав пакет с формой*Можете приступать к работе', -1)
                wait(1500)
                sampAddChatMessage('/invite ' .. invite_id.v, -1) --тут ошибка
            end)
            invite_id.v = ''
        end
    end
    imgui.SameLine()
    imgui.SetCursorPosX(194)
    if imgui.Button(u8'Отмена', imgui.ImVec2(120, 30)) then
        imgui.CloseCurrentPopup()
    end
    imgui.EndPopup()
end
 
Последнее редактирование:

percheklii

Известный
737
275
Снова я...
Почему не показывает дистанцию когда игрок получает урон, за которым в спеке?
Хотя когда наношу урон, все показывает правильно...
EE9POYv.png


Lua:
local ev = require("samp.events")
local weap = require("game.weapons")

local spectatedPlayerId = nil
local damagelist = {}

function ev.onSpectatePlayer(playerId)
    spectatedPlayerId = playerId
end

local posY = 200

local weapons = {
    [0] = "Fist", "Brass Knuckles", "Golf Club", "Nightstick", "Knife", "Baseball Bat", "Shovel", "Pool Cue", "Katana", "Chainsaw",
    "Purple Dildo", "Dildo", "Vibrator", "Vibrator", "Flowers", "Cane", "Grenade", "Tear Gas", "Molotov", "", "", "",
    "9m", "Silenced 9mm", "Desert Eagle", "Shotgun", "Sawnoff Shotgun", "Combat Shotgun", "Micro Uzi", "MP5", "AK-47", "M4",
    "Tec-9", "Country Rifle", "Sniper Rifle", "RPG", "HS Rocket", "Flamethrower", "Minigun", "Satchel Charge", "Detonator",
    "Spraycan", "Extinguisher"
}

function ev.onBulletSync(playerId, data)
    if spectatedPlayerId and ((spectatedPlayerId == playerId and data.targetType == 1) or (data.targetId == spectatedPlayerId and data.targetType == 1)) then
        local nameT, nameP = sampGetPlayerNickname(data.targetId), sampGetPlayerNickname(playerId)
        local in_stream, TPED = sampGetCharHandleBySampPlayerId(data.targetId)

        if in_stream then
            local x, y, z = getCharCoordinates(TPED)
            local result, ped = sampGetCharHandleBySampPlayerId(spectatedPlayerId)
            local mX, mY, mZ = getCharCoordinates(ped)
            local dist = getDistanceBetweenCoords3d(x, y, z, mX, mY, mZ)

            if result then
                local damageInfo = (spectatedPlayerId == playerId) and
                    string.format("{30FF30}%s[%d] {F0F0F0}нанёс урон {FF3030}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм", nameP, playerId, nameT, data.targetId, weapons[data.weaponId], math.floor(dist)) or
                    string.format("{FF3030}%s[%d] {F0F0F0}получил урон {30FF30}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм", nameT, data.targetId, nameP, playerId, weapons[data.weaponId], math.floor(dist))

                table.insert(damagelist, { damageInfo = damageInfo })

                if #damagelist > 10 then
                    table.remove(damagelist, 1)
                end
            end
        end
    end
end

function main()
    local font = renderCreateFont("Arial", 10, 13)
    while true do
        wait(0)
        local pos = posY
        for i = 1, #damagelist do
            renderFontDrawText(font, i .. damagelist[i]["damageInfo"], 10, pos, 0xFFFFFFFF)
            pos = pos - renderGetFontDrawHeight(font)
        end
    end
end
 

Andrinall

Известный
681
532
В чем ошибка? Отправляется просто команда /invite без id
Мне надо, чтобы после отправки инпут очистился
Lua:
if imgui.BeginPopupModal('##invite_human', _, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove) then
    imgui.SetNextWindowSize(imgui.ImVec2(350, 150))
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.CenterText(u8'Введите ID игрока, которого хотите принять.')
    imgui.SetCursorPosX((350-90)/2)
    imgui.PushItemWidth(90)
    imgui.InputText(u8'##ID', invite_id)
    imgui.PopItemWidth()
    imgui.NewLine()
    imgui.SetCursorPosX(35)
    if imgui.Button(u8'Принять', imgui.ImVec2(120, 30)) then
        if invite_id.v == '' then
            imgui.CloseCurrentPopup()
            sampAddChatMessage('{0099FF}[Prison Helper]:' .. white_color .. ' Вы не ввели ID!', -1)
        else
            imgui.CloseCurrentPopup()
            lua_thread.create(function()
                wait(1500)
                sampAddChatMessage('Вы нам подходите!', -1)
                wait(1500)
                sampAddChatMessage('/do В руках пакет с формой и ключом от шкафчика.', -1)
                wait(1500)
                sampAddChatMessage('/todo Передав пакет с формой*Можете приступать к работе', -1)
                wait(1500)
                sampAddChatMessage('/invite ' .. invite_id.v, -1) --тут ошибка
            end)
            invite_id.v = ''
        end
    end
    imgui.SameLine()
    imgui.SetCursorPosX(194)
    if imgui.Button(u8'Отмена', imgui.ImVec2(120, 30)) then
        imgui.CloseCurrentPopup()
    end
    imgui.EndPopup()
end
Ну так очищай его после отправки, а не сразу после запуска потока)
Прикол в том, что поток после запуска работает параллельно и, следовательно, у тебя очищается раньше, чем отправляется.
(invite_id.v = '' перекинь в поток после отправки /invite)

Снова я...
Почему не показывает дистанцию когда игрок получает урон, за которым в спеке?
Хотя когда наношу урон, все показывает правильно...
EE9POYv.png


Lua:
local ev = require("samp.events")
local weap = require("game.weapons")

local spectatedPlayerId = nil
local damagelist = {}

function ev.onSpectatePlayer(playerId)
    spectatedPlayerId = playerId
end

local posY = 200

local weapons = {
    [0] = "Fist", "Brass Knuckles", "Golf Club", "Nightstick", "Knife", "Baseball Bat", "Shovel", "Pool Cue", "Katana", "Chainsaw",
    "Purple Dildo", "Dildo", "Vibrator", "Vibrator", "Flowers", "Cane", "Grenade", "Tear Gas", "Molotov", "", "", "",
    "9m", "Silenced 9mm", "Desert Eagle", "Shotgun", "Sawnoff Shotgun", "Combat Shotgun", "Micro Uzi", "MP5", "AK-47", "M4",
    "Tec-9", "Country Rifle", "Sniper Rifle", "RPG", "HS Rocket", "Flamethrower", "Minigun", "Satchel Charge", "Detonator",
    "Spraycan", "Extinguisher"
}

function ev.onBulletSync(playerId, data)
    if spectatedPlayerId and ((spectatedPlayerId == playerId and data.targetType == 1) or (data.targetId == spectatedPlayerId and data.targetType == 1)) then
        local nameT, nameP = sampGetPlayerNickname(data.targetId), sampGetPlayerNickname(playerId)
        local in_stream, TPED = sampGetCharHandleBySampPlayerId(data.targetId)

        if in_stream then
            local x, y, z = getCharCoordinates(TPED)
            local result, ped = sampGetCharHandleBySampPlayerId(spectatedPlayerId)
            local mX, mY, mZ = getCharCoordinates(ped)
            local dist = getDistanceBetweenCoords3d(x, y, z, mX, mY, mZ)

            if result then
                local damageInfo = (spectatedPlayerId == playerId) and
                    string.format("{30FF30}%s[%d] {F0F0F0}нанёс урон {FF3030}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм", nameP, playerId, nameT, data.targetId, weapons[data.weaponId], math.floor(dist)) or
                    string.format("{FF3030}%s[%d] {F0F0F0}получил урон {30FF30}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм", nameT, data.targetId, nameP, playerId, weapons[data.weaponId], math.floor(dist))

                table.insert(damagelist, { damageInfo = damageInfo })

                if #damagelist > 10 then
                    table.remove(damagelist, 1)
                end
            end
        end
    end
end

function main()
    local font = renderCreateFont("Arial", 10, 13)
    while true do
        wait(0)
        local pos = posY
        for i = 1, #damagelist do
            renderFontDrawText(font, i .. damagelist[i]["damageInfo"], 10, pos, 0xFFFFFFFF)
            pos = pos - renderGetFontDrawHeight(font)
        end
    end
end
По ощущениям я почти нифига не поменял, но у меня показывает в обе стороны дистанцию.
И зачем тебе отдельная таблица с названиями ганов, если можно local weapons = require('game.weapons').names ?
Lua:
function ev.onBulletSync(playerId, data)
    if not spectatedPlayerId or data.targetType ~= 1 then return true end
   
    local nameT, nameP = sampGetPlayerNickname(data.targetId), sampGetPlayerNickname(playerId)
    local in_stream, TPED = sampGetCharHandleBySampPlayerId(data.targetId)
    if not in_stream then return true end

    local x, y, z = getCharCoordinates(TPED)
    local result, ped = sampGetCharHandleBySampPlayerId(playerId)
    if not result then return true end
   
    local mX, mY, mZ = getCharCoordinates(ped)
    local dist = getDistanceBetweenCoords3d(x, y, z, mX, mY, mZ)

    local damageInfo = (spectatedPlayerId == playerId) and
        ("{30FF30}%s[%d] {F0F0F0}нанёс урон {FF3030}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм"):format(nameP, playerId, nameT, data.targetId, weapons[data.weaponId], math.floor(dist)) or
        ("{FF3030}%s[%d] {F0F0F0}получил урон {30FF30}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм"):format(nameT, data.targetId, nameP, playerId, weapons[data.weaponId], math.floor(dist))

    table.insert(damagelist, { damageInfo = damageInfo })

--    sampAddChatMessage(damageInfo, -1)

    if #damagelist > 10 then
        table.remove(damagelist, 1)
    end
end
1702572229904.png
 
Последнее редактирование:
  • Влюблен
Реакции: percheklii

percheklii

Известный
737
275
Ну так очищай его после отправки, а не сразу после запуска потока)
Прикол в том, что поток после запуска работает параллельно и, следовательно, у тебя очищается раньше, чем отправляется.
(invite_id.v = '' перекинь в поток после отправки /invite)


По ощущениям я почти нифига не поменял, но у меня показывает в обе стороны дистанцию.
И зачем тебе отдельная таблица с названиями ганов, если можно local weapons = require('game.weapons').names ?
Lua:
function ev.onBulletSync(playerId, data)
    if not spectatedPlayerId or data.targetType ~= 1 then return true end
  
    local nameT, nameP = sampGetPlayerNickname(data.targetId), sampGetPlayerNickname(playerId)
    local in_stream, TPED = sampGetCharHandleBySampPlayerId(data.targetId)
    if not in_stream then return true end

    local x, y, z = getCharCoordinates(TPED)
    local result, ped = sampGetCharHandleBySampPlayerId(playerId)
    if not result then return true end
  
    local mX, mY, mZ = getCharCoordinates(ped)
    local dist = getDistanceBetweenCoords3d(x, y, z, mX, mY, mZ)

    local damageInfo = (spectatedPlayerId == playerId) and
        ("{30FF30}%s[%d] {F0F0F0}нанёс урон {FF3030}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм"):format(nameP, playerId, nameT, data.targetId, weapons[data.weaponId], math.floor(dist)) or
        ("{FF3030}%s[%d] {F0F0F0}получил урон {30FF30}%s[%d]{F0F0F0}. Оружие: {303030}%s. {F0F0F0}Дистанция: {03FF03}%sм"):format(nameT, data.targetId, nameP, playerId, weapons[data.weaponId], math.floor(dist))

    table.insert(damagelist, { damageInfo = damageInfo })

--    sampAddChatMessage(damageInfo, -1)

    if #damagelist > 10 then
        table.remove(damagelist, 1)
    end
end
Посмотреть вложение 224571
бля, спасибо просто лучший, а насчет стандартного шаблона оружия я подключал его но не правильно, сейчас все ок, вот я...
 

Corrygan228

Участник
132
9
пытался сделать биндер
подскажите, почему отправляются какие-то иероглифы, вместо моего текста(даже в json файл оно сохраняется не правильно)
1702578128681.png

Lua:
require 'lib.moonloader'
local imgui = require 'imgui'
local encoding = require 'encoding'
local vkeys = require 'vkeys'
local u8                    = encoding.UTF8
encoding.default            = "CP1251"

local function createNewJsonTable(table)
    if not doesFileExist(getWorkingDirectory().."\\config\\"..table[2]..".json") then
           local f = io.open(getWorkingDirectory().."\\config\\"..table[2]..".json", 'w+')
           if f then
              f:write(encodeJson(table[1])):close()
        end
       else
           local f = io.open(getWorkingDirectory().."\\config\\"..table[2]..".json", "r")
           if f then
             table[1] = decodeJson(f:read("*a"))
             f:close()
           end
    end
end

local switch = 0

local J_ = {
       BINDER = {
        {
            {
                name = "Приветствие",
                multiline = "Write here",
                command = "firstcmd",
                hotkey = 0x61,
                activation = 0
            }
        }, "SETTINGS_FORMS" }
}

createNewJsonTable(J_.BINDER)

local buffer = {}

for k, v in ipairs(J_.BINDER[1]) do
    table.insert(buffer, {
        name = imgui.ImBuffer(tostring(v.name), 100),
        multiline = imgui.ImBuffer(tostring(v.multiline), 1024),
        command = imgui.ImBuffer(tostring(v.command), 50),
        old_command = "",
        activation = imgui.ImInt(v.activation),
        hotkey = v.hotkey
    })
end

for k,v in ipairs(buffer) do
    v.old_command = u8:encode(v.command.v)
end

local window = imgui.ImBool(false)   

function main()
    while not isSampLoaded() do wait(100) end
    temp_buffer = {
        name = imgui.ImBuffer(100),
        multiline = imgui.ImBuffer(1024),
        command = imgui.ImBuffer(50),
        activation = imgui.ImInt(0),
        hotkey = 0x61,
        arr_hotkey = {
            name = vkeys.key_names[0x61], edit = false, ticked = os.clock(), tickedState = false, sName = ""
        }
    }
    sampRegisterChatCommand('test', function()
        window.v = not window.v
    end)
    for k,v in ipairs(buffer) do
        if v.activation.v == 1 then
            sampRegisterChatCommand(u8:decode(v.command.v), function()
                for text in u8:encode(v.multiline.v):gmatch("[^\r\n]+") do 
                    lua_thread.create(function()
                        sampSendChat(text)
                        wait(1000)
                    end)
                end     
            end)
        end
    end
    hotkeys = {}
    for k,v in ipairs(buffer) do
        table.insert(hotkeys, {
            name = vkeys.key_names[v.hotkey], edit = false, ticked = os.clock(), tickedState = false, sName = v.name.v
        })
    end
    while true do wait(0)
        imgui.Process = true
        if not window.v then
            imgui.ShowCursor = false
        end
        for k,v in ipairs(buffer) do
            if isKeyJustPressed(v.hotkey) then
                for text in u8:encode(v.multiline.v):gmatch("[^\r\n]+") do 
                    sampSendChat(text)
                    wait(1000)
                end     
            end
        end
    end
end

function imgui.OnDrawFrame()
    if window.v then
        imgui.ShowCursor = true
        imgui.SetNextWindowPos(imgui.ImVec2(imgui.GetIO().DisplaySize.x / 2, imgui.GetIO().DisplaySize.y / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(600, 300), imgui.Cond.FirstUseEver)
        imgui.Begin("Test", window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoScrollbar)
        imgui.BeginChild("##1", imgui.ImVec2(100, 100), true)
        for k,v in ipairs(buffer) do
            if imgui.Button(u8(v.name.v), imgui.ImVec2(74, 24)) then
                switch = k
            end
        end
        if imgui.Button(u8"Добавить", imgui.ImVec2(74, 24)) then
            imgui.OpenPopup(u8"Добавить кнопку")
        end
        if imgui.BeginPopupModal(u8"Добавить кнопку", _, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove) then
            imgui.PushItemWidth(150)
            imgui.InputText(u8"Введите текст", temp_buffer.name)
            imgui.Combo(u8"Выберите активацию", temp_buffer.activation, {u8"На кнопку", u8"На команду"})
            if temp_buffer.activation.v == 1 then
                imgui.InputText(u8"command", temp_buffer.command)
            else
                if temp_buffer.arr_hotkey.edit then
                    local downKey = getDownKeys()
                    temp_buffer.hotkey = downKey
                    if downKey == '' then
                        if os.clock() - temp_buffer.arr_hotkey.ticked > 0.5 then
                            temp_buffer.arr_hotkey.ticked = os.clock()
                            temp_buffer.arr_hotkey.tickedState = not temp_buffer.arr_hotkey.tickedState
                        end
                        temp_buffer.arr_hotkey.name = temp_buffer.arr_hotkey.tickedState and "No" or "##isNo "..temp_buffer.arr_hotkey.ticked
                    else
                        temp_buffer.arr_hotkey.name = vkeys.key_names[temp_buffer.hotkey]
                        temp_buffer.arr_hotkey.edit = false
                        save()
                    end
                end
                if imgui.Button(u8(tostring(temp_buffer.hotkey == nil and "##asdasd" or temp_buffer.arr_hotkey.name.."##asdasd")), imgui.ImVec2(110, 0)) then
                    temp_buffer.arr_hotkey.edit = true
                end imgui.SameLine() imgui.Text(u8(temp_buffer.arr_hotkey.sName))
            end
            imgui.PopItemWidth()
            if imgui.Button(u8"Сохранить", imgui.ImVec2(100, 0)) then
                if temp_buffer.activation.v == 1 then
                    if temp_buffer.command.v == "" then
                        sampAddChatMessage("write command", -1)
                    else
                        if temp_buffer.name.v ~= "" then
                            sampAddChatMessage(u8:decode(temp_buffer.name.v), -1)
                            table.insert(J_.BINDER[1], {
                                name = tostring(u8:decode(temp_buffer.name.v)),
                                multiline = temp_buffer.multiline.v,
                                activation = temp_buffer.activation.v,
                                command = temp_buffer.command.v,
                                hotkey = temp_buffer.hotkey
                            })
                            table.insert(buffer, {
                                name = imgui.ImBuffer(tostring(u8:decode(temp_buffer.name.v)), 100),
                                multiline = imgui.ImBuffer(tostring(temp_buffer.multiline.v), 1024),
                                activation = imgui.ImInt(temp_buffer.activation.v),
                                old_command = "",
                                command = imgui.ImBuffer(tostring(temp_buffer.command.v), 50),
                                hotkey = temp_buffer.hotkey
                            })
                            save()
                            buffer[#buffer].old_command = u8:encode(buffer[#buffer].command.v)
                            sampRegisterChatCommand(temp_buffer.command.v, function()
                                for text in u8:encode(temp_buffer.multiline.v):gmatch("[^\r\n]+") do 
                                    lua_thread.create(function()
                                        sampSendChat(text)
                                        wait(1000)
                                    end)
                                end     
                            end)
                            temp_buffer = {
                                name = imgui.ImBuffer(100),
                                multiline = imgui.ImBuffer(1024),
                                command = imgui.ImBuffer(50),
                                activation = imgui.ImInt(0),
                                hotkey = 0x61,
                                arr_hotkey = {
                                    name = vkeys.key_names[0x61], edit = false, ticked = os.clock(), tickedState = false, sName = ""
                                }
                            }
                            table.insert(hotkeys, {
                                name = vkeys.key_names[buffer[#buffer].hotkey], edit = false, ticked = os.clock(), tickedState = false, sName = buffer[#buffer].name.v
                            })
                            imgui.CloseCurrentPopup()
                        else
                            sampAddChatMessage("name is clean", -1)
                        end
                    end
                else
                    if temp_buffer.hotkey >= 0 then
                        table.insert(J_.BINDER[1], {
                            name = temp_buffer.name.v,
                            multiline = temp_buffer.multiline.v,
                            activation = temp_buffer.activation.v,
                            command = temp_buffer.command.v,
                            hotkey = temp_buffer.hotkey
                        })
                        table.insert(buffer, {
                            name = imgui.ImBuffer(tostring(temp_buffer.name.v), 100),
                            multiline = imgui.ImBuffer(tostring(temp_buffer.multiline.v), 1024),
                            activation = imgui.ImInt(temp_buffer.activation.v),
                            old_command = "",
                            command = imgui.ImBuffer(tostring(temp_buffer.command.v), 50),
                            hotkey = temp_buffer.hotkey
                        })
                        save()
                        temp_buffer = {
                            name = imgui.ImBuffer(100),
                            multiline = imgui.ImBuffer(1024),
                            command = imgui.ImBuffer(50),
                            activation = imgui.ImInt(0),
                            hotkey = 0x61,
                            arr_hotkey = {
                                name = vkeys.key_names[0x61], edit = false, ticked = os.clock(), tickedState = false, sName = ""
                            }
                        }
                        table.insert(hotkeys, {
                            name = vkeys.key_names[buffer[#buffer].hotkey], edit = false, ticked = os.clock(), tickedState = false, sName = buffer[#buffer].name.v
                        })
                        imgui.CloseCurrentPopup()
                    else
                        sampAddChatMessage("choose button", -1)
                    end
                end
            end
            imgui.SameLine()
            if imgui.Button(u8"Закрыть", imgui.ImVec2(100, 0)) then
                imgui.CloseCurrentPopup()
            end
            imgui.EndPopup()
        end
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginChild("##2", imgui.ImVec2(200, 200), true)
        for k,v in ipairs(buffer) do
            if k == switch then
                if imgui.Combo("##choose", v.activation, {u8"На кнопку", u8"На команду"}) then
                    J_.BINDER[1][k].activation = v.activation.v
                    save()
                end
                if imgui.InputTextMultiline("##multiline", v.multiline, imgui.ImVec2(150, 50)) then
                    J_.BINDER[1][k].multiline = v.multiline.v
                    save()
                end
                if v.activation.v == 0 then 
                    if hotkeys[k].edit then
                        local downKey = getDownKeys()
                        J_.BINDER[1][k].hotkey = downKey
                        if downKey == '' then
                            if os.clock() - hotkeys[k].ticked > 0.5 then
                                hotkeys[k].ticked = os.clock()
                                hotkeys[k].tickedState = not hotkeys[k].tickedState
                            end
                            hotkeys[k].name = hotkeys[k].tickedState and "No" or "##isNo "..hotkeys[k].ticked
                        else
                            hotkeys[k].name = vkeys.key_names[J_.BINDER[1][k].hotkey]
                            hotkeys[k].edit = false
                            save()
                        end
                    end
                    if imgui.Button(u8(tostring(J_.BINDER[1][k].hotkey == nil and "##"..k or hotkeys[k].name.."##"..k)), imgui.ImVec2(110, 0)) then
                        hotkeys[k].edit = true
                    end imgui.SameLine() imgui.Text(u8:encode(hotkeys[k].sName))
                else
                    if imgui.InputText(u8"command", v.command) then
                        J_.BINDER[1][k].command = v.command.v
                        save()
                        sampUnregisterChatCommand(v.old_command)
                        sampRegisterChatCommand(v.command.v, function()
                            for text in u8:encode(v.multiline.v):gmatch("[^\r\n]+") do 
                                lua_thread.create(function()
                                    sampSendChat(text)
                                    wait(1000)
                                end)
                            end     
                        end)
                        v.old_command = v.command.v
                    end     
                end
                if imgui.Button(u8"Удалить", imgui.ImVec2(90, 0)) then
                    table.remove(buffer, k)
                    table.remove(J_.BINDER[1], k)
                    save()
                end
            end
        end
        imgui.EndChild()
        imgui.End()
    end
end

function getDownKeys()
    local curkeys = ""
    local bool = false
    for k,v in pairs(vkeys) do
        if isKeyDown(v) then
            curkeys = v
            bool = true
        end
    end
    return curkeys, bool
end

function save()
    for k,v in pairs(J_) do
        if doesFileExist(getWorkingDirectory().."\\config\\"..J_[k][2]..".json") then
            local f = io.open(getWorkingDirectory().."\\config\\"..J_[k][2]..".json", "w+")
            if f then
                f:write(encodeJson(J_[k][1])):close()
            end
        end
    end
end
 

Milukation

Участник
44
9
Подскажите пожалуйста почему не работают кнопки в вкладках, сами вкладки есть, а кнопки которые я добавил нету.
Пизда.lua:
imgui.OnFrame(function()
    imgui.Button(faicons('USER')..' Основное', imgui.ImVec2(400, 60), function() menu = 1 end)
    imgui.Button(faicons('gear')..' Настройки', imgui.ImVec2(400, 60), function() menu = 2 end)
    imgui.Button(faicons('scroll')..' Шпаргалки', imgui.ImVec2(400, 60), function() menu = 3 end)
    imgui.Button(faicons('book')..' Лекции', imgui.ImVec2(400, 60), function() menu = 4 end)
    imgui.Button(faicons('info')..' О нас', imgui.ImVec2(400, 60), function() menu = 5 end)

    imgui.SameLine()

    imgui.SetCursorPos(imgui.ImVec2(415, 54))

    if imgui.BeginChild('Name##', imgui.ImVec2(1210, 340), true) then
if menu == 1 then
    imgui.Button('Акцент', imgui.ImVec2(400, 60), function() menu = 1 end)
elseif menu == 2 then
     imgui.Button('Тест', imgui.ImVec2(89, 56), function() menu = 2 end)
elseif menu == 3 then
    -- Код для третьей вкладки
-- Добавьте аналогичные блоки для других вкладок при необходимости
end
 

MLycoris

Режим чтения
Проверенный
1,822
1,869
Подскажите пожалуйста почему не работают кнопки в вкладках, сами вкладки есть, а кнопки которые я добавил нету.
попробуй так
Lua:
for numTab, nameTab in pairs({faicons('USER')..' Основное',faicons('gear')..' Настройки',faicons('scroll')..' Шпаргалки',faicons('book')..' Лекции',faicons('info')..' О нас',}) do
    if imgui.Button(nameTab,imgui.ImVec2(400,60)) then
        menu = numTab
    end
end
 

Milukation

Участник
44
9
попробуй так
Lua:
for numTab, nameTab in pairs({faicons('USER')..' Основное',faicons('gear')..' Настройки',faicons('scroll')..' Шпаргалки',faicons('book')..' Лекции',faicons('info')..' О нас',}) do
    if imgui.Button(nameTab,imgui.ImVec2(400,60)) then
        menu = numTab
    end
end
Спасибо! Работает
 
  • Нравится
Реакции: MLycoris

Corrygan228

Участник
132
9
пытался сделать биндер
подскажите, почему отправляются какие-то иероглифы, вместо моего текста(даже в json файл оно сохраняется не правильно)
Посмотреть вложение 224590
Lua:
require 'lib.moonloader'
local imgui = require 'imgui'
local encoding = require 'encoding'
local vkeys = require 'vkeys'
local u8                    = encoding.UTF8
encoding.default            = "CP1251"

local function createNewJsonTable(table)
    if not doesFileExist(getWorkingDirectory().."\\config\\"..table[2]..".json") then
           local f = io.open(getWorkingDirectory().."\\config\\"..table[2]..".json", 'w+')
           if f then
              f:write(encodeJson(table[1])):close()
        end
       else
           local f = io.open(getWorkingDirectory().."\\config\\"..table[2]..".json", "r")
           if f then
             table[1] = decodeJson(f:read("*a"))
             f:close()
           end
    end
end

local switch = 0

local J_ = {
       BINDER = {
        {
            {
                name = "Приветствие",
                multiline = "Write here",
                command = "firstcmd",
                hotkey = 0x61,
                activation = 0
            }
        }, "SETTINGS_FORMS" }
}

createNewJsonTable(J_.BINDER)

local buffer = {}

for k, v in ipairs(J_.BINDER[1]) do
    table.insert(buffer, {
        name = imgui.ImBuffer(tostring(v.name), 100),
        multiline = imgui.ImBuffer(tostring(v.multiline), 1024),
        command = imgui.ImBuffer(tostring(v.command), 50),
        old_command = "",
        activation = imgui.ImInt(v.activation),
        hotkey = v.hotkey
    })
end

for k,v in ipairs(buffer) do
    v.old_command = u8:encode(v.command.v)
end

local window = imgui.ImBool(false)  

function main()
    while not isSampLoaded() do wait(100) end
    temp_buffer = {
        name = imgui.ImBuffer(100),
        multiline = imgui.ImBuffer(1024),
        command = imgui.ImBuffer(50),
        activation = imgui.ImInt(0),
        hotkey = 0x61,
        arr_hotkey = {
            name = vkeys.key_names[0x61], edit = false, ticked = os.clock(), tickedState = false, sName = ""
        }
    }
    sampRegisterChatCommand('test', function()
        window.v = not window.v
    end)
    for k,v in ipairs(buffer) do
        if v.activation.v == 1 then
            sampRegisterChatCommand(u8:decode(v.command.v), function()
                for text in u8:encode(v.multiline.v):gmatch("[^\r\n]+") do
                    lua_thread.create(function()
                        sampSendChat(text)
                        wait(1000)
                    end)
                end    
            end)
        end
    end
    hotkeys = {}
    for k,v in ipairs(buffer) do
        table.insert(hotkeys, {
            name = vkeys.key_names[v.hotkey], edit = false, ticked = os.clock(), tickedState = false, sName = v.name.v
        })
    end
    while true do wait(0)
        imgui.Process = true
        if not window.v then
            imgui.ShowCursor = false
        end
        for k,v in ipairs(buffer) do
            if isKeyJustPressed(v.hotkey) then
                for text in u8:encode(v.multiline.v):gmatch("[^\r\n]+") do
                    sampSendChat(text)
                    wait(1000)
                end    
            end
        end
    end
end

function imgui.OnDrawFrame()
    if window.v then
        imgui.ShowCursor = true
        imgui.SetNextWindowPos(imgui.ImVec2(imgui.GetIO().DisplaySize.x / 2, imgui.GetIO().DisplaySize.y / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(600, 300), imgui.Cond.FirstUseEver)
        imgui.Begin("Test", window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoScrollbar)
        imgui.BeginChild("##1", imgui.ImVec2(100, 100), true)
        for k,v in ipairs(buffer) do
            if imgui.Button(u8(v.name.v), imgui.ImVec2(74, 24)) then
                switch = k
            end
        end
        if imgui.Button(u8"Добавить", imgui.ImVec2(74, 24)) then
            imgui.OpenPopup(u8"Добавить кнопку")
        end
        if imgui.BeginPopupModal(u8"Добавить кнопку", _, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoMove) then
            imgui.PushItemWidth(150)
            imgui.InputText(u8"Введите текст", temp_buffer.name)
            imgui.Combo(u8"Выберите активацию", temp_buffer.activation, {u8"На кнопку", u8"На команду"})
            if temp_buffer.activation.v == 1 then
                imgui.InputText(u8"command", temp_buffer.command)
            else
                if temp_buffer.arr_hotkey.edit then
                    local downKey = getDownKeys()
                    temp_buffer.hotkey = downKey
                    if downKey == '' then
                        if os.clock() - temp_buffer.arr_hotkey.ticked > 0.5 then
                            temp_buffer.arr_hotkey.ticked = os.clock()
                            temp_buffer.arr_hotkey.tickedState = not temp_buffer.arr_hotkey.tickedState
                        end
                        temp_buffer.arr_hotkey.name = temp_buffer.arr_hotkey.tickedState and "No" or "##isNo "..temp_buffer.arr_hotkey.ticked
                    else
                        temp_buffer.arr_hotkey.name = vkeys.key_names[temp_buffer.hotkey]
                        temp_buffer.arr_hotkey.edit = false
                        save()
                    end
                end
                if imgui.Button(u8(tostring(temp_buffer.hotkey == nil and "##asdasd" or temp_buffer.arr_hotkey.name.."##asdasd")), imgui.ImVec2(110, 0)) then
                    temp_buffer.arr_hotkey.edit = true
                end imgui.SameLine() imgui.Text(u8(temp_buffer.arr_hotkey.sName))
            end
            imgui.PopItemWidth()
            if imgui.Button(u8"Сохранить", imgui.ImVec2(100, 0)) then
                if temp_buffer.activation.v == 1 then
                    if temp_buffer.command.v == "" then
                        sampAddChatMessage("write command", -1)
                    else
                        if temp_buffer.name.v ~= "" then
                            sampAddChatMessage(u8:decode(temp_buffer.name.v), -1)
                            table.insert(J_.BINDER[1], {
                                name = tostring(u8:decode(temp_buffer.name.v)),
                                multiline = temp_buffer.multiline.v,
                                activation = temp_buffer.activation.v,
                                command = temp_buffer.command.v,
                                hotkey = temp_buffer.hotkey
                            })
                            table.insert(buffer, {
                                name = imgui.ImBuffer(tostring(u8:decode(temp_buffer.name.v)), 100),
                                multiline = imgui.ImBuffer(tostring(temp_buffer.multiline.v), 1024),
                                activation = imgui.ImInt(temp_buffer.activation.v),
                                old_command = "",
                                command = imgui.ImBuffer(tostring(temp_buffer.command.v), 50),
                                hotkey = temp_buffer.hotkey
                            })
                            save()
                            buffer[#buffer].old_command = u8:encode(buffer[#buffer].command.v)
                            sampRegisterChatCommand(temp_buffer.command.v, function()
                                for text in u8:encode(temp_buffer.multiline.v):gmatch("[^\r\n]+") do
                                    lua_thread.create(function()
                                        sampSendChat(text)
                                        wait(1000)
                                    end)
                                end    
                            end)
                            temp_buffer = {
                                name = imgui.ImBuffer(100),
                                multiline = imgui.ImBuffer(1024),
                                command = imgui.ImBuffer(50),
                                activation = imgui.ImInt(0),
                                hotkey = 0x61,
                                arr_hotkey = {
                                    name = vkeys.key_names[0x61], edit = false, ticked = os.clock(), tickedState = false, sName = ""
                                }
                            }
                            table.insert(hotkeys, {
                                name = vkeys.key_names[buffer[#buffer].hotkey], edit = false, ticked = os.clock(), tickedState = false, sName = buffer[#buffer].name.v
                            })
                            imgui.CloseCurrentPopup()
                        else
                            sampAddChatMessage("name is clean", -1)
                        end
                    end
                else
                    if temp_buffer.hotkey >= 0 then
                        table.insert(J_.BINDER[1], {
                            name = temp_buffer.name.v,
                            multiline = temp_buffer.multiline.v,
                            activation = temp_buffer.activation.v,
                            command = temp_buffer.command.v,
                            hotkey = temp_buffer.hotkey
                        })
                        table.insert(buffer, {
                            name = imgui.ImBuffer(tostring(temp_buffer.name.v), 100),
                            multiline = imgui.ImBuffer(tostring(temp_buffer.multiline.v), 1024),
                            activation = imgui.ImInt(temp_buffer.activation.v),
                            old_command = "",
                            command = imgui.ImBuffer(tostring(temp_buffer.command.v), 50),
                            hotkey = temp_buffer.hotkey
                        })
                        save()
                        temp_buffer = {
                            name = imgui.ImBuffer(100),
                            multiline = imgui.ImBuffer(1024),
                            command = imgui.ImBuffer(50),
                            activation = imgui.ImInt(0),
                            hotkey = 0x61,
                            arr_hotkey = {
                                name = vkeys.key_names[0x61], edit = false, ticked = os.clock(), tickedState = false, sName = ""
                            }
                        }
                        table.insert(hotkeys, {
                            name = vkeys.key_names[buffer[#buffer].hotkey], edit = false, ticked = os.clock(), tickedState = false, sName = buffer[#buffer].name.v
                        })
                        imgui.CloseCurrentPopup()
                    else
                        sampAddChatMessage("choose button", -1)
                    end
                end
            end
            imgui.SameLine()
            if imgui.Button(u8"Закрыть", imgui.ImVec2(100, 0)) then
                imgui.CloseCurrentPopup()
            end
            imgui.EndPopup()
        end
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginChild("##2", imgui.ImVec2(200, 200), true)
        for k,v in ipairs(buffer) do
            if k == switch then
                if imgui.Combo("##choose", v.activation, {u8"На кнопку", u8"На команду"}) then
                    J_.BINDER[1][k].activation = v.activation.v
                    save()
                end
                if imgui.InputTextMultiline("##multiline", v.multiline, imgui.ImVec2(150, 50)) then
                    J_.BINDER[1][k].multiline = v.multiline.v
                    save()
                end
                if v.activation.v == 0 then
                    if hotkeys[k].edit then
                        local downKey = getDownKeys()
                        J_.BINDER[1][k].hotkey = downKey
                        if downKey == '' then
                            if os.clock() - hotkeys[k].ticked > 0.5 then
                                hotkeys[k].ticked = os.clock()
                                hotkeys[k].tickedState = not hotkeys[k].tickedState
                            end
                            hotkeys[k].name = hotkeys[k].tickedState and "No" or "##isNo "..hotkeys[k].ticked
                        else
                            hotkeys[k].name = vkeys.key_names[J_.BINDER[1][k].hotkey]
                            hotkeys[k].edit = false
                            save()
                        end
                    end
                    if imgui.Button(u8(tostring(J_.BINDER[1][k].hotkey == nil and "##"..k or hotkeys[k].name.."##"..k)), imgui.ImVec2(110, 0)) then
                        hotkeys[k].edit = true
                    end imgui.SameLine() imgui.Text(u8:encode(hotkeys[k].sName))
                else
                    if imgui.InputText(u8"command", v.command) then
                        J_.BINDER[1][k].command = v.command.v
                        save()
                        sampUnregisterChatCommand(v.old_command)
                        sampRegisterChatCommand(v.command.v, function()
                            for text in u8:encode(v.multiline.v):gmatch("[^\r\n]+") do
                                lua_thread.create(function()
                                    sampSendChat(text)
                                    wait(1000)
                                end)
                            end    
                        end)
                        v.old_command = v.command.v
                    end    
                end
                if imgui.Button(u8"Удалить", imgui.ImVec2(90, 0)) then
                    table.remove(buffer, k)
                    table.remove(J_.BINDER[1], k)
                    save()
                end
            end
        end
        imgui.EndChild()
        imgui.End()
    end
end

function getDownKeys()
    local curkeys = ""
    local bool = false
    for k,v in pairs(vkeys) do
        if isKeyDown(v) then
            curkeys = v
            bool = true
        end
    end
    return curkeys, bool
end

function save()
    for k,v in pairs(J_) do
        if doesFileExist(getWorkingDirectory().."\\config\\"..J_[k][2]..".json") then
            local f = io.open(getWorkingDirectory().."\\config\\"..J_[k][2]..".json", "w+")
            if f then
                f:write(encodeJson(J_[k][1])):close()
            end
        end
    end
end
актуально
 

7 СМЕРТНЫХ ГРЕХОВ

Известный
515
159
Как релогать конфиг.
Потому что сохраняю
LUA:
local ini = inicfg.load({
    main = {
        bebra = "",
    }
}, "название конфига.ini")
тут типо
bebra = какой то хуйне с буфера в мимгуи и сохраняет это в конфиг Например: 1234
bebraN = 123

И если я делаю то будет неправильно ну это логично
if bebra = bebraN then
-body
end

Но если в мимгуи меню написать 123 и не релогать скрипт то меня шлет нахуй

Но если я его релогаю то настройки подгружаются и if bebra = bebraN then > дейсвие выполняется меня нахуй не шлет
 

MLycoris

Режим чтения
Проверенный
1,822
1,869
Как релогать конфиг.
Потому что сохраняю
LUA:
local ini = inicfg.load({
    main = {
        bebra = "",
    }
}, "название конфига.ini")
Покажи строку где и как ты сохраняешь новое значение. Должно быть так
Lua:
    if imgui.InputText('##Add', inputt, 256) then
        ini.set.inputsaved = u8:decode(ffi.string(inputt))
        inicfg.save(ini, 'Test.ini')
    end
 

7 СМЕРТНЫХ ГРЕХОВ

Известный
515
159
Покажи строку где и как ты сохраняешь новое значение. Должно быть так
Lua:
    if imgui.InputText('##Add', inputt, 256) then
        ini.set.inputsaved = u8:decode(ffi.string(inputt))
        inicfg.save(ini, 'Test.ini')
    end
LUA:
function save_ini()
    inicfg.save(ini, 'Название конфига.ini')
end

if imgui.InputText('##xyetablat', xyetablat, sizeof(xyetablat)) then
    ini.main.bebra = str(xyetablat)
    save_ini()
end
 

MLycoris

Режим чтения
Проверенный
1,822
1,869
LUA:
function save_ini()
    inicfg.save(ini, 'Название конфига.ini')
end

if imgui.InputText('##xyetablat', xyetablat, sizeof(xyetablat)) then
    ini.main.bebra = str(xyetablat)
    save_ini()
end
попробуй свой инпут в нужном месте в число переводить типа
bebraN == tonumber(str(xyetablat))

потому что ты используешь инпуттекст, а он введёное переводит в стринг, для чисел надо инпут инт