json save

IlyaHL2

Известный
Автор темы
232
49
Версия MoonLoader
.026-beta
Не save нихера
[08:06:07.326637] (exception) cocs: CJSON: Cannot serialise userdata: type not supported
[08:06:07.326637] (error) cocs: C:\Games\GTA 140K\moonloader\cocs.lua:52: bad argument #1 to 'write' (string expected, got nil)
stack traceback:
[C]: in function 'write'
C:\Games\GTA 140K\moonloader\cocs.lua:52: in main chunk
[08:06:07.326637] (error) cocs: Script died due to an error. (0BEADD74)


Lua:
local config = {
    gram = {
        mess = imgui.ImBool(false),
        spam = imgui.ImBool(false),
    }
}

if not doesFileExist(path) then
    local f = io.open(path, 'w+')
    f:write(encodeJson(config)):close()
else
    local f = io.open(path, "r")
    a = f:read("*a")
    config = decodeJson(a)
    f:close()
end

function JSONSave()
    if doesFileExist(path) then
        local f = io.open(path, 'w+')
        if f then
            f:write(encodeJson(config)):close() --52 строка
            return true
        else
            return false
        end
    else
        return false
    end
end
 
У

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

Гость
Ну не охота переписывать по 2 раза одно,
Lua:
local config = {
    gram = {
        mess = imgui.ImBool(false),
        spam = imgui.ImBool(false),
    }
}

mess = imgui.ImBool(config.gram.mess)
spam = imgui.ImBool(config.gram.spam)


других вариантов нет?
Вот так же, в ини простые типы, в имгуи обертка, при сохранении к сожалению придется сохранять поле .v из обертки
Lua:
local config = {
    gram = {
        mess = false,
        spam = false,
    }
}

mess = imgui.ImBool(config.gram.mess)
spam = imgui.ImBool(config.gram.spam)
 
  • Нравится
Реакции: IlyaHL2

RedHolms

Известный
Проверенный
624
383
Ну не охота переписывать по 2 раза одно,
Lua:
local config = {
    gram = {
        mess = imgui.ImBool(false),
        spam = imgui.ImBool(false),
    }
}

mess = imgui.ImBool(config.gram.mess)
spam = imgui.ImBool(config.gram.spam)


других вариантов нет?
Не охота писать много кода? Переходи на mimgui и не говнокодь

(ниже код, который написан только мной, и приятен только мне, если хочешь оставать на MoonImGui - перепиши это под своё, или вообще не используй это)
Lua:
local ImGui = require 'mimgui'

local ImNew = ImGui.new

local ImGuiData = {
   iMyData = ImNew.int(0)

   get_name = nil
}

local ImGuiDataMap = {
   ["my_container.my_data"] = ImGuiData.iMyData,

   load = nil,
   saveValue = nil
}

local settings = {
   my_container = {
      my_data = 0
   }

   load = nil,
   save = nil
}

local ImGuiLoadCValue, ImGuiSaveCValue

ImGuiLoadCValue = function(v, p)
   local nm = ImGuiData:get_name(p)
   if not nm then print("invalid p ", p) return end

   if nm:startswith('sz') then
      ImGui.StrCopy(p, v)
   else
      p[0] = v
   end
end

ImGuiSaveCValue = function(t, k, p)
   local nm = ImGuiData:get_name(p)
   if not nm then print("invalid p ", p) return end

   if nm:startswith('sz') then
      table.set(t, k, ffi.string(p))
   else
      table.set(t, k, p[0])
   end
end

function ImGuiData:get_name(p)
   for n, pp in pairs(self) do
      if pp == p then
         return n
      end
   end
   return nil
end

function ImGuiDataMap:load()
   for k, v in pairs(ImGuiDataMap) do
      if type(v) == "function" then goto continue end
      ImGuiLoadCValue(table.get(settings, k), v)
   ::continue:: end
end

