Гайд Как ХотКей из imgui_addons привязать к txt

  • Автор темы Удалённый пользователь 341712
  • Дата начала
У

Удалённый пользователь 341712

Гость
Автор темы
By DoubleTapInside
Привет! Я уже делал похожий обзор, он был связан с JSON, но теперь переключаемся к .txt, по скольку inicfg не умеет сохранять таблицы, переходим к другому формату.
Сначала давайте укажем директорию.

Lua:
path_settings = getWorkingDirectory().."\\config" -- получаем рабочий путь папки moonloader, переходим сразу в config
filename_settings = path_settings.."\\settings.txt" -- создаем наш файл, указываем название, указываем .txt формат
Далее создадим необходимые функции
Lua:
function deepcopy(orig)
  local orig_type = type(orig)
  local copy
  if orig_type == 'table' then
      copy = {}
      for orig_key, orig_value in next, orig, nil do
          copy[deepcopy(orig_key)] = deepcopy(orig_value)
      end
      setmetatable(copy, deepcopy(getmetatable(orig)))
  else -- number, string, boolean, etc
      copy = orig
  end
  return copy
end

local Luacfg = {
    _version = "9"
}
setmetatable(Luacfg, {
    __call = function(self)
        return self.__init()
    end
})
function Luacfg.__init()
    local self = {}
    local lfs = require "lfs"
    local inspect = require "inspect"
 
 
    function self.mkpath(filename)
        local sep, pStr = package.config:sub(1, 1), ""
        local path = filename:match("(.+"..sep..").+$") or filename
        for dir in path:gmatch("[^" .. sep .. "]+") do
            pStr = pStr .. dir .. sep
            lfs.mkdir(pStr)
        end
    end
 
 
    function self.load(filename, tbl)
        local file = io.open(filename, "r")    
        if file then
            local text = file:read("*all")
            file:close()
         
            local lua_code = loadstring("return "..text)
            if lua_code then
                loaded_tbl = lua_code()
             
                if type(loaded_tbl) == "table" then
                    for key, value in pairs(loaded_tbl) do
                        tbl[key] = value
                    end
                    return true
                else
                    return false
                end
            else
                return false
            end
        else
            return false
        end
  end
 
    function self.save(filename, tbl)
        self.mkpath(filename)
     
        local file = io.open(filename, "w+")
        if file then
            file:write(inspect(tbl))
            file:close()
            return true
        else
            return false
        end
    end
 
    return self
end

luacfg = Luacfg()
Далее укажем cfg, в котором будет сохраняться наш хот кей.
Lua:
cfg = {
  hotkey_newOne = {vkeys.VK_E},
  hotkey_newTwo = {vkeys.VK_O}
}
Загружаем наш "конфиг"
Lua:
luacfg.load(filename_settings, cfg)
Указываем локал с нашим хот кеем, который будет возвращать то, что в конфиге, сразу же создадим имгуи окно
Lua:
local hotkey_One = {v = deepcopy(cfg.hotkey_newOne)}
local hotkey_Two = {v = deepcopy(cfg.hotkey_newTwo)}
local window = imgui.ImBool(true)
Создадим тело скрипта.
Lua:
function main()
  while not isSampAvailable() do wait(100) end
  repeat wait(0) until sampIsLocalPlayerSpawned()
    wait(0)
    imgui.Process = window.v -- задаем процесс на одно окно
    if not window.v then -- если не активно наше окно то
      imgui.ShowCursor = false -- выключить курсор
    end
  end
