Неактуально JSON - для разных серверов.

Bene //

Участник
Автор темы
127
6
Версия MoonLoader
.027.0-preview
Всем здравствуйте.
Подскажите пожалуйста, сделать чтобы JSON создавался для каждого сервера? (такое есть в скрипте checkerе игроков).
У меня есть скрипт в который я пишу ту или иную информацию, но он ее сохраняет в одном файле, эта инфа не актуальна для другого сервера. Мне нужно чтобы json загружался для каждого сервера по отдельности, как такое сделать?
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,776
11,226
если делаешь через иникфг:
Lua:
local inicfg = require 'inicfg'
local directIni = 'filename.ini'
local ini = inicfg.load(inicfg.load({
    servers = {
        Data = encodeJson({})
    },
}, directIni))
inicfg.save(ini, directIni)
local Data = decodeJson(ini.servers.data)

function main()
    while not isSampAvailable() do wait(0) end
    CurrentServerAddress = table.concat({sampGetCurrentServerAddress()}, ':')
    if Data[CurrentServerAddress] == nil then
        sampAddChatMessage('настройки для сервера не были найдены, создаю', -1)
        Data[CurrentServerAddress] = {}
        ini.servers.data = encodeJson(Data)
        inicfg.save(ini, directIni)
    end
    wait(-1)
end

если делаешь через JSON:
Lua:
-- JSON
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 Data = json('FileName.json'):Load({})

function main()
    while not isSampAvailable() do wait(0) end
    CurrentServerAddress = table.concat({sampGetCurrentServerAddress()}, ':')
    if Data[CurrentServerAddress] == nil then
        sampAddChatMessage('настройки для сервера не были найдены, создаю', -1)
        Data[CurrentServerAddress] = {}
        json('FileName.json'):Save(Data)
    end
    wait(-1)
end
 

Bene //

Участник
Автор темы
127
6
если делаешь через иникфг:
Lua:
local inicfg = require 'inicfg'
local directIni = 'filename.ini'
local ini = inicfg.load(inicfg.load({
    servers = {
        Data = encodeJson({})
    },
}, directIni))
inicfg.save(ini, directIni)
local Data = decodeJson(ini.servers.data)

function main()
    while not isSampAvailable() do wait(0) end
    CurrentServerAddress = table.concat({sampGetCurrentServerAddress()}, ':')
    if Data[CurrentServerAddress] == nil then
        sampAddChatMessage('настройки для сервера не были найдены, создаю', -1)
        Data[CurrentServerAddress] = {}
        ini.servers.data = encodeJson(Data)
        inicfg.save(ini, directIni)
    end
    wait(-1)
end

если делаешь через JSON:
Lua:
-- JSON
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 Data = json('FileName.json'):Load({})

function main()
    while not isSampAvailable() do wait(0) end
    CurrentServerAddress = table.concat({sampGetCurrentServerAddress()}, ':')
    if Data[CurrentServerAddress] == nil then
        sampAddChatMessage('настройки для сервера не были найдены, создаю', -1)
        Data[CurrentServerAddress] = {}
        json('FileName.json'):Save(Data)
    end
    wait(-1)
end
Я попытался сделать чтобы для каждого сервера создавался отдельный файл, по началу когда заходишь на серв появляется ошибка
[ML] (error) TimeHouse.lua: opcode '0B39' call caused an unhandled exception
stack traceback:
[C]: in function 'sampGetCurrentServerAddress'
...nity GTA Launcher\trinity_games\moonloader\TimeHouse.lua:22: in main chunk
, но потом когда перезагружаю скрипты вручную (CTRL + R) - все начинает работать. В чем тут может быть проблемы?

Lua:
local servers = {
        '185.169.134.83',
        '185.169.134.84',
        '185.169.134.85'
}
local ip = sampGetCurrentServerAddress() -- Получаем айпи сервера на котором мы сейчас
    for k, v in pairs(servers) do -- Проверяем
        if v == ip then

