Вопросы по Lua скриптингу

Общая тема для вопросов по разработке скриптов на языке программирования Lua, в частности под MoonLoader.
  • Задавая вопрос, убедитесь, что его нет в списке частых вопросов и что на него ещё не отвечали (воспользуйтесь поиском).
  • Поищите ответ в теме посвященной разработке Lua скриптов в MoonLoader
  • Отвечая, убедитесь, что ваш ответ корректен.
  • Старайтесь как можно точнее выразить мысль, а если проблема связана с кодом, то обязательно прикрепите его к сообщению, используя блок [code=lua]здесь мог бы быть ваш код[/code].
  • Если вопрос связан с MoonLoader-ом первым делом желательно поискать решение на wiki.

Частые вопросы

Как научиться писать скрипты? С чего начать?
Информация - Гайд - Всё о Lua скриптинге для MoonLoader(https://blast.hk/threads/22707/)
Как вывести текст на русском? Вместо русского текста у меня какие-то каракули.
Изменить кодировку файла скрипта на Windows-1251. В Atom: комбинация клавиш Ctrl+Shift+U, в Notepad++: меню Кодировки -> Кодировки -> Кириллица -> Windows-1251.
Как получить транспорт, в котором сидит игрок?
Lua:
local veh = storeCarCharIsInNoSave(PLAYER_PED)
Как получить свой id или id другого игрока?
Lua:
local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED) -- получить свой ид
local _, id = sampGetPlayerIdByCharHandle(ped) -- получить ид другого игрока. ped - это хендл персонажа
Как проверить, что строка содержит какой-то текст?
Lua:
if string.find(str, 'текст', 1, true) then
-- строка str содержит "текст"
end
Как эмулировать нажатие игровой клавиши?
Lua:
local game_keys = require 'game.keys' -- где-нибудь в начале скрипта вне функции main

setGameKeyState(game_keys.player.FIREWEAPON, -1) -- будет сэмулировано нажатие клавиши атаки
Все иды клавиш находятся в файле moonloader/lib/game/keys.lua.
Подробнее о функции setGameKeyState здесь: lua - setgamekeystate | BlastHack — DEV_WIKI(https://www.blast.hk/wiki/lua:setgamekeystate)
Как получить id другого игрока, в которого целюсь я?
Lua:
local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
  local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
  if result then -- проверить, прошло ли получение ида успешно
    -- здесь любые действия с полученным идом игрока
  end
end
Как зарегистрировать команду чата SAMP?
Lua:
-- До бесконечного цикла/задержки
sampRegisterChatCommand("mycommand", function (param)
     -- param будет содержать весь текст введенный после команды, чтобы разделить его на аргументы используйте string.match()
    sampAddChatMessage("MyCMD", -1)
end)
Крашит игру при вызове sampSendChat. Как это исправить?
Это происходит из-за бага в SAMPFUNCS, когда производится попытка отправки пакета определенными функциями изнутри события исходящих RPC и пакетов. Исправления для этого бага нет, но есть способ не провоцировать его. Вызов sampSendChat изнутри обработчика исходящих RPC/пакетов нужно обернуть в скриптовый поток с нулевой задержкой:
Lua:
function onSendRpc(id)
  -- крашит:
  -- sampSendChat('Send RPC: ' .. id)

  -- норм:
  lua_thread.create(function()
    wait(0)
    sampSendChat('Send RPC: ' .. id)
  end)
end
 
Последнее редактирование:

BaiYun

Новичок
17
0
Всем общий, ребят помогите с ошибкой, пожалуйста)
После сохранение скрипта вылезает данная ошибка - attempt to index upvalue 'imgui' (a function value)

Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
        while true do
            wait(0)

        sampRegisterChatCommand("imgui", imgui)
        imgui.Process = true
        function imgui(arg)
            main_window_state.v = not main_window_state.v
            imgui.Process = main_window_state.v
         end
         function imgui.OnDrawFrame()
             imgui.Begin("Start menu")
             imgui.text("123123")
             imgui.End()
         end   
    end
end
 

Dmitriy Makarov

25.05.2021
Проверенный
2,484
1,114
Всем общий, ребят помогите с ошибкой, пожалуйста)
После сохранение скрипта вылезает данная ошибка - attempt to index upvalue 'imgui' (a function value)

Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
        while true do
            wait(0)

        sampRegisterChatCommand("imgui", imgui)
        imgui.Process = true
        function imgui(arg)
            main_window_state.v = not main_window_state.v
            imgui.Process = main_window_state.v
         end
         function imgui.OnDrawFrame()
             imgui.Begin("Start menu")
             imgui.text("123123")
             imgui.End()
         end  
    end
end
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end

Хай. Можете помочь сделать скрипт, который будет отправлять команды после того, когда в чате найдет текст "объявление". У работает, если я сам пишу "объявление" в чат. А если просто в чате, ничего не происходит. Вот код

Код:
local sampev = require 'lib.samp.events'
local activation = false


function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("adlvnews", cmd)
end
function sampev.onServerMessage(color, text)
    if activation then
        if text:find("Объявление") then
            lua_thread.create(function()
                sampSendChat("/flood 2")
                wait(1000)
                sampSendChat("/ad LVn - Свободная строка объявлений - 103.3 FM")
                wait(2000)
                sampSendChat("/flood /adsend 0")
            end)
        end
    end
end
function sampev.onShowDialog(id, style, title, button1, button2, text)
    if activation then
        if title:find("Подтверждение") then
            sampSendDialogResponse(id, 1, 0, _)
            return false
        end
    end
end
function cmd()
    if activation then
        activation = false
        printStringNow("AdLvNews - OFF", 3000)
    else
        activation = true
        printStringNow("AdLvNews - ON", 3000)
    end