function ImGuiDataMap:saveValue(p)
   for k, pp in pairs(ImGuiDataMap) do
      if type(pp) == "function" then goto continue end
      if pp == p then
         ImGuiSaveCValue(settings, k, p)
      end
   ::continue:: end
end

function settings:load()
   print("loading settings...")

   local f, err = io.open(CFG_SETTINGS_FILEPATH, "r")
   if not f then
      print("failed to load settings: ", err)
      return
   end

   local c = f:read("*a")
   f:close()

   local loaded = decodeJson(c)
   if loaded then
      table.merge(self, loaded)
   end
end

function settings:save()
   print("saving settings...")
  
   local f, err = io.open(CFG_SETTINGS_FILEPATH, "w+")
   if not f then
      print("failed to save settings: ", err)
      return
   end

   local to_encode = table.copy(self)
   to_encode.load = nil
   to_encode.save = nil

   local encoded = encodeJson(to_encode)
   if encoded then
      f:write(encoded)
   end

   f:close()
end

function string:startswith(str)
   return self:sub(1, #str) == str
end

function string:split(sep, reallen)
   local result = {}

   local len = reallen or #sep

   local substring_start_index = 1

   for i = 1, #self do
      if self:sub(i, i + len):match('^' .. sep) then
         local substr = self:sub(substring_start_index, i - 1)
         if #substr > 0 then
            table.insert(result, substr)
         end
         substring_start_index = i + len
      end
   end

   local last_substr = self:sub(substring_start_index, #self)
   if #last_substr > 0 then
      table.insert(result, last_substr)
   end

   return result
end

function table.merge(p, s)
   for k, v in pairs(s) do
      if type(k) == "number" and p._d then
         p[k] = table.copy(p._d)
      end

      if type(v) == type(p[k]) then
         if type(v) == "table" then
            p[k] = table.merge(p[k], v)
         else
            p[k] = v
         end
      end
   end

   return p
end

function table.get(t, k)
   local splited = k:split('%.', 1)
   local v = t

   for _, kp in pairs(splited) do
      v = v[kp]
   end

   return v
end

function table.set(t, k, v)
   local splited = k:split('%.', 1)
   local fk = splited[#splited]
   splited[#splited] = nil

   for _, kp in pairs(splited) do
      t = t[kp]
   end

   t[fk] = v
end

function table.copy(t, _seen)
   if type(t) ~= "table" then return t end

   local seen = _seen or {}
   if seen[t] then return seen[t] end

   local _copy = setmetatable({}, getmetatable(t))
   seen[t] = _copy

   for k, v in pairs(t) do _copy[k] = table.copy(v, seen) end

   return _copy
end

Пример:
Lua:
function main()
    settings:load()

    -- ...
    
    ImGuiDataMap:load()
    
    while not isSampAvailable() do wait(10) end
    -- ...
end

ImGui.OnFrame(
    function() return ... end,
    function(pl)
        if ImGui.InputInt("Число", ImGuiData.iMyData) then
            ImGuiDataMap:saveValue(ImGuiData.iMyData)
        end
    end
)
 
  • Эм
Реакции: IlyaHL2

IlyaHL2

Известный
Автор темы
232
49
Не охота писать много кода? Переходи на mimgui и не говнокодь

(ниже код, который написан только мной, и приятен только мне, если хочешь оставать на MoonImGui - перепиши это под своё, или вообще не используй это)
Lua:
local ImGui = require 'mimgui'

local ImNew = ImGui.new

local ImGuiData = {
   iMyData = ImNew.int(0)

   get_name = nil
}

local ImGuiDataMap = {
   ["my_container.my_data"] = ImGuiData.iMyData,

   load = nil,
   saveValue = nil
}

local settings = {
   my_container = {
      my_data = 0
   }

   load = nil,
   save = nil
}

local ImGuiLoadCValue, ImGuiSaveCValue

ImGuiLoadCValue = function(v, p)
   local nm = ImGuiData:get_name(p)
   if not nm then print("invalid p ", p) return end

   if nm:startswith('sz') then
      ImGui.StrCopy(p, v)
   else
      p[0] = v
   end
end

ImGuiSaveCValue = function(t, k, p)
   local nm = ImGuiData:get_name(p)
   if not nm then print("invalid p ", p) return end

   if nm:startswith('sz') then
      table.set(t, k, ffi.string(p))
   else
      table.set(t, k, p[0])
   end
end

function ImGuiData:get_name(p)
   for n, pp in pairs(self) do
      if pp == p then
         return n
      end
   end
   return nil
end

function ImGuiDataMap:load()
   for k, v in pairs(ImGuiDataMap) do
      if type(v) == "function" then goto continue end
      ImGuiLoadCValue(table.get(settings, k), v)
   ::continue:: end
end

function ImGuiDataMap:saveValue(p)
   for k, pp in pairs(ImGuiDataMap) do
      if type(pp) == "function" then goto continue end
      if pp == p then
         ImGuiSaveCValue(settings, k, p)
      end
   ::continue:: end
end

function settings:load()
   print("loading settings...")

   local f, err = io.open(CFG_SETTINGS_FILEPATH, "r")
   if not f then
      print("failed to load settings: ", err)
      return
   end

   local c = f:read("*a")
   f:close()

   local loaded = decodeJson(c)
   if loaded then
      table.merge(self, loaded)
   end
end

function settings:save()
   print("saving settings...")
 
   local f, err = io.open(CFG_SETTINGS_FILEPATH, "w+")
   if not f then
      print("failed to save settings: ", err)
      return
   end

   local to_encode = table.copy(self)
   to_encode.load = nil
   to_encode.save = nil

   local encoded = encodeJson(to_encode)
   if encoded then
      f:write(encoded)
   end

   f:close()
end

function string:startswith(str)
   return self:sub(1, #str) == str
end

function string:split(sep, reallen)
   local result = {}

   local len = reallen or #sep

   local substring_start_index = 1

   for i = 1, #self do
      if self:sub(i, i + len):match('^' .. sep) then
         local substr = self:sub(substring_start_index, i - 1)
         if #substr > 0 then
            table.insert(result, substr)
         end
         substring_start_index = i + len
      end
   end

   local last_substr = self:sub(substring_start_index, #self)
   if #last_substr > 0 then
      table.insert(result, last_substr)
   end

   return result
end

function table.merge(p, s)
   for k, v in pairs(s) do
      if type(k) == "number" and p._d then
         p[k] = table.copy(p._d)
      end

      if type(v) == type(p[k]) then
         if type(v) == "table" then
            p[k] = table.merge(p[k], v)
         else
            p[k] = v
         end
      end
   end

   return p
end

function table.get(t, k)
   local splited = k:split('%.', 1)
   local v = t

   for _, kp in pairs(splited) do
      v = v[kp]
   end

   return v
end

function table.set(t, k, v)
   local splited = k:split('%.', 1)
   local fk = splited[#splited]
   splited[#splited] = nil

   for _, kp in pairs(splited) do
      t = t[kp]
   end

   t[fk] = v
end

function table.copy(t, _seen)
   if type(t) ~= "table" then return t end

   local seen = _seen or {}
   if seen[t] then return seen[t] end

   local _copy = setmetatable({}, getmetatable(t))
   seen[t] = _copy

   for k, v in pairs(t) do _copy[k] = table.copy(v, seen) end

   return _copy
end

Пример:
Lua:
function main()
    settings:load()

    -- ...
   
    ImGuiDataMap:load()
   
    while not isSampAvailable() do wait(10) end
    -- ...
end

ImGui.OnFrame(
    function() return ... end,
    function(pl)
        if ImGui.InputInt("Число", ImGuiData.iMyData) then
            ImGuiDataMap:saveValue(ImGuiData.iMyData)
        end
    end
)
В вопросе не слово про mimgui, меня интересовал обычный imgui,ну да ладно...