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

Corrygan228

Участник
132
9
Есть биндер, с одним биндом по умолчанию, называется он Приветствие, но если пытаюсь добавить ещё, то вместо названия иероглифы, добавляю, естественно, на русском языке.
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(170, 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
                            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()
                            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
 

colton.

Активный
152
53
Есть биндер, с одним биндом по умолчанию, называется он Приветствие, но если пытаюсь добавить ещё, то вместо названия иероглифы, добавляю, естественно, на русском языке.
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(170, 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
                            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()
                            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
кодировку поставь на Windows 1251 в редакторе кода и сохрани файл
 

tsunamiqq

Участник
429
16
Как сделать кнопку в диалоговом окне, у меня есть onShowDialog и return, в return'e мне нужно сделать кнопку
Lua:
hook.onShowDialog(id, style, title, b1, b2, text)

        return {id, style, title, b1, b2, text.. "  \n- 123: {00FF00}$"..tostring(statbizWeek).."\n-123:{00FF00}$"..tostring(statbizDay).."\n- 123: {00FF00}$"..tostring(sum).."\n- {FF0000}Обновить список(Это должно быть кнопкой)"}
 

Anti...

Активный
276
36
Есть вот такая функция, она красит и центрирует текст по колонке, однако очень криво центрирует русский текст. Как решить проблему?
Mimgui

Код:
function imgui.CenterTextColoredRGB(text)
    --imgui.SetCursorPosX(imgui.GetWindowSize().x / 2 - imgui.CalcTextSize(text).x / 2) -- Центрирование текста по окну
    imgui.SetCursorPosX( ( imgui.GetColumnOffset() + ( imgui.GetColumnWidth() / 2 ) ) - imgui.CalcTextSize( text ).x / 2 ) -- Центрирование текста по колонке
    imgui.TextColoredRGB(text)
end

function imgui.TextColoredRGB(text)
    local style = imgui.GetStyle()
    local colors = style.Colors
    local col = imgui.Col
   
    local designText = function(text__)
        local pos = imgui.GetCursorPos()
        if sampGetChatDisplayMode() == 2 then
            for i = 1, 1 --[[Степень тени]] do
                imgui.SetCursorPos(imgui.ImVec2(pos.x + i, pos.y))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x - i, pos.y))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x, pos.y + i))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x, pos.y - i))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
            end
        end
        imgui.SetCursorPos(pos)
    end
   
   
   
    local text = text:gsub('{(%x%x%x%x%x%x)}', '{%1FF}')

    local color = colors[col.Text]
    local start = 1
    local a, b = text:find('{........}', start)  
   
    while a do
        local t = text:sub(start, a - 1)
        if #t > 0 then
            designText(t)
            imgui.TextColored(color, t)
            imgui.SameLine(nil, 0)
        end

        local clr = text:sub(a + 1, b - 1)
        if clr:upper() == 'STANDART' then color = colors[col.Text]
        else
            clr = tonumber(clr, 16)
            if clr then
                local r = bit.band(bit.rshift(clr, 24), 0xFF)
                local g = bit.band(bit.rshift(clr, 16), 0xFF)
                local b = bit.band(bit.rshift(clr, 8), 0xFF)
                local a = bit.band(clr, 0xFF)
                color = imgui.ImVec4(r / 255, g / 255, b / 255, a / 255)
            end
        end

        start = b + 1
        a, b = text:find('{........}', start)
    end
    imgui.NewLine()
    if #text >= start then
        imgui.SameLine(nil, 0)
        designText(text:sub(start))
        imgui.TextColored(color, text:sub(start))
    end
end

Код взят из mimgui chat
 

хуега)

РП игрок
Модератор
2,574
2,278
Есть вот такая функция, она красит и центрирует текст по колонке, однако очень криво центрирует русский текст. Как решить проблему?
Mimgui

Код:
function imgui.CenterTextColoredRGB(text)
    --imgui.SetCursorPosX(imgui.GetWindowSize().x / 2 - imgui.CalcTextSize(text).x / 2) -- Центрирование текста по окну
    imgui.SetCursorPosX( ( imgui.GetColumnOffset() + ( imgui.GetColumnWidth() / 2 ) ) - imgui.CalcTextSize( text ).x / 2 ) -- Центрирование текста по колонке
    imgui.TextColoredRGB(text)
