Вопросы по 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
 
Последнее редактирование:

qdIbp

Автор темы
Проверенный
1,438
1,199
1. Как сделать что бы текущие координаты персонажа выводились на экран?
https://www.blast.hk/dokuwiki/lua:render
https://www.blast.hk/dokuwiki/lua:getcharcoordinates
2. Что бы курсор мыши был на указанной директории и нажимал ЛКМ.

Попробуй
x = msg:sub(i-1, i)
Там вроде индексы символов с 0 начинаются в строке.
неа
 
Последнее редактирование:

sep

Известный
714
79
или так
Lua:
local on = require "lib.samp.events"
function main()
    while true do wait(0)
 
    end
end
function on.onShowDialog(did, style, title, b1, b2, text)
    lua_thread.create(function()
        if title:find('Игровое меню')and did == 722 and text:find('Действия персонажа') then
            tt = text:gsub('Действия персонажа','{FF00FF}%1')
            sampShowDialog(17, title, tt, b1, b2, style)
            while sampIsDialogActive(17) do wait(100) end
            local res, button, list, inp = sampHasDialogRespond(17)
            if button == 1 then sampSendDialogResponse(did, 1, list, _) end
        end
    end)
    if title:find('Игровое меню') and did == 722 then
        return false
    end
end
Посмотреть вложение 125681

а можно перекрацывать не по тексту а по столбцам ?
например перекрасить 2 столбец там где написано скрыто (в реале такст там разный я его просто скрыл)

di-DWYWVH.png
 

yoozee

Новичок
12
0
Когда пишу /zbind крашит после добавления команд
imgui.RadioButton("Radio 1", checked_radio, 3)
imgui.RadioButton("Radio 2", checked_radio, 4)
imgui.RadioButton("Radio 3", checked_radio, 5)

Lua:
 script_name("imgui")