end
Возможно, строка имеет цвет или же нужно увеличить количество слов для поиска. Скинь строку с нужным тебе текстом из чатлога.
И ещё, что за команда "/flood"? Она серверная или же в другом скрипте? Если в другом скрипте, то sampSendChat не будет её отправлять. Используй для таких целей sampProcessChatInput. Рядом со строками пример добавил.
Lua:
local sampev = require 'lib.samp.events'
local activation = false


function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("adlvnews", function()
        activation = not activation
        printStringNow("AdLvNews - "..(activation and "ON" or "OFF"), 3000)
    end)
    wait(-1)
end

function sampev.onServerMessage(color, text)
    if activation then
        if text:find("Объявление") then
            lua_thread.create(function()
                sampSendChat("/flood 2") -- sampProcessChatInput("/flood 2")
                wait(1000)
                sampSendChat("/ad LVn - Свободная строка объявлений - 103.3 FM")
                wait(2000)
                sampSendChat("/flood /adsend 0") -- sampProcessChatInput("/flood /adsend 0")
            end)
        end
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if activation then
        if title:find("Подтверждение") then
            sampSendDialogResponse(id, 1, 0, nil)
            return false
        end
    end
end

I want to use this in my ImGui code, how do I do it?
This is C++ code. You need to first translate it into Lua and then add it to your script.
 
Последнее редактирование:
  • Нравится
Реакции: MLycoris

BaiYun

Новичок
17
0
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end


Возможно, строка имеет цвет или же нужно увеличить количество слов для поиска. Скинь строку с нужным тебе текстом из чатлога.
И ещё, что за команда "/flood"? Она серверная или же в другом скрипте? Если в другом скрипте, то sampSendChat не будет её отправлять. Используй для таких целей sampProcessChatInput. Рядом со строками пример добавил.
Lua:
local sampev = require 'lib.samp.events'
local activation = false


function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("adlvnews", function()
        activation = not activation
        printStringNow("AdLvNews - "..(activation and "ON" or "OFF"), 3000)
    end)
    wait(-1)
end

function sampev.onServerMessage(color, text)
    if activation then
        if text:find("Объявление") then
            lua_thread.create(function()
                sampSendChat("/flood 2") -- sampProcessChatInput("/flood 2")
                wait(1000)
                sampSendChat("/ad LVn - Свободная строка объявлений - 103.3 FM")
                wait(2000)
                sampSendChat("/flood /adsend 0") -- sampProcessChatInput("/flood /adsend 0")
            end)
        end
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if activation then
        if title:find("Подтверждение") then
            sampSendDialogResponse(id, 1, 0, nil)
            return false
        end
    end
end


This is C++ code. You need to first translate it into Lua and then add it to your script.
теперь такая ошибка вылезла - attempt to index global 'main_window_state' (a nil value)
 

Dmitriy Makarov

25.05.2021
Проверенный
2,484
1,114
теперь такая ошибка вылезла - attempt to index global 'main_window_state' (a nil value)
Точно.
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local main_window_state = imgui.ImBool(false)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end
 

Less_Go

Новичок
12
1
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end


Возможно, строка имеет цвет или же нужно увеличить количество слов для поиска. Скинь строку с нужным тебе текстом из чатлога.
И ещё, что за команда "/flood"? Она серверная или же в другом скрипте? Если в другом скрипте, то sampSendChat не будет её отправлять. Используй для таких целей sampProcessChatInput. Рядом со строками пример добавил.
Lua:
local sampev = require 'lib.samp.events'
local activation = false


function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("adlvnews", function()
        activation = not activation
        printStringNow("AdLvNews - "..(activation and "ON" or "OFF"), 3000)
    end)
    wait(-1)
end

function sampev.onServerMessage(color, text)
    if activation then
        if text:find("Объявление") then
            lua_thread.create(function()
                sampSendChat("/flood 2") -- sampProcessChatInput("/flood 2")
                wait(1000)
                sampSendChat("/ad LVn - Свободная строка объявлений - 103.3 FM")
                wait(2000)
                sampSendChat("/flood /adsend 0") -- sampProcessChatInput("/flood /adsend 0")
            end)
        end
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if activation then
        if title:find("Подтверждение") then
            sampSendDialogResponse(id, 1, 0, nil)
            return false
        end
    end
end


This is C++ code. You need to first translate it into Lua and then add it to your script.
Спасибо. Решил проблему немного другим способом. А за sampProcessChatInput отдельное спасибо. Проебался немного
 

BaiYun

Новичок
17
0
Точно.
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local main_window_state = imgui.ImBool(false)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end
Спасибо, я уже нашёл проблему в коде
 

sssilvian

Активный
237
25
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end


Возможно, строка имеет цвет или же нужно увеличить количество слов для поиска. Скинь строку с нужным тебе текстом из чатлога.
И ещё, что за команда "/flood"? Она серверная или же в другом скрипте? Если в другом скрипте, то sampSendChat не будет её отправлять. Используй для таких целей sampProcessChatInput. Рядом со строками пример добавил.
Lua:
local sampev = require 'lib.samp.events'
local activation = false


function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand("adlvnews", function()
        activation = not activation
        printStringNow("AdLvNews - "..(activation and "ON" or "OFF"), 3000)
    end)
    wait(-1)
end

function sampev.onServerMessage(color, text)
    if activation then
        if text:find("Объявление") then
            lua_thread.create(function()
                sampSendChat("/flood 2") -- sampProcessChatInput("/flood 2")
                wait(1000)
                sampSendChat("/ad LVn - Свободная строка объявлений - 103.3 FM")
                wait(2000)
                sampSendChat("/flood /adsend 0") -- sampProcessChatInput("/flood /adsend 0")
            end)
        end
    end
end