end

function imgui.TextColoredRGB(text)
    local style = imgui.GetStyle()
    local colors = style.Colors
    local col = imgui.Col
  
    local designText = function(text__)
        local pos = imgui.GetCursorPos()
        if sampGetChatDisplayMode() == 2 then
            for i = 1, 1 --[[Степень тени]] do
                imgui.SetCursorPos(imgui.ImVec2(pos.x + i, pos.y))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x - i, pos.y))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x, pos.y + i))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x, pos.y - i))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
            end
        end
        imgui.SetCursorPos(pos)
    end
  
  
  
    local text = text:gsub('{(%x%x%x%x%x%x)}', '{%1FF}')

    local color = colors[col.Text]
    local start = 1
    local a, b = text:find('{........}', start) 
  
    while a do
        local t = text:sub(start, a - 1)
        if #t > 0 then
            designText(t)
            imgui.TextColored(color, t)
            imgui.SameLine(nil, 0)
        end

        local clr = text:sub(a + 1, b - 1)
        if clr:upper() == 'STANDART' then color = colors[col.Text]
        else
            clr = tonumber(clr, 16)
            if clr then
                local r = bit.band(bit.rshift(clr, 24), 0xFF)
                local g = bit.band(bit.rshift(clr, 16), 0xFF)
                local b = bit.band(bit.rshift(clr, 8), 0xFF)
                local a = bit.band(clr, 0xFF)
                color = imgui.ImVec4(r / 255, g / 255, b / 255, a / 255)
            end
        end

        start = b + 1
        a, b = text:find('{........}', start)
    end
    imgui.NewLine()
    if #text >= start then
        imgui.SameLine(nil, 0)
        designText(text:sub(start))
        imgui.TextColored(color, text:sub(start))
    end
end

Код взят из mimgui chat
Там с кодировкой надо играться
 

percheklii

Известный
749
279
 

MLycoris

Режим чтения
Проверенный
1,835
1,905
могу такой пример дать, не знаю насколько он правильный, но вроде рабоает
Следи, чтоб на 31 строке false был
Lua:
local imgui = require 'mimgui'
local faicons = require('fAwesome6')

local WinState = imgui.new.bool(true)

imgui.OnFrame(function() return WinState[0] end, function()
    imgui.SetNextWindowPos(imgui.ImVec2(500,500), imgui.Cond.Always, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(500,500), imgui.Cond.Always)
    imgui.Begin('##Window', WinState)
    imgui.PushFont(one)
    imgui.Text(faicons('user')..'Test 1')
    imgui.Button(faicons('user')..'Test 1')
    imgui.PopFont()
    imgui.Separator()
    imgui.PushFont(two)
    imgui.Button(faicons('user')..'Test 2')
    imgui.Text(faicons('user')..'Test 2')
    imgui.PopFont()
    imgui.End()
end)

function main()
    sampRegisterChatCommand('testt', function()
        WinState[0] = not WinState[0]
    end) wait(-1)
end

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    local config = imgui.ImFontConfig()
    config.MergeMode = false
    config.PixelSnapH = true
    local iconRanges = imgui.new.ImWchar[3](faicons.min_range, faicons.max_range, 0)
    one = imgui.GetIO().Fonts:AddFontFromMemoryCompressedBase85TTF(faicons.get_font_data_base85('solid'), 12, config, iconRanges) -- solid - тип иконок, так же есть thin, regular, light и duotone
    two = imgui.GetIO().Fonts:AddFontFromMemoryCompressedBase85TTF(faicons.get_font_data_base85('solid'), 24, config, iconRanges) -- solid - тип иконок, так же есть thin, regular, light и duotone
end)

1690107628126.png
 
  • Влюблен
Реакции: Julimba

Julimba

Участник
108
10
WSiUU.png

иконка с fawesome6 вообще пропадает
 

sssilvian

Активный
239
25
Как проверить, открыт ли диалог? А если диалог открыт, сразу нажать ENTER?
Lua:
    while true do wait(0)
        if mainIni.config.parcela then
            setGameKeyState(11, 255)