end
Давайте теперь создадим рендер имгуи, где мы и сделаем наш хот кей меняя клавиши.
Lua:
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(300, 300), imgui.Cond.FirstUseEver)
    imgui.Begin('Test', window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    local tLastKeys = {}
    if require('imgui_addons').HotKey("##hotkey_neww", hotkey_newOne, tLastKeys, 100) then
      rkeys.changeHotKey(bind_hotkeyNewOne, hotkey_newOne.v)
      cfg.hotkey_newOne = deepcopy(hotkey_newOne.v)
      luacfg.save(filename_settings, cfg)
    end
    local tLastKeysTwo = {}
    if require('imgui_addons').HotKey("##hotkey_new", hotkey_newTwo, tLastKeysTwo, 100) then
      rkeys.changeHotKey(bind_hotkeyNewTwo, hotkey_newSMS.v)
      cfg.hotkey_newSMS = deepcopy(hotkey_newSMS.v)
      luacfg.save(filename_settings, cfg)
    end
     imgui.End()
  end
end
Теперь в main регистрируем клавиши.
Lua:
function main()
  while not isSampAvailable() do wait(100) end
  repeat wait(0) until sampIsLocalPlayerSpawned()
  bind_hotkeyNewOne = rkeys.registerHotKey(hotkey_newOne.v, 1, true, function()
    sampSendChat('test')
  end)
   bind_hotkeyNewTwo = rkeys.registerHotKey(hotkey_newTwo.v, 1, true, function()
    sampSendChat('testTwo')
  end)
  while true do
    wait(0)
    imgui.Process = window.v
    if not window.v then
      imgui.ShowCursor = false
    end
  end
end
То что получилось:
Lua:
require 'lib.moonloader'

local imgui = require 'imgui'
local rkeys = require 'lib.rkeys'
local vkeys = require 'vkeys'

path_settings = getWorkingDirectory().."\\config"
filename_settings = path_settings.."\\settings.txt"

function deepcopy(orig)
  local orig_type = type(orig)
  local copy
  if orig_type == 'table' then
      copy = {}
      for orig_key, orig_value in next, orig, nil do
          copy[deepcopy(orig_key)] = deepcopy(orig_value)
      end
      setmetatable(copy, deepcopy(getmetatable(orig)))
  else -- number, string, boolean, etc
      copy = orig
  end
  return copy
end

local Luacfg = {
    _version = "9"
}
setmetatable(Luacfg, {
    __call = function(self)
        return self.__init()
    end
})
function Luacfg.__init()
    local self = {}
    local lfs = require "lfs"
    local inspect = require "inspect"
 
 
    function self.mkpath(filename)
        local sep, pStr = package.config:sub(1, 1), ""
        local path = filename:match("(.+"..sep..").+$") or filename
        for dir in path:gmatch("[^" .. sep .. "]+") do
            pStr = pStr .. dir .. sep
            lfs.mkdir(pStr)
        end
    end
 
 
    function self.load(filename, tbl)
        local file = io.open(filename, "r")    
        if file then
            local text = file:read("*all")
            file:close()
         
            local lua_code = loadstring("return "..text)
            if lua_code then
                loaded_tbl = lua_code()
             
                if type(loaded_tbl) == "table" then
                    for key, value in pairs(loaded_tbl) do
                        tbl[key] = value
                    end
                    return true
                else
                    return false
                end
            else
                return false
            end
        else
            return false
        end
  end
 
    function self.save(filename, tbl)
        self.mkpath(filename)
     
        local file = io.open(filename, "w+")
        if file then
            file:write(inspect(tbl))
            file:close()
            return true
        else
            return false
        end
    end
 
    return self
end

luacfg = Luacfg()
cfg = {
  hotkey_newOne = {vkeys.VK_E},
  hotkey_newTwo = {vkeys.VK_M}
}


luacfg.load(filename_settings, cfg)

local hotkey_newOne = {v = deepcopy(cfg.hotkey_newOne)}
local hotkey_newTwo = {v = deepcopy(cfg.hotkey_newTwo)}
local window = imgui.ImBool(true)

function main()
  while not isSampAvailable() do wait(100) end
  repeat wait(0) until sampIsLocalPlayerSpawned()
  bind_hotkeyNewOne = rkeys.registerHotKey(hotkey_newOne.v, 1, true, function()
    sampSendChat('test')
  end)
  bind_hotkeyNewTwo = rkeys.registerHotKey(hotkey_newTwo.v, 1, true, function()
    sampSendChat('testTwo')
  end)
  while true do
    wait(0)
    imgui.Process = window.v
    if not window.v then
      imgui.ShowCursor = false
    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(300, 300), imgui.Cond.FirstUseEver)
    imgui.Begin('Test', window, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    local tLastKeys = {}
    if require('imgui_addons').HotKey("##hotkey_newOne", hotkey_newOne, tLastKeys, 100) then
      rkeys.changeHotKey(bind_hotkeyNewOne, hotkey_newOne.v)
      cfg.hotkey_newOne = deepcopy(hotkey_newOne.v)
      luacfg.save(filename_settings, cfg)
    end
    local tLastKeysTwo = {}
     if require('imgui_addons').HotKey("##hotkey_newTwo", hotkey_newTwo, tLastKeysTwo, 100) then
      rkeys.changeHotKey(bind_hotkeyNewTwo, hotkey_newTwo.v)
      cfg.hotkey_newTwo = deepcopy(hotkey_newTwo.v)
      luacfg.save(filename_settings, cfg)
    end
     imgui.End()
  end
end

На этом всё, всем удачи!
Убедительная просьба меня не бить
 

Вложения

  • test (8).lua
    3.5 KB · Просмотры: 20
Последнее редактирование модератором:
1,417
1,029
по скольку inicfg не умеет сохранять таблицы
всм
1592581234572.png

 

reseller

Потрачен
33
8
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
смеруха rkeys.lua:106: attempt to call field 'callback' (a boolean value) stack traceback: moonloader\lib\rkeys.lua: in function \moonloader\lib\rkeys.lua:89>
 

Double Tap Inside

Известный
Проверенный
1,898
1,253
Спасибо. Но не стоит рассматривать мои временные решения как что то постоянное. Именно по этому я не выкладываю никаких модулей и тому подобного, чтобы не обсираться. И именно по этому все временные решения остаются в том скрипте в котором я их использовал. Я постоянно и медленно учусь лучше кодить и лучше использовать готовые наработки (пиздить код). Вариант с json был хорош, покрайней мере, мне кто то кидал хороший вариант с ним
 
  • Нравится
Реакции: AnWu