script_author("zabivnoy")
require('moonloader')
local imgui = require('imgui')
local encoding = require("encoding")
encoding.default = "CP1251"
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
function main()
    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded()) then
        return
    end
    while (not isSampAvailable()) do
        wait(200)
    end
    
    sampRegisterChatCommand('zbind', 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 cmd_check(arg)
    sampAddChatMessage(checked_radio.v, -1)
end

function imgui.OnDrawFrame()
    if (main_window_state.v) then
        imgui.Begin("Z-binder by zabivnoy", main_window_state)
        imgui.Text("z-binder")
        imgui.InputText('Введите текст!', text_buffer)
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text(u8("Ваша позиция: X:" .. math.floor(x) .. "  | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z)))
        imgui.Text(text_buffer.v)
        if imgui.Button("Press me") then
            sampAddChatMessage("q", -1)
        end
        imgui.RadioButton("Radio 1", checked_radio, 3)
        imgui.RadioButton("Radio 2", checked_radio, 4)
        imgui.RadioButton("Radio 3", checked_radio, 5)
        imgui.End()
    end
end
 

qdIbp

Автор темы
Проверенный
1,438
1,199
Когда пишу /zbind крашит после добавления команд
imgui.RadioButton("Radio 1", checked_radio, 3)
imgui.RadioButton("Radio 2", checked_radio, 4)
imgui.RadioButton("Radio 3", checked_radio, 5)

Lua:
 script_name("imgui")
script_author("zabivnoy")
require('moonloader')
local imgui = require('imgui')
local encoding = require("encoding")
encoding.default = "CP1251"
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
function main()
    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded()) then
        return
    end
    while (not isSampAvailable()) do
        wait(200)
    end
   
    sampRegisterChatCommand('zbind', 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 cmd_check(arg)
    sampAddChatMessage(checked_radio.v, -1)
end

function imgui.OnDrawFrame()
    if (main_window_state.v) then
        imgui.Begin("Z-binder by zabivnoy", main_window_state)
        imgui.Text("z-binder")
        imgui.InputText('Введите текст!', text_buffer)
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text(u8("Ваша позиция: X:" .. math.floor(x) .. "  | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z)))
        imgui.Text(text_buffer.v)
        if imgui.Button("Press me") then
            sampAddChatMessage("q", -1)
        end
        imgui.RadioButton("Radio 1", checked_radio, 3)
        imgui.RadioButton("Radio 2", checked_radio, 4)
        imgui.RadioButton("Radio 3", checked_radio, 5)
        imgui.End()
    end
end
Lua:
script_name("imgui")
script_author("zabivnoy")
require('moonloader')
local imgui = require('imgui')
local encoding = require("encoding")
encoding.default = "CP1251"
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local checked_radio = imgui.ImInt(3) --0
function main()
    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded()) then return end
    while (not isSampAvailable()) do wait(200) end
    
    sampRegisterChatCommand('zbind', function() main_window_state.v = not main_window_state.v end)
    sampRegisterChatCommand('cmd', cmd_check)--0
    while true do wait(0)
        imgui.Process = main_window_state.v
    end
end
function cmd_check(arg) sampAddChatMessage(checked_radio.v, -1) end

function imgui.OnDrawFrame()
    if main_window_state.v then
        imgui.Begin("Z-binder by zabivnoy", main_window_state)
            imgui.Text("z-binder")
            imgui.InputText('Введите текст!', text_buffer)
            x, y, z = getCharCoordinates(PLAYER_PED)
            imgui.Text(u8("Ваша позиция: X:" .. math.floor(x) .. "  | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z)))
            imgui.Text(text_buffer.v)
            if imgui.Button("Press me") then
                sampAddChatMessage("q", -1)
            end
            imgui.RadioButton("Radio 1", checked_radio, 3)
            imgui.RadioButton("Radio 2", checked_radio, 4)
            imgui.RadioButton("Radio 3", checked_radio, 5)
        imgui.End()
    end
end
 
У

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

Гость
Подскажите как сделать паттерн под такую строку
Код:
[12:44:04]     {ff0105}Nik  [Jeremy_Gold]    R-IP [94.233.249.124]    L-IP  [94.233.249.124]    IP  [94.233.249.124]
Lua:
require('moonloader')
local sampev = require('samp.events')

function sampev.onServerMessage(color, text)
    -- Nik  [Jeremy_Gold]    R-IP [94.233.249.124]    L-IP  [94.233.249.124]    IP  [94.233.249.124]
    if (text:find('Nik  %[(%w+_%w+)%]    R%pIP %[(%d+%p%d+%p%d+%p%d+)%]    L%pIP  %[(%d+%p%d+%p%d+%p%d+)%]    IP  %[(%d+%p%d+%p%d+%p%d+)%]')) then
        local nickname, rip, lip, ip = text:match('Nik  %[(%w+_%w+)%]    R%pIP %[(%d+%p%d+%p%d+%p%d+)%]    L%pIP  %[(%d+%p%d+%p%d+%p%d+)%]    IP  %[(%d+%p%d+%p%d+%p%d+)%]')
        sampAddChatMessage(string.format('Nickname: %s | R-IP: %s | L-IP: %s | IP: %s', nickname, rip, lip, ip), -1)
    end
end
 
  • Нравится
Реакции: lovandog

yoozee

Новичок
12
0
хелп почему не работает
Lua:
 script_name("imgui")
script_author("zabivnoy")
require('moonloader')
local imgui = require('imgui')
local encoding = require("encoding")
encoding.default = "CP1251"
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local checked_test = imgui.ImBool(false)
local checked_test_2 = imgui.ImBool(false)
local checked_radio = imgui.ImInt(1)
local combo_select = imgui.ImInt(0)
local arr_str = {"Салам", "test2", "test3"}
function main()
    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded()) then
        return
    end
    while (not isSampAvailable()) do
        wait(200)
    end
    
    sampRegisterChatCommand('zbind', function()
        main_window_state.v = not main_window_state.v
    end)
    sampRegisterChatCommand('check', cmd_check)
end
        
function cmd_check(arg)
    sampAddChatMessage(checked_radio.v, -1)
    
    if checked_test.v then
        sampAddChatMessage("Галочка стоит!", -1)
    end
    sampAddChatMessage(u8:decode(arr_str[combo_select.v +1]), -1)
end

function imgui.OnDrawFrame()
    if main_window_state.v then
            imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)
        --imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin("Z-binder by zabivnoy", main_window_state)
        imgui.Text("z-binder")
        imgui.InputText('Введите текст!', text_buffer)
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text("Ваша позиция: X:" .. math.floor(x) .. "  | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z))
        imgui.Text(text_buffer.v)
        imgui.SetCursorPosY(120)
        imgui.Separator()
        imgui.SetCursorPosY(140)
        imgui.Text("Это наша выборка")
        imgui.SameLine()
        imgui.SetCursorPosX(200)
        imgui.Checkbox("Checkbox 1", checked_test)
        imgui.SameLine()
        imgui.Checkbox("Checkbox 2", checked_test_2)
        imgui.SetCursorPosY(180)
        imgui.Separator()
        imgui.RadioButton("Radio 1", checked_radio, 3)
        imgui.SameLine()
        imgui.RadioButton("Radio 2", checked_radio, 4)
        imgui.SameLine()
        imgui.RadioButton("Radio 3", checked_radio, 5)
        imgui.PushItemWidth(120)

        imgui.SetCursorPosY(250)
        imgui.SetCursorPosX(200)
        imgui.Combo("Combo 1", combo_select, arr_str, #arr_str)
        imgui.End()
        end
    end
 

qdIbp

Автор темы
Проверенный
1,438
1,199
а можно перекрацывать не по тексту а по столбцам ?
например перекрасить 2 столбец там где написано скрыто (в реале такст там разный я его просто скрыл)

di-DWYWVH.png
Lua:
local on = require "lib.samp.events"
function main()
    while true do wait(0)
    end
end

function on.onShowDialog(did, style, title, b1, b2, text)
    if title:find('Статистика игрока')and did == 0 then
            xz = text:gsub('\n','-')
            tt = xz:gsub('{FFFFFF}(%A+)','{FF00FF}%1')
            da = tt:gsub('-','\n')
            sampShowDialog(17, title, da, b1, b2, style)
        return false
    end
end
Вместо FF00FF свой цвет поставь, либо сделай таблицу и через рег.команды крути цвета /color 2
Крч сам придумывай

хелп почему не работает
Lua:
 script_name("imgui")
script_author("zabivnoy")
require('moonloader')
local imgui = require('imgui')
local encoding = require("encoding")
encoding.default = "CP1251"
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local checked_test = imgui.ImBool(false)
local checked_test_2 = imgui.ImBool(false)
local checked_radio = imgui.ImInt(1)
local combo_select = imgui.ImInt(0)
local arr_str = {"Салам", "test2", "test3"}
function main()
    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded()) then
        return
    end
    while (not isSampAvailable()) do
        wait(200)
    end
  
    sampRegisterChatCommand('zbind', function()
        main_window_state.v = not main_window_state.v
    end)
    sampRegisterChatCommand('check', cmd_check)
end
      
function cmd_check(arg)
    sampAddChatMessage(checked_radio.v, -1)
  
    if checked_test.v then
        sampAddChatMessage("Галочка стоит!", -1)
    end
    sampAddChatMessage(u8:decode(arr_str[combo_select.v +1]), -1)
end

function imgui.OnDrawFrame()
    if main_window_state.v then
            imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)
        --imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin("Z-binder by zabivnoy", main_window_state)
        imgui.Text("z-binder")
        imgui.InputText('Введите текст!', text_buffer)
        x, y, z = getCharCoordinates(PLAYER_PED)
        imgui.Text("Ваша позиция: X:" .. math.floor(x) .. "  | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z))
        imgui.Text(text_buffer.v)
        imgui.SetCursorPosY(120)
        imgui.Separator()
        imgui.SetCursorPosY(140)
        imgui.Text("Это наша выборка")
        imgui.SameLine()
        imgui.SetCursorPosX(200)
        imgui.Checkbox("Checkbox 1", checked_test)
        imgui.SameLine()
        imgui.Checkbox("Checkbox 2", checked_test_2)
        imgui.SetCursorPosY(180)
        imgui.Separator()
        imgui.RadioButton("Radio 1", checked_radio, 3)
        imgui.SameLine()
        imgui.RadioButton("Radio 2", checked_radio, 4)
        imgui.SameLine()
        imgui.RadioButton("Radio 3", checked_radio, 5)
        imgui.PushItemWidth(120)

        imgui.SetCursorPosY(250)
        imgui.SetCursorPosX(200)
        imgui.Combo("Combo 1", combo_select, arr_str, #arr_str)
        imgui.End()
        end
    end
Lua:
script_name("imgui")
script_author("zabivnoy")
require('moonloader')
local imgui = require('imgui')
local encoding = require("encoding")
encoding.default = "CP1251"
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)
local checked_test = imgui.ImBool(false)
local checked_test_2 = imgui.ImBool(false)
local checked_radio = imgui.ImInt(1)
local combo_select = imgui.ImInt(0)
local arr_str = {"Салам", "test2", "test3"}
function main()
    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded())then return end
    while (not isSampAvailable()) do wait(200) end
    sampRegisterChatCommand('zbind', function() main_window_state.v = not main_window_state.v print(main_window_state.v)end)
    sampRegisterChatCommand('check', cmd_check)
    while true do wait(0) --беск цикл отсутст.
        imgui.Process = main_window_state.v --процесс отсутст
    end
end
       
function cmd_check(arg)
    sampAddChatMessage(checked_radio.v, -1)
    if checked_test.v then sampAddChatMessage("Галочка стоит!", -1) end
    sampAddChatMessage(u8:decode(arr_str[combo_select.v +1]), -1)
end

function imgui.OnDrawFrame()
    sizeX, sizeY = getScreenResolution()--получение разр.экрана отсутст
    if main_window_state.v then print('+++')
        imgui.SetNextWindowSize(imgui.ImVec2(500, 300), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2(sizeX / 2, sizeY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin("Z-binder by zabivnoy", main_window_state)
            imgui.Text("z-binder")
            imgui.InputText(u8'Введите текст!', text_buffer) --отсутст u8
            x, y, z = getCharCoordinates(PLAYER_PED)
            imgui.Text("Ваша позиция: X:" .. math.floor(x) .. "  | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z))
            imgui.Text(text_buffer.v)
            imgui.SetCursorPosY(120)
            imgui.Separator()
            imgui.SetCursorPosY(140)
            imgui.Text("Это наша выборка")
            imgui.SameLine()
            imgui.SetCursorPosX(200)
            imgui.Checkbox("Checkbox 1", checked_test)
            imgui.SameLine()
            imgui.Checkbox("Checkbox 2", checked_test_2)
            imgui.SetCursorPosY(180)
            imgui.Separator()
            imgui.RadioButton("Radio 1", checked_radio, 3)
            imgui.SameLine()
            imgui.RadioButton("Radio 2", checked_radio, 4)
            imgui.SameLine()
            imgui.RadioButton("Radio 3", checked_radio, 5)
            imgui.PushItemWidth(120)

            imgui.SetCursorPosY(250)
            imgui.SetCursorPosX(200)
            imgui.Combo("Combo 1", combo_select, arr_str, #arr_str)
        imgui.End()
    end
end
Я закомментировал что отсутствовало
 
Последнее редактирование:
  • Нравится
Реакции: sep

ch1ps

Участник
101
3
Код:
require "lib.moonloader"
local events = require 'lib.samp.events'
if not doesDirectoryExist('moonloader/config') then createDirectory('moonloader/config') end

local settings = {
    e = 1,
    s = 2
}

function saveSettings(str)
    local file = io.open('moonloader/config/bot.ini', 'w')
    file:write(settings)
    file:close()
end

function loadSettings()
    local file = io.open('moonloader/config/bot.ini', 'r')
    settings = convertStringToSettings(file:read())
    file:close()
end

function main()
    while true do
        if isKeyJustPressed(VK_L) then
            e=2
            sampAddChatMessage("okay")
        elseif isKeyJustPressed(VK_K) then
            sampAddChatMessage(e)
        end
    end
end
Вообщем есть одна проблемка, я щас пытаюсь разобраться, как создавать конфиги, но из-за этого кода игра при запуске зависает, что не так?
 

Smeruxa

smeruxa.ru
Проверенный
1,434
800
Код:
require "lib.moonloader"
local events = require 'lib.samp.events'
if not doesDirectoryExist('moonloader/config') then createDirectory('moonloader/config') end

local settings = {
    e = 1,
    s = 2
}

function saveSettings(str)
    local file = io.open('moonloader/config/bot.ini', 'w')
    file:write(settings)
    file:close()
end

function loadSettings()
    local file = io.open('moonloader/config/bot.ini', 'r')
    settings = convertStringToSettings(file:read())
    file:close()
end

function main()
    while true do
        if isKeyJustPressed(VK_L) then
            e=2
            sampAddChatMessage("okay")
        elseif isKeyJustPressed(VK_K) then
            sampAddChatMessage(e)
        end
    end
end
Вообщем есть одна проблемка, я щас пытаюсь разобраться, как создавать конфиги, но из-за этого кода игра при запуске зависает, что не так?
если L не нажимаешь - "е" не сущ-ет, + сохраняй нормально как все люди
 

Pashyka

Участник
220
17
Привет всем, подскажите как возвращать текст в чат, который хукнул.
То есть например ввели /plveh 32 0 то в чате эта строка будет

Lua:
function hook.onServerMessage(color, text)
    if hookrep then
        if text:find("%[.-%] от .+%[%d+%]:{......} .+ Уже {......}%d+{......} жалоб!!!") then
            sampSendChat("/ot")
            hookrep = false
        end
    end
    if autoform then
        if text:find("%[.-%] {......}%w+_%w+%[%d+%]{......}: /plveh .+") then
            sampAddChatMessage("{DC143C}[A] {FFFFFF}Форма выдана", -1)
            sampSendChat(string.format("/plveh %s", text:match("/plveh (.+)")))
        end
    end
end
 
Последнее редактирование:
У

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

Гость
Нормально это как?

Код:
require "lib.moonloader"
local events = require 'lib.samp.events'
if not doesDirectoryExist('moonloader/config') then createDirectory('moonloader/config') end

local settings = {
    e = 1,
    s = 2
}

function saveSettings(str)
    local file = io.open('moonloader/config/bot.ini', 'w')
    file:write(settings)
    file:close()
end

function loadSettings()
    local file = io.open('moonloader/config/bot.ini', 'r')
    settings = convertStringToSettings(file:read())
    file:close()
end

function main()
    while true do
        if isKeyJustPressed(VK_L) then
            e=2
            sampAddChatMessage("okay")
        elseif isKeyJustPressed(VK_K) then
            sampAddChatMessage(e)
        end
    end
end
Вообщем есть одна проблемка, я щас пытаюсь разобраться, как создавать конфиги, но из-за этого кода игра при запуске зависает, что не так?
Если я правильно понял

Lua:
require('moonloader')
local inicfg = require('inicfg')

local config = 'config.ini'
local path = getWorkingDirectory() .. config

-- https://wiki.blast.hk/ru/moonloader/lua/inicfg

-- Загружаем файл с конфигом
local mainIni = inicfg.load({ -- https://wiki.blast.hk/ru/moonloader/lua/inicfg#inicfgload
    settings = {
        a = 0
    }
}, config)

--[[

-----------------------------
Как указать новое значение?

mainIni.settings.a = 123
-----------------------------

]]--

function main()

    if (not isSampLoaded() or not isSampfuncsLoaded() or not isCleoLoaded()) then
        return
    end
    while (not isSampAvailable()) do
        wait(200)
    end

    -- Проверяем на существование config.ini
    if (not doesFileExist(path)) then -- https://wiki.blast.hk/ru/moonloader/lua/doesFileExist
        inicfg.save(mainIni, config) -- https://wiki.blast.hk/ru/moonloader/lua/inicfg#inicfgsave
    end

    -- Регистрируем команду с аргументом, который будет сохраняться в конфиг
    sampRegisterChatCommand('a', function (arg1)
        if (arg1:find('.+')) then
            sampAddChatMessage(string.format('Новое значение: %s', arg1:match('.+')), -1)
            -- Указываем новое значение а
            mainIni.settings.a = arg1
            -- Сохраняем конфиг
            inicfg.save(mainIni, config)
        end
        --[[
        Тоже самое, что выше
        if (arg1 ~= nil) then
            sampAddChatMessage(string.format('Новое значение: %s', arg), -1)
            mainIni.settings.a = arg1
            inicfg.save(mainIni, config)
        end
        ]]--
    end)

    while (true) do wait(0)

        -- Если нажмем Z, то в чате появится то значение(a), которое указано в config.ini
        if (isKeyJustPressed(VK_Z)) then
            sampAddChatMessage(string.format('A: %s', mainIni.settings.a), -1)
        end

    end
end
 

S7XA

Активный
106
76
Где можно глянуть гайд по подключению VK Notifications в свой скрипт?