Как в таблицу добавить что-то из игры?

askfmaskfaosflas

Потрачен
Автор темы
1,089
511
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Версия MoonLoader
.026-beta
У меня есть таблица:
1659141481738.png

И есть поле ввода текста, и кнопка, по нажатию которой должно добавиться значение из поля ввода текста в таблицу
1659141522183.png

Как можно это реализовать с сохранением в ini или json? Функция в которой используется таблица:
1659141538455.png


Можно пожалуйста готовый код?
 
Решение
1659177205082.png

Lua:
script_author('chapo')
local ffi = require('ffi')
local sampev = require 'lib.samp.events'
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local inicfg = require 'inicfg'
local directIni = 'NiggerListedWords.ini'
local ini = inicfg.load(inicfg.load({
    main = {
        list = "[]"
    },
}, directIni))
inicfg.save(ini, directIni)

local renderWindow = imgui.new.bool(true)
local Add = imgui.new.char[128]('')
local List = decodeJson(ini.main.list)
local save = function()
    ini.main.list = encodeJson(List)
    inicfg.save(ini, directIni)
end

function sampev.onSendChat(text)
    for k, v in ipairs(List) do
        if text:find(v) then...

askfmaskfaosflas

Потрачен
Автор темы
1,089
511
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.

kyrtion

Известный
668
246
/home/kyrtion/Games/SAMP/moonloader/sample.lua:
local sampleJson = getWorkingDirectory()..'/config/sample.json'; local sampleList = {}
function json(filePath)
    local f = {}
    function f:read()
        local f = io.open(filePath, "r+")
        local jsonInString = f:read("*a")
        f:close()
        local jsonTable = decodeJson(jsonInString)
        return jsonTable
    end
    function f:write(t)
        f = io.open(filePath, "w")
        f:write(encodeJson(t))
        f:flush()
        f:close()
    end
    return f
end

function main()
    -- Перед цикла, как сообщение для приветствия от скрипта
    if not doesFileExist(sampleJson) then json(sampleJson):write({}) end; sampleList = json(sampleJson):read()
end

-- Добавить в таблицу по массиву и сохранить
local tempList = {
    old_text = 'OLD!',
    new_text = 'NEW!',
}
table.insert(sampleList, tempList)
json(sampleJson):write(sampleList)

-- Если 2 раза подряд сверху^ и будет так выглядит в sample json:
--[[
sample.json
[
    {
        "old_text": "OLD!",
        "new_text": "NEW!"
    },
    {
        "old_text": "OLD!",
        "new_text": "NEW!"
    },
]
]]--

-- В таком случае, если просто без секции, то можно так:
local tempMsg1 = 'hello1'
local tempMsg2 = 'hello2'
table.insert(sampleList, tempMsg1)
table.insert(sampleList, tempMsg2)
json(sampleJson):write(sampleList)

-- И получится:
--[[
sample.json:
[
    "hello1",
    "hello2"
]
]]

-- <<>>
-- Удалять с таблицы только по числовому (tonumber) массиву! А затем сохраняем.
for i=1, #sampleList do -- получаем максимальное значение массив в таблице - #sampleList, и так будет выглядит [i=1, 2], т.к. в таблице 2 без секции "hello"
    -- например, я хочу удалять где стоит в таблице без секции: "hello1"
    -- ну либо по массиву, если пользователь кликает кнопка для удаления с таблицы: if sampleList[1] then
    if sampleList[i] == "hello1" then
        table.remove(sampleList, i) -- убирается с таблицы целый объект по массиву
        json(sampleJson):write(sampleList)
    end
end
-- И что получится:
-- было: sample.json: [ "hello1", "hello2" ]. стало: sample.json: [ "hello2" ].
И ещё, настоятельно рекомендую поиграться с json'ом. если всё понял как это работает, записываешь в код
UPD: ни в коем случае нельзя записывать в таблицу где нет массив. типа того table.insert(sampleJson, 'привет') - это не нужно так делать
 
Последнее редактирование:

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,776
11,224
1659177205082.png

Lua:
script_author('chapo')
local ffi = require('ffi')
local sampev = require 'lib.samp.events'
local imgui = require 'mimgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local inicfg = require 'inicfg'
local directIni = 'NiggerListedWords.ini'
local ini = inicfg.load(inicfg.load({
    main = {
        list = "[]"
    },
}, directIni))
inicfg.save(ini, directIni)

local renderWindow = imgui.new.bool(true)
local Add = imgui.new.char[128]('')
local List = decodeJson(ini.main.list)
local save = function()
    ini.main.list = encodeJson(List)
    inicfg.save(ini, directIni)
end

function sampev.onSendChat(text)
    for k, v in ipairs(List) do
        if text:find(v) then
            sampAddChatMessage('Найдено запрещенное слово "'..v..'"', -1)
            return false
        end
    end
end

local newFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 300
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        if imgui.Begin('BlacklistedWords', renderWindow) then
            local size = imgui.GetWindowSize()
            imgui.SetCursorPosX(5)
            if imgui.Button(u8'Добавить', imgui.ImVec2(size.x - 5, 24)) then
                imgui.OpenPopup(u8'пизда')
            end
            if imgui.BeginPopupModal(u8'пизда', _, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize) then
                imgui.SetWindowSizeVec2(imgui.ImVec2(200, 150))
                imgui.InputText(u8'Слово', Add, ffi.sizeof(Add))
                if imgui.Button(u8'Добавить') then
                    table.insert(List, u8:decode(ffi.string(Add)))
                    imgui.StrCopy(Add, '')
                    save()
                    imgui.CloseCurrentPopup()
                end
                if imgui.Button(u8'Закрыть') then
                    imgui.StrCopy(Add, '')
                    imgui.CloseCurrentPopup()
                end
                imgui.EndPopup()
            end
            imgui.SetCursorPosX(5)
            if imgui.BeginChild('list', imgui.ImVec2(size.x - 10, size.y - 10 - imgui.GetCursorPosY()), true) then
                for k, v in ipairs(List) do
                    imgui.Text(u8(v))
                    imgui.SameLine()
                    imgui.SetCursorPosX(size.x - 100)
                    imgui.TextDisabled(u8'УДАЛИТЬ')
                    if imgui.IsItemClicked() then
                        table.remove(List, k)
                        save()
                    end
                end
                imgui.EndChild()
            end
            imgui.End()
        end
    end
)

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('nword', function()
        renderWindow[0] = not renderWindow[0]
    end)
    wait(-1)
end
 
  • Нравится
Реакции: kyrtion