function sampev.onShowDialog(id, style, title, button1, button2, text)
    if activation then
        if title:find("Подтверждение") then
            sampSendDialogResponse(id, 1, 0, nil)
            return false
        end
    end
end


This is C++ code. You need to first translate it into Lua and then add it to your script.
I can't find a theme that is in lua, can you help me?

Точно.
Lua:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local main_window_state = imgui.ImBool(false)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function()
        main_window_state.v = not main_window_state.v
    end)
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Start menu")
        imgui.Text("123123")
        imgui.End()
    end
end
So I have 2 scripts where in one script the theme works perfectly and in the other one the script works, but the theme is not changing.
1) Functional script:
Lua:
local imgui = require 'imgui'
local fWindow = imgui.ImBool(false)
local inicfg = require 'inicfg'
local HLcfg = inicfg.load({
    Raspuns = {
        [1]  = " ",
        [2]  = " ",
        [3]  = " ",
        [4]  = " ",
        [5]  = " ",
        [6]  = " ",
        [7]  = " ",
        [8]  = " ",
        [9]  = " ",
        [10] = " ",
        [11] = " ",
        [12] = " ",
        [13] = " ",
        [14] = " ",
        [15] = " "
    },
    Intrebare1 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare2 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare3 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare4 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare5 = {
        rand2 = " ",
        rand1 = " "
       },
    Intrebare6 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare7 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare8 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare9 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare10 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare11 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare12 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare13 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare14 = {
        rand2 = " ",
        rand1 = " "
    },
    Intrebare15 = {
        rand2 = " ",
        rand1 = " "
    }
}, "TestHelper.ini")

local function spairs(t, order)
    local keys = {}
    for k in pairs(t) do keys[#keys+1] = k end
    if order then table.sort(keys, function(a,b) return order(t, a, b) end) else table.sort(keys) end
    local i = 0
    return function() i = i + 1 if keys[i] then return keys[i], t[keys[i]] end end
end

local function find_config(file)
    local workdir = getWorkingDirectory()
    local paths = {
        workdir..[[\config\]]..file..'.ini',
        workdir..[[\config\]]..file,
        file,
    }
    for _, path in ipairs(paths) do
        if doesFileExist(path) then
            return path
        end
    end
    return nil
end

local function ini_value(val)
    local lwr = val:lower()
    if lwr == 'true' then return true end
    if lwr == 'false' then return false end
    return tonumber(val) or val
end

inicfg.save = function(data, file, order)
    assert(type(data) == 'table')
    local file = file or (script.this.filename..'.ini')
    local path = find_config(file)
    local dir
    if not path then
        if file:match('^%a:[\\/]') then
            dir = file:match('(.+[\\/]).-')
            path = file
        else
            if file:sub(-4):lower() ~= '.ini' then
                file = file..'.ini'
            end
            dir = getWorkingDirectory()..[[\config\]]
            path = dir..file
        end
    end
    if dir and not doesDirectoryExist(dir) then
        createDirectory(dir)
    end
    local f = io.open(path, 'w')
    if f then
        for secname, secdata in spairs(data, order) do
            assert(type(secdata) == 'table')
            f:write('['..tostring(secname)..']\n')
            for key, value in pairs(secdata) do
                f:write(tostring(key)..' = '..tostring(value)..'\n')
            end
            f:write('\n')
        end
        f:close()
        return true
    end
    return false
end

function sortConfig(t, a, b)
    local reg = "(%d+)$"
    if not a:find(reg) and not b:find(reg) then return true end
    if not a:find(reg) and b:find(reg) then return true end
    if a:find(reg) and not b:find(reg) then return false end

    local an, bn = a:match(reg), b:match(reg)
    if not tonumber(an) then return false end
    if not tonumber(bn) then return true end
    return tonumber(an) < tonumber(bn)
end

function main()
    inicfg.save(HLcfg, "TestHelper.ini", sortConfig)
    sampRegisterChatCommand('testlog', function() fWindow.v = not fWindow.v end)

    wait(1000)
    sampAddChatMessage("{00ff78}[TestHelper]{ffffff} Loaded. Made by {00ff78}21Cristi", 0x00ff78)
    sampAddChatMessage("{00ff78}[TestHelper]{ffffff} Scrie {00ff78}/testlog{ffffff} pentru a deschide meniul interactiv.", 0x00ff78)
    while true do
        wait(0)
        imgui.Process = fWindow.v
    end
end

function imgui.OnDrawFrame()
        local sw, sh = getScreenResolution()
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 1.2, sh / 1.8), imgui.Cond.FirstUseEver, imgui.ImVec2(-0.3, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(215, 620), imgui.Cond.FirstUseEver)
    if fWindow.v then
        imgui.Begin('                    Tester Menu', fWindow, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
        
    imgui.SetCursorPos(imgui.ImVec2(30, 30))
    if imgui.Button('Reguli test',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
    sampSendChat("/cw Daca dai /q, esti picat.")
    wait(1000)
    sampSendChat("/cw Daca iei crash, ai 3 minute sa revii sau esti picat.")
    wait(1000)
    sampSendChat("/cw Daca te pui AFK, esti picat.")
    wait(1000)
    sampSendChat("/cw Ai un minut la dispozitie sa raspunzi la fiecare intrebare.")
    wait(1000)
    sampSendChat("/cw Daca esti prins pe forumul SFSI, esti declarat picat.")
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 80))
    if imgui.Button('Intrebarea 1',imgui.ImVec2(150, 25)) then 
        lua_thread.create(function()
        sampSendChat("/cw 1) "..HLcfg.Intrebare1.rand1)
        sampSendChat("/cw 1) "..HLcfg.Intrebare1.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[1])
        end)
    end
                    
    imgui.SetCursorPos(imgui.ImVec2(30, 110))
    if imgui.Button('Intrebarea 2',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 2) "..HLcfg.Intrebare2.rand1)
        sampSendChat("/cw 2) "..HLcfg.Intrebare2.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[2])
    end)
    end

    imgui.SetCursorPos(imgui.ImVec2(30, 140))
    if imgui.Button('Intrebarea 3',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 3) "..HLcfg.Intrebare3.rand1)
        sampSendChat("/cw 3) "..HLcfg.Intrebare3.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[3])
    end)
    end

    imgui.SetCursorPos(imgui.ImVec2(30, 170))
    if imgui.Button('Intrebarea 4',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 4) "..HLcfg.Intrebare4.rand1)
        sampSendChat("/cw 4) "..HLcfg.Intrebare4.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[4])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 200))
    if imgui.Button('Intrebarea 5',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 5) "..HLcfg.Intrebare5.rand1)
        sampSendChat("/cw 5) "..HLcfg.Intrebare5.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[5])
    end)
    end

    imgui.SetCursorPos(imgui.ImVec2(30, 230))
    if imgui.Button('Intrebarea 6',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 6) "..HLcfg.Intrebare6.rand1)
        sampSendChat("/cw 6) "..HLcfg.Intrebare6.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[6])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 260))
    if imgui.Button('Intrebarea 7',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 7) "..HLcfg.Intrebare7.rand1)
        sampSendChat("/cw 7) "..HLcfg.Intrebare7.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[7])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 290))
    if imgui.Button('Intrebarea 8',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 8) "..HLcfg.Intrebare8.rand1)
        sampSendChat("/cw 8) "..HLcfg.Intrebare8.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[8])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 320))
    if imgui.Button('Intrebarea 9',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 9) "..HLcfg.Intrebare9.rand1)
        sampSendChat("/cw 9) "..HLcfg.Intrebare9.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[9])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 350))
    if imgui.Button('Intrebarea 10',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 10) "..HLcfg.Intrebare10.rand1)
        sampSendChat("/cw 10) "..HLcfg.Intrebare10.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[10])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 380))
    if imgui.Button('Intrebarea 11',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 11) "..HLcfg.Intrebare11.rand1)
        sampSendChat("/cw 11) "..HLcfg.Intrebare11.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[11])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 410))
    if imgui.Button('Intrebarea 12',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 12) " ..HLcfg.Intrebare12.rand1)
        sampSendChat("/cw 12) "..HLcfg.Intrebare12.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[12])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 440))
    if imgui.Button('Intrebarea 13',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 13) "..HLcfg.Intrebare13.rand1)
        sampSendChat("/cw 13) "..HLcfg.Intrebare13.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[13])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 470))
    if imgui.Button('Intrebarea 14',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 14) "..HLcfg.Intrebare14.rand1)
        sampSendChat("/cw 14) "..HLcfg.Intrebare14.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[14])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 500))
    if imgui.Button('Intrebarea 15',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
        sampSendChat("/cw 15) "..HLcfg.Intrebare15.rand1)
        sampSendChat("/cw 15) "..HLcfg.Intrebare15.rand2)
        sampAddChatMessage("{00ff78}[TestHelper]{FFFFFF} Raspuns corect: {00ff78}"..HLcfg.Raspuns[15])
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 550))
    if imgui.Button('Mesaj admis',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
    sampSendChat("/cw Felicitari, ai trecut testul factiunii.")
    end)
    end
    
    imgui.SetCursorPos(imgui.ImVec2(30, 580))
    if imgui.Button('Mesaj picat',imgui.ImVec2(150, 25)) then
    lua_thread.create(function()
    sampSendChat("/cw Din pacate, ai picat testul factiunii. Succes data viitoare!")
    end)
    end
    imgui.End()
    end