setGameKeyState(15, 255)
            wait(10)
   sampSendDialogResponse(sampGetCurrentDialogId(), 1, 0, nil)
            wait(0)
        end
    end
end
Я хочу сделать галочку здесь для открытия диалога.
 

MLycoris

Режим чтения
Проверенный
1,835
1,905
Как проверить, открыт ли диалог? А если диалог открыт, сразу нажать ENTER?
Lua:
    while true do wait(0)
        if mainIni.config.parcela then
            setGameKeyState(11, 255)
setGameKeyState(15, 255)
            wait(10)
   sampSendDialogResponse(sampGetCurrentDialogId(), 1, 0, nil)
            wait(0)
        end
    end
end
Я хочу сделать галочку здесь для открытия диалога.
Lua:
if sampIsDialogActive() then -- если самп диалог открыт, то выполняется след код
    sampCloseCurrentDialogWithButton(1) -- 1 left button, 0 right button
end
 

tsunamiqq

Участник
429
16
Как сделать кнопку в диалоговом окне, у меня есть onShowDialog и return, в return'e мне нужно сделать кнопку
Lua:
hook.onShowDialog(id, style, title, b1, b2, text)

        return {id, style, title, b1, b2, text.. "  \n- 123: {00FF00}$"..tostring(statbizWeek).."\n-123:{00FF00}$"..tostring(statbizDay).."\n- 123: {00FF00}$"..tostring(sum).."\n- {FF0000}Обновить список(Это должно быть кнопкой)"}
актуал
 

Anti...

Активный
276
36
Есть вот такая функция, она красит и центрирует текст по колонке, однако очень криво центрирует русский текст. Как решить проблему?
Mimgui

Код:
function imgui.CenterTextColoredRGB(text)
    --imgui.SetCursorPosX(imgui.GetWindowSize().x / 2 - imgui.CalcTextSize(text).x / 2) -- Центрирование текста по окну
    imgui.SetCursorPosX( ( imgui.GetColumnOffset() + ( imgui.GetColumnWidth() / 2 ) ) - imgui.CalcTextSize( text ).x / 2 ) -- Центрирование текста по колонке
    imgui.TextColoredRGB(text)
end

function imgui.TextColoredRGB(text)
    local style = imgui.GetStyle()
    local colors = style.Colors
    local col = imgui.Col
 
    local designText = function(text__)
        local pos = imgui.GetCursorPos()
        if sampGetChatDisplayMode() == 2 then
            for i = 1, 1 --[[Степень тени]] do
                imgui.SetCursorPos(imgui.ImVec2(pos.x + i, pos.y))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x - i, pos.y))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x, pos.y + i))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
                imgui.SetCursorPos(imgui.ImVec2(pos.x, pos.y - i))
                imgui.TextColored(imgui.ImVec4(0, 0, 0, 1), text__) -- shadow
            end
        end
        imgui.SetCursorPos(pos)
    end
 
 
 
    local text = text:gsub('{(%x%x%x%x%x%x)}', '{%1FF}')

    local color = colors[col.Text]
    local start = 1
    local a, b = text:find('{........}', start)
 
    while a do
        local t = text:sub(start, a - 1)
        if #t > 0 then
            designText(t)
            imgui.TextColored(color, t)
            imgui.SameLine(nil, 0)
        end

        local clr = text:sub(a + 1, b - 1)
        if clr:upper() == 'STANDART' then color = colors[col.Text]
        else
            clr = tonumber(clr, 16)
            if clr then
                local r = bit.band(bit.rshift(clr, 24), 0xFF)
                local g = bit.band(bit.rshift(clr, 16), 0xFF)
                local b = bit.band(bit.rshift(clr, 8), 0xFF)
                local a = bit.band(clr, 0xFF)
                color = imgui.ImVec4(r / 255, g / 255, b / 255, a / 255)
            end
        end

        start = b + 1
        a, b = text:find('{........}', start)
    end
    imgui.NewLine()
    if #text >= start then
        imgui.SameLine(nil, 0)
        designText(text:sub(start))
        imgui.TextColored(color, text:sub(start))
    end
end

Код взят из mimgui chat
Актуально))
не понимаю в каком смысле "играться с кодировкой"
Функция криво центрирует текст на любом языке в колонке если текст имеет цвет
 
Последнее редактирование: