В попытках создать биндер

Corrygan228

Участник
Автор темы
132
9
Версия MoonLoader
.027.0-preview
Скинули вот такой код биндера, где пользователь может выбрать сам активацию(клавиша/команда), вроде все работает нормально, но вот писанина убивает:
1702668422477.png

Есть подозрения, что дело в том, что скрипт как-то не так сохраняет созданные бинды в json(по идее � должен заменять каждый русский символ, но так не происходит)
1702668471909.png

Прошу помощи у гениев Lua, как это пофиксить или может кто-то скинет другой код биндера?
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 = "Ваш текст",
                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 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 (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
                            table.insert(J_.BINDER[1], {
                                name = tostring(u8:decode(temp_buffer.name.v)),
                                multiline = tostring(u8:decode(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(u8:decode(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
 

Corrygan228

Участник
Автор темы
132
9
попробуй все
u8:encode
заменить на
u8:decode
не помогло
название бинда нормально сохраняется в json, а его содержание нет
1702670289215.png


мб есть какой-то схожий по функционалу биндер с открытым кодом? мб там чего подсмотрю, хотя я вроде искал - не нашел
 
  • Вау
Реакции: Hinаta

Corrygan228

Участник
Автор темы
132
9

Corrygan228

Участник
Автор темы
132
9
  • Эм
Реакции: Hinаta

MLycoris

На вид оружие массового семяизвержения
Проверенный
1,992
2,186
слушай, учи мимгуи пока не поздно, я тебе даже пример биндера на жсон накидал
1702671652409.png

Lua:
local imgui = require 'mimgui'
local ffi = require 'ffi'
local encoding = require 'encoding'
encoding.default = 'CP1251'
local u8 = encoding.UTF8
local new = imgui.new

local WinState = new.bool()

function json(filePath)
    local filePath = getWorkingDirectory()..'\\config\\'..(filePath:find('(.+).json') and filePath or filePath..'.json')
    local class = {}
    if not doesDirectoryExist(getWorkingDirectory()..'\\config') then
        createDirectory(getWorkingDirectory()..'\\config')
    end
    function class:Save(tbl)
        if tbl then
            local F = io.open(filePath, 'w')
            F:write(encodeJson(tbl) or {})
            F:close()
            return true, 'ok'
        end
        return false, 'table = nil'
    end
    function class:Load(defaultTable)
        if not doesFileExist(filePath) then
            class:Save(defaultTable or {})
        end
        local F = io.open(filePath, 'r+')
        local TABLE = decodeJson(F:read() or {})
        F:close()
        for def_k, def_v in next, defaultTable do
            if TABLE[def_k] == nil then
                TABLE[def_k] = def_v
            end
        end
        return TABLE
    end
    return class
end
local testJSON = json('testJSON.json'):Load({})
function save()
    json('testJSON.json'):Save(testJSON)
end

local whatSave = {
    name = new.char[256](),
    multiline = new.char[256](),
    command = new.char[256](),
    hotkey = new.char[256](),
    activation = new.int(),
}

local item_list = {u8'Раз', u8'Два'}
local ImItems = new['const char*'][#item_list](item_list)


imgui.OnFrame(function() return WinState[0] end, function(player)
    imgui.SetNextWindowPos(imgui.ImVec2(500,500), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(500, 500), imgui.Cond.Always)
    imgui.Begin('##Window', WinState, imgui.WindowFlags.NoResize)
    imgui.InputText('Name',whatSave.name,256)
    imgui.InputTextMultiline('Text',whatSave.multiline,256)
    imgui.InputText('Command',whatSave.command,256)
    imgui.InputText('hotkey',whatSave.hotkey,256)
    imgui.Combo('activation',whatSave.activation,ImItems, #item_list)
    if imgui.Button(u8'Добавить') then
        table.insert(testJSON, {
            name = u8:decode(ffi.string(whatSave.name)),
            multiline = u8:decode(ffi.string(whatSave.multiline)),
            command = u8:decode(ffi.string(whatSave.command)),
            hotkey = u8:decode(ffi.string(whatSave.hotkey)),
            activation = whatSave.activation[0],
        }) save()
        whatSave = {
            name = new.char[256](),
            multiline = new.char[256](),
            command = new.char[256](),
            hotkey = new.char[256](),
            activation = new.int(),
        }
    end
    imgui.SameLine()
    if imgui.Button(u8'Очистить') then
        whatSave = {
            name = new.char[256](),
            multiline = new.char[256](),
            command = new.char[256](),
            hotkey = new.char[256](),
            activation = new.int(),
        }
    end
    if imgui.CollapsingHeader('SavesBind') then
        for index, data in pairs(testJSON) do
            imgui.Text(u8'Название: '..u8(data.name))
            imgui.Separator()
            imgui.TextWrapped(u8'Текст: '..u8(data.multiline))
            imgui.Separator()
            imgui.Text(u8'Команда: '..u8(data.command))
            imgui.Text(u8'Хоткей: '..u8(data.hotkey))
            imgui.Text(u8'Активация: '..u8(data.activation))
        end
    end
    imgui.End()
end)

function main()
    sampRegisterChatCommand('cmd', function() WinState[0] = not WinState[0] end)
    wait(-1)
end
 
  • Нравится
Реакции: Fellespe. и chromiusj

Corrygan228

Участник
Автор темы
132
9
слушай, учи мимгуи пока не поздно, я тебе даже пример биндера на жсон накидал
Посмотреть вложение 224789
Lua:
local imgui = require 'mimgui'
local ffi = require 'ffi'
local encoding = require 'encoding'
encoding.default = 'CP1251'
local u8 = encoding.UTF8
local new = imgui.new

local WinState = new.bool()

function json(filePath)
    local filePath = getWorkingDirectory()..'\\config\\'..(filePath:find('(.+).json') and filePath or filePath..'.json')
    local class = {}
    if not doesDirectoryExist(getWorkingDirectory()..'\\config') then
        createDirectory(getWorkingDirectory()..'\\config')
    end
    function class:Save(tbl)
        if tbl then
            local F = io.open(filePath, 'w')
            F:write(encodeJson(tbl) or {})
            F:close()
            return true, 'ok'
        end
        return false, 'table = nil'
    end
    function class:Load(defaultTable)
        if not doesFileExist(filePath) then
            class:Save(defaultTable or {})
        end
        local F = io.open(filePath, 'r+')
        local TABLE = decodeJson(F:read() or {})
        F:close()
        for def_k, def_v in next, defaultTable do
            if TABLE[def_k] == nil then
                TABLE[def_k] = def_v
            end
        end
        return TABLE
    end
    return class
end
local testJSON = json('testJSON.json'):Load({})
function save()
    json('testJSON.json'):Save(testJSON)
end

local whatSave = {
    name = new.char[256](),
    multiline = new.char[256](),
    command = new.char[256](),
    hotkey = new.char[256](),
    activation = new.int(),
}

local item_list = {u8'Раз', u8'Два'}
local ImItems = new['const char*'][#item_list](item_list)


imgui.OnFrame(function() return WinState[0] end, function(player)
    imgui.SetNextWindowPos(imgui.ImVec2(500,500), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(500, 500), imgui.Cond.Always)
    imgui.Begin('##Window', WinState, imgui.WindowFlags.NoResize)
    imgui.InputText('Name',whatSave.name,256)
    imgui.InputTextMultiline('Text',whatSave.multiline,256)
    imgui.InputText('Command',whatSave.command,256)
    imgui.InputText('hotkey',whatSave.hotkey,256)
    imgui.Combo('activation',whatSave.activation,ImItems, #item_list)
    if imgui.Button(u8'Добавить') then
        table.insert(testJSON, {
            name = u8:decode(ffi.string(whatSave.name)),
            multiline = u8:decode(ffi.string(whatSave.multiline)),
            command = u8:decode(ffi.string(whatSave.command)),
            hotkey = u8:decode(ffi.string(whatSave.hotkey)),
            activation = whatSave.activation[0],
        }) save()
        whatSave = {
            name = new.char[256](),
            multiline = new.char[256](),
            command = new.char[256](),
            hotkey = new.char[256](),
            activation = new.int(),
        }
    end
    imgui.SameLine()
    if imgui.Button(u8'Очистить') then
        whatSave = {
            name = new.char[256](),
            multiline = new.char[256](),
            command = new.char[256](),
            hotkey = new.char[256](),
            activation = new.int(),
        }
    end
    if imgui.CollapsingHeader('SavesBind') then
        for index, data in pairs(testJSON) do
            imgui.Text(u8'Название: '..u8(data.name))
            imgui.Separator()
            imgui.TextWrapped(u8'Текст: '..u8(data.multiline))
            imgui.Separator()
            imgui.Text(u8'Команда: '..u8(data.command))
            imgui.Text(u8'Хоткей: '..u8(data.hotkey))
            imgui.Text(u8'Активация: '..u8(data.activation))
        end
    end
    imgui.End()
end)

function main()
    sampRegisterChatCommand('cmd', function() WinState[0] = not WinState[0] end)
    wait(-1)
end
а можешь тоже самое на imgui, пожалуйста?
mimgui конечно надо заняться, но мне сейчас нужно на imgui именно биндер закончить