end
function apply_custom_style()
       imgui.SwitchContext()
       local style = imgui.GetStyle()
       local colors = style.Colors
       local clr = imgui.Col
       local ImVec4 = imgui.ImVec4
       local ImVec2 = imgui.ImVec2

    style.WindowPadding = ImVec2(15, 15)
    style.WindowRounding = 10.0
    style.FramePadding = ImVec2(5, 5)
    style.ItemSpacing = ImVec2(4, 6)
    style.ItemInnerSpacing = ImVec2(4, 6)
    style.IndentSpacing = 25.0
    style.ScrollbarSize = 15.0
    style.ScrollbarRounding = 15.0
    style.GrabMinSize = 7.0
    style.GrabRounding = 7.0
    style.ChildWindowRounding = 7.0
    style.FrameRounding = 6.0
 

    colors[clr.Text] = ImVec4(0.95, 0.96, 0.98, 1.00)
    colors[clr.TextDisabled] = ImVec4(0.36, 0.42, 0.47, 1.00)
    colors[clr.WindowBg] = ImVec4(0.11, 0.15, 0.17, 0.9)
    colors[clr.ChildWindowBg] = ImVec4(0.15, 0.18, 0.22, 0.0)
    colors[clr.PopupBg] = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.Border] = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow] = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.FrameBg] = ImVec4(0.20, 0.25, 0.29, 0.05)
    colors[clr.FrameBgHovered] = ImVec4(0.12, 0.20, 0.28, 0.05)
    colors[clr.FrameBgActive] = ImVec4(0.09, 0.12, 0.14, 0.05)
    colors[clr.TitleBg] = ImVec4(0.09, 0.12, 0.14, 0.65)
    colors[clr.TitleBgCollapsed] = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.TitleBgActive] = ImVec4(0.08, 0.10, 0.12, 1.00)
    colors[clr.MenuBarBg] = ImVec4(0.15, 0.18, 0.22, .00)
    colors[clr.ScrollbarBg] = ImVec4(0.02, 0.02, 0.02, 0.39)
    colors[clr.ScrollbarGrab] = ImVec4(0.20, 0.25, 0.29, 1.00)
    colors[clr.ScrollbarGrabHovered] = ImVec4(0.18, 0.22, 0.25, 1.00)
    colors[clr.ScrollbarGrabActive] = ImVec4(0.09, 0.21, 0.31, 1.00)
    colors[clr.ComboBg] = ImVec4(0.20, 0.25, 0.29, 1.00)
    colors[clr.CheckMark] = ImVec4(0.28, 0.56, 1.00, 1.00)
    colors[clr.SliderGrab] = ImVec4(0.28, 0.56, 1.00, 1.00)
    colors[clr.SliderGrabActive] = ImVec4(0.37, 0.61, 1.00, 1.00)
    colors[clr.Button] = ImVec4(0.20, 0.25, 0.29, 0.6)
    colors[clr.ButtonHovered] = ImVec4(0.28, 0.56, 1.00, 0.6)
    colors[clr.ButtonActive] = ImVec4(0.06, 0.53, 0.98, 0.6)
    colors[clr.Header] = ImVec4(0.20, 0.25, 0.29, 0.55)
    colors[clr.HeaderHovered] = ImVec4(0.26, 0.59, 0.98, 0.80)
    colors[clr.HeaderActive] = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip] = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered] = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive] = ImVec4(0.06, 0.05, 0.07, 1.00)
    colors[clr.CloseButton] = ImVec4(0.40, 0.39, 0.38, 0.16)
    colors[clr.CloseButtonHovered] = ImVec4(0.40, 0.39, 0.38, 0.39)
    colors[clr.CloseButtonActive] = ImVec4(0.40, 0.39, 0.38, 1.00)
    colors[clr.PlotLines] = ImVec4(1.61, 2.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered] = ImVec4(1.00, 2.43, 0.35, 1.00)
    colors[clr.PlotHistogram] = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered] = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.TextSelectedBg] = ImVec4(0.25, 1.00, 0.00, 0.43)
    colors[clr.ModalWindowDarkening] = ImVec4(1.00, 0.98, 0.95, 0.0)