local tableConfig = {
    ["config"]         = thisScript().version, -- // Версия конфига
    ["HOUSE"] = {}
}
local linkConfig = getWorkingDirectory() .. "/config/"..ip..".json"
if not doesFileExist(linkConfig) then
    local file = io.open(linkConfig, "w")
    file:write(encodeJson(tableConfig))
    io.close(file)
end
if doesFileExist(linkConfig) then
    local file = io.open(linkConfig, "r")
    if file then
        local code = decodeJson(file:read("*a"))
        if code["config"] == nil or tostring(code["config"]) ~= tostring(thisScript().version) then
            os.remove(linkConfig)
            io.close(file)
            local file = io.open(linkConfig, "w")
            file:write(encodeJson(tableConfig))
            io.close(file)
        end
    end
    local file = io.open(linkConfig, "r")
    if file then
        db = decodeJson(file:read("*a"))
    end
    io.close(file)
end
end
end
 
Последнее редактирование:

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,776
11,226
Я попытался сделать чтобы для каждого сервера создавался отдельный файл, по началу когда заходишь на серв появляется ошибка
[ML] (error) TimeHouse.lua: opcode '0B39' call caused an unhandled exception
stack traceback:
[C]: in function 'sampGetCurrentServerAddress'
...nity GTA Launcher\trinity_games\moonloader\TimeHouse.lua:22: in main chunk
, но потом когда перезагружаю скрипты вручную (CTRL + R) - все начинает работать. В чем тут может быть проблемы?

Lua:
local servers = {
        '185.169.134.83',
        '185.169.134.84',
        '185.169.134.85'
}
local ip = sampGetCurrentServerAddress() -- Получаем айпи сервера на котором мы сейчас
    for k, v in pairs(servers) do -- Проверяем
        if v == ip then

local tableConfig = {
    ["config"]         = thisScript().version, -- // Версия конфига
    ["HOUSE"] = {}
}
local linkConfig = getWorkingDirectory() .. "/config/"..ip..".json"
if not doesFileExist(linkConfig) then
    local file = io.open(linkConfig, "w")
    file:write(encodeJson(tableConfig))
    io.close(file)
end
if doesFileExist(linkConfig) then
    local file = io.open(linkConfig, "r")
    if file then
        local code = decodeJson(file:read("*a"))
        if code["config"] == nil or tostring(code["config"]) ~= tostring(thisScript().version) then
            os.remove(linkConfig)
            io.close(file)
            local file = io.open(linkConfig, "w")
            file:write(encodeJson(tableConfig))
            io.close(file)
        end
    end
    local file = io.open(linkConfig, "r")
    if file then
        db = decodeJson(file:read("*a"))
    end
    io.close(file)
end
end
end
в том что ты не ожидаешь загрузки сампа, сделай в мейне как в моем примере
 

Bene //

Участник
Автор темы
127
6
в том что ты не ожидаешь загрузки сампа, сделай в мейне как в моем примере
Шо тут не так?
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local ip = sampGetCurrentServerAddress()
    if ip ~= "185.169.134.83" and ip ~= "185.169.134.84" and ip ~= "185.169.134.85" then
    return sampAddChatMessage(prefix..'Ошибка! Вы не на Trinity!')
    else
            sampAddChatMessage("работает", -1)
    end
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,776
11,226
Шо тут не так?
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local ip = sampGetCurrentServerAddress()
    if ip ~= "185.169.134.83" and ip ~= "185.169.134.84" and ip ~= "185.169.134.85" then
    return sampAddChatMessage(prefix..'Ошибка! Вы не на Trinity!')
    else
            sampAddChatMessage("работает", -1)
    end
энда не хватает
 

Bene //

Участник
Автор темы
127
6
энда не хватает
Есть...просто та ошибка осталась, не понял что изменить то надо?
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    local ip = sampGetCurrentServerAddress()
    if ip ~= "185.169.134.83" and ip ~= "185.169.134.84" and ip ~= "185.169.134.85" then
    return sampAddChatMessage(prefix..'Ошибка! Вы не на Trinity!')
    else
            sampAddChatMessage("работает", -1)
    end


    while true do wait(0)
        imgui.Process = mainMenu.v
    end
    wait(-1)
end