end
apply_custom_style()
and 2) the code where the theme doesn't change at all:

Lua:
local imgui = require 'mimgui'
local samp = require 'samp.events'
local sampev = require("lib.samp.events")
require "lib.moonloader"


local sw, sh = 355, 425
local active = imgui.new.bool(false)
local checkbox = imgui.new.bool(false)
local ffi = require "ffi"
local buf = imgui.new.char[24]()
function main()
    wait(1000)
    sampRegisterChatCommand("sfsi", function() active[0] = not active[0] end)
    sampAddChatMessage("{ff0078}[SFSI Helper]{ffffff} Loaded. Made by {ff0078}21Cristi", 0xff0078)
    sampAddChatMessage("{ff0078}[SFSI Helper]{ffffff} Scrie {ff0078}/sfsi{ffffff} pentru a deschide meniul interactiv.", 0xff0078)
    while true do
        wait(0)
    end
end

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
    imgui.StyleColorsDark()
end)

local mainFrame = imgui.OnFrame(function() return active[0] end, function(self)
local sw, sh = getScreenResolution()
    imgui.SetNextWindowSize(imgui.ImVec2(sw / 5.4, sh / 2.5), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 1.6, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(-0.3, 0.5))
    imgui.Begin('            SFSI Helper', active)
    if imgui.BeginTabBar('Tabs') then
        if imgui.BeginTabItem('Flying') then
            imgui.Text('ID-ul clientului (conectat pe server):')
        imgui.InputText("ID", buf, ffi.sizeof(buf), imgui.InputTextFlags.CharsDecimal)
                imgui.Text('Intrebi pe /sx daca clientul a fost acceptat de altcineva')
        imgui.SetCursorPos(imgui.ImVec2(10, 115))
if imgui.Button("Intreaba", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end
imgui.Text('Anunta pe /f ca ai preluat un client')
        imgui.SetCursorPos(imgui.ImVec2(10, 160))
if imgui.Button("Anunta", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/f %s (%s) la mine pentru licenta de Flying.", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end

imgui.Text('Incepe lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 205))
if imgui.Button("Startlesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/startlesson %s flying", sampGetPlayerNickname(ffi.string(buf))))
    end
end

imgui.Text('Instructiunile pentru test')
        imgui.SetCursorPos(imgui.ImVec2(10, 250))
if imgui.Button("Instructiuni", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
    sampSendChat("Condu Maverick-ul pe orice aeroport doresti, apoi aterizezi.")
    sampSendChat("Odata ajuns, reia zborul si intoarce-te de unde am plecat.")
    sampSendChat("Daca Maverick-ul atinge sub 950.0HP, esti picat. Poti verifica cu /dl HP-ul.")
end
end
imgui.Text('Acorda licenta clientului (in caz ca a trecut testul)')

        imgui.SetCursorPos(imgui.ImVec2(10, 295))
if imgui.Button("Acorda", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/say Felicitari, ai trecut testul pentru licenta de Flying.")
       sampSendChat(string.format("/givelicense %s flying", sampGetPlayerNickname(ffi.string(buf))))
end
end
imgui.Text('Anunti clientul ca a picat testul de licenta')
        imgui.SetCursorPos(imgui.ImVec2(10, 340))
if imgui.Button("Picat", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("Din pacate, ai picat testul pentru licenta de Flying.")
end
end

imgui.Text('Opreste lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 385))
if imgui.Button("Stoplesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
        sampSendChat("/stoplesson "..ffi.string(buf))
end
end

            imgui.EndTabItem()
        end
                if imgui.BeginTabItem('Sailing') then
            imgui.Text('ID-ul clientului (conectat pe server):')
        imgui.InputText("ID", buf, ffi.sizeof(buf), imgui.InputTextFlags.CharsDecimal)
                imgui.Text('Intrebi pe /sx daca clientul a fost acceptat de altcineva')
        imgui.SetCursorPos(imgui.ImVec2(10, 115))
if imgui.Button("Intreaba", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end
imgui.Text('Anunta pe /f ca ai preluat un client')
        imgui.SetCursorPos(imgui.ImVec2(10, 160))
if imgui.Button("Anunta", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/f %s (%s) la mine pentru licenta de sailing.", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end

imgui.Text('Incepe lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 205))
if imgui.Button("Startlesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/startlesson %s sailing", sampGetPlayerNickname(ffi.string(buf))))
    end
end

imgui.Text('Ghidarile pentru test')
        imgui.SetCursorPos(imgui.ImVec2(10, 250))
if imgui.Button("Sail LS", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
    sampSendChat("Condu barca pana la farul de pe plaja. Odata ajuns, te intorci inapoi.")
    sampSendChat("Daca barca atinge sub 950.0 HP, esti picat. Poti verifica HP-ul cu comanda /dl")
end
end
        imgui.SetCursorPos(imgui.ImVec2(95, 250))
if imgui.Button("Sail LV", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
    sampSendChat("Condu barca pana la fosta baza NG (vaporul de langa Aero SF). Odata ajuns, te intorci inapoi.")
    sampSendChat("Daca barca atinge sub 950.0 HP, esti picat. Poti verifica HP-ul cu comanda /dl")
end
end
        imgui.SetCursorPos(imgui.ImVec2(180, 250))
if imgui.Button("Sail SF", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
    sampSendChat("Condu barca pana la docurile din Bayside. Odata ajuns, te intorci inapoi.")
    sampSendChat("Daca barca atinge sub 950.0 HP, esti picat. Poti verifica HP-ul cu comanda /dl")
end
end
imgui.Text('Acorda licenta clientului (in caz ca a trecut testul)')

        imgui.SetCursorPos(imgui.ImVec2(10, 295))
if imgui.Button("Acorda", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/say Felicitari, ai trecut testul pentru licenta de Sailing.")
       sampSendChat(string.format("/givelicense %s sailing", sampGetPlayerNickname(ffi.string(buf))))
end
end
imgui.Text('Anunti clientul ca a picat testul de licenta')
        imgui.SetCursorPos(imgui.ImVec2(10, 340))
if imgui.Button("Picat", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("Din pacate, ai picat testul pentru licenta de Sailing.")
end
end

imgui.Text('Opreste lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 385))
if imgui.Button("Stoplesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
        sampSendChat("/stoplesson "..ffi.string(buf))
end
end

            imgui.EndTabItem()
        end
               if imgui.BeginTabItem('Fishing') then
            imgui.Text('ID-ul clientului (conectat pe server):')
        imgui.InputText("ID", buf, ffi.sizeof(buf), imgui.InputTextFlags.CharsDecimal)
                imgui.Text('Intrebi pe /sx daca clientul a fost acceptat de altcineva')
        imgui.SetCursorPos(imgui.ImVec2(10, 115))
if imgui.Button("Intreaba", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end
imgui.Text('Anunta pe /f ca ai preluat un client')
        imgui.SetCursorPos(imgui.ImVec2(10, 160))
if imgui.Button("Anunta", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/f %s (%s) la mine pentru licenta de Fishing.", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end

imgui.Text('Incepe lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 205))
if imgui.Button("Startlesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/startlesson %s fishing", sampGetPlayerNickname(ffi.string(buf))))
    end
end

imgui.Text('Setul de intrebari pentru test')
        imgui.SetCursorPos(imgui.ImVec2(10, 250))
if imgui.Button("Intrebarea 1", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Cu ce comanda pescuiesti?")
end
end
        imgui.SetCursorPos(imgui.ImVec2(95, 250))
if imgui.Button("Intrebarea 2", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Unde pescuiesti?")
end
end
        imgui.SetCursorPos(imgui.ImVec2(180, 250))
if imgui.Button("Intrebarea 3", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Unde duci pestele prins?")
end
end
        imgui.SetCursorPos(imgui.ImVec2(265, 250))
if imgui.Button("Intrebarea 4", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Ce primesti daca pescuiesti fara licenta?")
end
end
imgui.Text('Acorda licenta clientului (in caz ca a trecut testul)')

        imgui.SetCursorPos(imgui.ImVec2(10, 295))
if imgui.Button("Acorda", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/say Felicitari, ai trecut testul pentru licenta de Fishing.")
       sampSendChat(string.format("/givelicense %s fishing", sampGetPlayerNickname(ffi.string(buf))))
end
end
imgui.Text('Anunti clientul ca a picat testul de licenta')
        imgui.SetCursorPos(imgui.ImVec2(10, 340))
if imgui.Button("Picat", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("Din pacate, ai picat testul pentru licenta de Fishing.")
end
end

imgui.Text('Opreste lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 385))
if imgui.Button("Stoplesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
        sampSendChat("/stoplesson "..ffi.string(buf))
end
end

            imgui.EndTabItem()
        end
                if imgui.BeginTabItem('Weapon') then
            imgui.Text('ID-ul clientului (conectat pe server):')
        imgui.InputText("ID", buf, ffi.sizeof(buf), imgui.InputTextFlags.CharsDecimal)
                imgui.Text('Intrebi pe /sx daca clientul a fost acceptat de altcineva')
        imgui.SetCursorPos(imgui.ImVec2(10, 115))
if imgui.Button("Intreaba", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end
imgui.Text('Anunta pe /f ca ai preluat un client')
        imgui.SetCursorPos(imgui.ImVec2(10, 160))
if imgui.Button("Anunta", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/f %s (%s) la mine pentru licenta de Weapon.", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end

imgui.Text('Incepe lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 205))
if imgui.Button("Startlesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/startlesson %s weapon", sampGetPlayerNickname(ffi.string(buf))))
    end
end

imgui.Text('Setul de intrebari pentru test')
        imgui.SetCursorPos(imgui.ImVec2(10, 250))
if imgui.Button("Intrebarea 1", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Enumera-mi 10 arme ilegale cu foc din GTA San Andreas.")
end
end
        imgui.SetCursorPos(imgui.ImVec2(95, 250))
if imgui.Button("Intrebarea 2", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Enumera-mi 8 safezone-uri.")
end
end
        imgui.SetCursorPos(imgui.ImVec2(180, 250))
if imgui.Button("Intrebarea 3", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Ce este interzis sa faci in aceste zone?")
end
end
        imgui.SetCursorPos(imgui.ImVec2(265, 250))
if imgui.Button("Intrebarea 4", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Cu ce comanda pescuiesti?")
end
end
imgui.Text('Acorda licenta clientului (in caz ca a trecut testul)')

        imgui.SetCursorPos(imgui.ImVec2(10, 295))
if imgui.Button("Acorda", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/say Felicitari, ai trecut testul pentru licenta de Weapon.")
       sampSendChat(string.format("/givelicense %s weapon", sampGetPlayerNickname(ffi.string(buf))))
end
end
imgui.Text('Anunti clientul ca a picat testul de licenta')
        imgui.SetCursorPos(imgui.ImVec2(10, 340))
if imgui.Button("Picat", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("Din pacate, ai picat testul pentru licenta de Weapon.")
end
end

imgui.Text('Opreste lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 385))
if imgui.Button("Stoplesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
        sampSendChat("/stoplesson "..ffi.string(buf))
end
end

            imgui.EndTabItem()
        end
                if imgui.BeginTabItem('Materials') then
            imgui.Text('ID-ul clientului (conectat pe server):')
        imgui.InputText("ID", buf, ffi.sizeof(buf), imgui.InputTextFlags.CharsDecimal)
                imgui.Text('Intrebi pe /sx daca clientul a fost acceptat de altcineva')
        imgui.SetCursorPos(imgui.ImVec2(10, 115))
if imgui.Button("Intreaba", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/sx L-a acceptat cineva pe %s (%s) ?", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end
imgui.Text('Anunta pe /f ca ai preluat un client')
        imgui.SetCursorPos(imgui.ImVec2(10, 160))
if imgui.Button("Anunta", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/f %s (%s) la mine pentru licenta de Materials.", sampGetPlayerNickname(ffi.string(buf)), ffi.string(buf)))
    end
end

imgui.Text('Incepe lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 205))
if imgui.Button("Startlesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
sampSendChat(string.format("/startlesson %s materials", sampGetPlayerNickname(ffi.string(buf))))
    end
end

imgui.Text('Setul de intrebari pentru test')
        imgui.SetCursorPos(imgui.ImVec2(10, 250))
if imgui.Button("Intrebarea 1", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Cu ce comanda cumperi materiale?")
end
end
        imgui.SetCursorPos(imgui.ImVec2(95, 250))
if imgui.Button("Intrebarea 2", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Unde nu ai voie sa vinzi arme?")
end
end
        imgui.SetCursorPos(imgui.ImVec2(180, 250))
if imgui.Button("Intrebarea 3", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Enumera-mi 5 safezone-uri.")
end
end
        imgui.SetCursorPos(imgui.ImVec2(265, 250))
if imgui.Button("Intrebarea 4", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/cw Cu ce comanda vinzi o arma?")
end
end
imgui.Text('Acorda licenta clientului (in caz ca a trecut testul)')

        imgui.SetCursorPos(imgui.ImVec2(10, 295))
if imgui.Button("Acorda", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("/say Felicitari, ai trecut testul pentru licenta de Materials.")
       sampSendChat(string.format("/givelicense %s materials", sampGetPlayerNickname(ffi.string(buf))))
end
end
imgui.Text('Anunti clientul ca a picat testul de licenta')
        imgui.SetCursorPos(imgui.ImVec2(10, 340))
if imgui.Button("Picat", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
       sampSendChat("Din pacate, ai picat testul pentru licenta de Materials.")
end
end

imgui.Text('Opreste lectia cu clientul')
        imgui.SetCursorPos(imgui.ImVec2(10, 385))
if imgui.Button("Stoplesson", imgui.ImVec2(80, 20)) then
    if ffi.string(buf) ~= "" then
        sampSendChat("/stoplesson "..ffi.string(buf))
end
end

            imgui.EndTabItem()
        end
        imgui.EndTabBar()
    end
    imgui.End()
end)
 
Последнее редактирование:
  • Эм
Реакции: qdIbp

BaiYun

Новичок
17
0
Не выводится в чат значение из конфига. Что делать?

code:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local inicfg = require 'inicfg'
local directini = "moonloader\\config.ini"
local mainini = inicfg.load(nil, directini)
local stateini = inicfg.save(mainini, directini)
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    while true do wait(0)
    end
    sampRegisterChatCommand("getinfo", getinfo)
    sampRegisterChatCommand("setinfo", setinfo)
    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(id)
end
function getinfo(arg)
    sampAddChatMessage(mainini.config.name, -1)
end

function setinfo(arg)
    -- body
end
 

YarikVL

Известный
Проверенный
4,795
1,814
Не выводится в чат значение из конфига. Что делать?

code:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local inicfg = require 'inicfg'
local directini = "moonloader\\config.ini"
local mainini = inicfg.load(nil, directini)
local stateini = inicfg.save(mainini, directini)
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    while true do wait(0)
    end
    sampRegisterChatCommand("getinfo", getinfo)
    sampRegisterChatCommand("setinfo", setinfo)
    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(id)
end
function getinfo(arg)
    sampAddChatMessage(mainini.config.name, -1)
end

function setinfo(arg)
    -- body
end
Перенести это надо:
CB8B58E3-71F6-46E6-9ADE-1257024E4759.jpeg
И у тебя в конфиге ключ config есть?
Если не ошибаюсь, при открытии твоего файла ini должно быть так:
[config]
name = "Значение твое"
 

Smeruxa

Известный
1,308
688
Не выводится в чат значение из конфига. Что делать?

code:
require "lib.moonloader"
local encoding = require "encoding"
local sampev = require 'lib.samp.events'
local imgui = require 'imgui'
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local inicfg = require 'inicfg'
local directini = "moonloader\\config.ini"
local mainini = inicfg.load(nil, directini)
local stateini = inicfg.save(mainini, directini)
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(100) end
    while true do wait(0)
    end
    sampRegisterChatCommand("getinfo", getinfo)
    sampRegisterChatCommand("setinfo", setinfo)
    _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    nick = sampGetPlayerNickname(id)
end
function getinfo(arg)
    sampAddChatMessage(mainini.config.name, -1)
end

function setinfo(arg)
    -- body
end
очень много мусора лишнего
Lua:
require "lib.moonloader"
local inicfg = require 'inicfg'

local HLcfg = inicfg.load({
    config = {
        name = ""  
    }
}, "test.ini")
inicfg.save(HLcfg, "test.ini")

function save()
    inicfg.save(HLcfg, "test.ini")
end

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("getinfo", function()
        print(HLcfg.config.name)
    end)
    sampRegisterChatCommand("setinfo", function(arg)
        HLcfg.config.name = arg
        save()
        print("arg name have new value -> "..arg)
    end)
    wait(-1)
end
 
  • Нравится
Реакции: YarikVL

BaiYun

Новичок
17
0
очень много мусора лишнего
Lua:
require "lib.moonloader"
local inicfg = require 'inicfg'

local HLcfg = inicfg.load({
    config = {
        name = "" 
    }
}, "test.ini")
inicfg.save(HLcfg, "test.ini")

function save()
    inicfg.save(HLcfg, "test.ini")
end

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("getinfo", function()
        print(HLcfg.config.name)
    end)
    sampRegisterChatCommand("setinfo", function(arg)
        HLcfg.config.name = arg
        save()
        print("arg name have new value -> "..arg)
    end)
    wait(-1)
end
Я знаю, я луа изучаю сижу поэтому и мусора много

Перенести это надо:
Посмотреть вложение 193921
И у тебя в конфиге ключ config есть?
Если не ошибаюсь, при открытии твоего файла ini должно быть так:
[config]
name = "Значение твое"
ini файл такой и есть у меня
 

YarikVL

Известный
Проверенный
4,795
1,814
Я знаю, я луа изучаю сижу поэтому и мусора много
Советую:

ini файл такой и есть у меня
У тебя скорее всего вообще не регистрируются такие команды, потому что бесконечный цикл запускается и не дает выполняться коду дальше ( если я не ошибаюсь то оно так работает )
И у тебя в конфиге ключ config есть?
Ключ это не название файла, а так сказать таблица, к которой твой lua файл обращается. Ну в роликах по ссылке выше - автор рассказывает про эти ключи.
при открытии твоего файла ini должно быть так:
[config] name = "Значение твое"
 

BaiYun

Новичок
17
0
Советую:



У тебя скорее всего вообще не регистрируются такие команды, потому что бесконечный цикл запускается и не дает выполняться коду дальше ( если я не ошибаюсь то оно так работает )

Ключ это не название файла, а так сказать таблица, к которой твой lua файл обращается. Ну в роликах по ссылке выше - автор рассказывает про эти ключи.
1) По этим видосам я и учусь
2)Кмд реагается и все норм
3)
Screenshot_174.png
 

Strand

Участник
48
27
Есть проблема со скриптом. Пытаюсь прочитать файл, но игру крашит, либо она намертво зависает. Как решить проблему? Первый файл вести 3КБ, второй 79КБ
Lua:
require 'lib.moonloader'
local sampev = require 'samp.events'

local snailMaticDir = os.getenv('USERPROFILE') .. '\\Documents\\GTA San Andreas User Files\\SAMP\\SnailMatic\\'
local settingsSnailMatic, currentProfileName, profileJson

function main()

    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    
    sampRegisterChatCommand('updateprofile', function()
        updateProfileInfo()
    end)
    
    sampRegisterChatCommand('checkprofile', function()
        if profileJson == nil then sampAddChatMessage('You need to load profile first!',-1) return end
        for _, folder in pairs(profileJson) do
            for _, bind in pairs(folder.binds) do
                print(bind.name)
            end
        end
    end)
    
    function updateProfileInfo()

        sampAddChatMessage('Started checking settings!',-1)
        settingsSnailMatic = io.open(snailMaticDir..'snailmatic.json', 'r')
        currentProfileName = string.match(io.read(), '"profile":"([%w%s%pА-Яа-яЁё]+)"')
        io.close(settingsSnailMatic)
        
        sampAddChatMessage('Opening profile file!',-1)
        profileJson = io.open(snailMaticDir..'profiles\\'..currentProfileName..'.json', 'r')
        local buffer = json.decode(io.read())
        io.close(profileJson)
        
        profileJson = table.copy(buffer)
        
        sampAddChatMessage('Profile info updated!',-1)

    end
    
end
 

joumey

Активный
195
43
Хай. Можете помочь сделать скрипт, который будет отправлять команды после того, когда в чате найдет текст "объявление". У работает, если я сам пишу "объявление" в чат. А если просто в чате, ничего не происходит. Вот код
Скинь строку с обьявлением из чатлога

Привет ребят. В чем беда?
Код скинь