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

Corrygan228

Участник
132
9
в чём ошибка заключается? не пойму
[ML] (error) Government Helper.lua: ...resources\projects\crmp\moonloader\Government Helper.lua:514: attempt to call a nil value
stack traceback:
...resources\projects\crmp\moonloader\Government Helper.lua:514: in function 'OnDrawFrame'
...AUNCHER\resources\projects\crmp\moonloader\lib\imgui.lua:1378: in function <...AUNCHER\resources\projects\crmp\moonloader\lib\imgui.lua:1367>
[ML] (error) Government Helper.lua: Script died due to an error. (1C00B14C)
Lua:
                                for i = 1, #binds_arr do
                                    if binds_arr[i] then
                                        imgui.CenterText(u8'Настройки бинда: ' .. binds_arr[i].name)
                                        imgui.Combo(u8'Активация', binds_arr[i].activation_select, binds_arr[i].activation_arr, #binds_arr[i].activation_arr)
                                        if binds_arr[i].activation_select == 0 then
                                            imgui.SameLine()
                                            imgui.Text(u8'Кнопка')
                                        else
                                            imgui.SameLine()
                                            imgui.InputText(u8'Команда для активации', binds_arr[i].activation_command)
                                        end
                                        imgui.Separator()
                                        for i in binds_arr.binds do -- тут ошибка
                                            imgui.InputText(u8'Строка №' .. #binds_arr.binds + 1, binds_arr.binds[i])
                                        end
                                        imgui.SameLine()
                                        if imgui.Button('+') then
                                            table.insert(binds_arr.binds, imgui.ImBuffer(256))
                                        end
                                        imgui.SameLine()
                                        if imgui.Button('-') then
                                            table.remove(binds_arr.binds)
                                        end
                                    end
                                end
 

MrRazrab

Известный
520
257
в чём ошибка заключается? не пойму

Lua:
                                for i = 1, #binds_arr do
                                    if binds_arr[i] then
                                        imgui.CenterText(u8'Настройки бинда: ' .. binds_arr[i].name)
                                        imgui.Combo(u8'Активация', binds_arr[i].activation_select, binds_arr[i].activation_arr, #binds_arr[i].activation_arr)
                                        if binds_arr[i].activation_select == 0 then
                                            imgui.SameLine()
                                            imgui.Text(u8'Кнопка')
                                        else
                                            imgui.SameLine()
                                            imgui.InputText(u8'Команда для активации', binds_arr[i].activation_command)
                                        end
                                        imgui.Separator()
                                        for i in binds_arr.binds do -- тут ошибка
                                            imgui.InputText(u8'Строка №' .. #binds_arr.binds + 1, binds_arr.binds[i])
                                        end
                                        imgui.SameLine()
                                        if imgui.Button('+') then
                                            table.insert(binds_arr.binds, imgui.ImBuffer(256))
                                        end
                                        imgui.SameLine()
                                        if imgui.Button('-') then
                                            table.remove(binds_arr.binds)
                                        end
                                    end
                                end
так в какой строке ошибка то
 

tsunamiqq

Участник
433
17
Lua:
local text = 'Вторник    {96E54C}$1201700{FFFFFF}'
if text:find('Вторник    {.-}%$(%d+){.-}') then
    local sum = text:match('Вторник    {.-}%$(%d+){.-}')
    print(sum)
end
Посмотреть вложение 208421
под диалоги переделай только,вроде считает


если что пробелы можно заменить вроде да как %s+
Lua:
    if id == 0 then
        for line in text:gmatch("[^\r\n]+") do
            if line:find("Вторник    %{......%}{.-}%$(%d+){.-}%{......%}") then
                bankbizWeek = line:match("Вторник    %{......%}{.-}%$(%d+){.-}%{......%}")
                statbizWeek = statbizWeek + bankbizWeek
            end
        end
    end
Видимо не так сделал
--Если что сорян, очень туплю по теме взаимодействий с диалогами :)
 
Последнее редактирование:

Dmitriy Makarov

25.05.2021
Проверенный
2,515
1,141
Lua:
    if id == 0 then
        for line in text:gmatch("[^\r\n]+") do
            if line:find("Вторник    %{......%}{.-}%$(%d+){.-}%{......%}") then
                bankbizWeek = line:match("Вторник    %{......%}{.-}%$(%d+){.-}%{......%}")
                statbizWeek = statbizWeek + bankbizWeek
            end
        end
    end
Видимо не так сделал
--Если что сорян, очень туплю по теме взаимодействий с диалогами :)
Убери везде либо это {.-}, либо это %{......%} на выбор. Это одно и то же, у тебя они дублируются и поэтому не срабатывает.
Один из вариантов используй:
1. "Вторник %{......%}%$(%d+)%{......%}"
2. "Вторник {.-}%$(%d+){.-}"
 
  • Нравится
Реакции: chromiusj

tsunamiqq

Участник
433
17
Убери везде либо это {.-}, либо это %{......%} на выбор. Это одно и то же, у тебя они дублируются и поэтому не срабатывает.
Один из вариантов используй:
1. "Вторник %{......%}%$(%d+)%{......%}"
2. "Вторник {.-}%$(%d+){.-}"
Ни тот ни тот вариант не работает
 

Dmitriy Makarov

25.05.2021
Проверенный
2,515
1,141
Ни тот ни тот вариант не работает
Не работает часть с суммированием или не находит текст?
Screenshot_2023-07-19-00-23-41-708_org.mozilla.firefox.png
 

tsunamiqq

Участник
433
17
Не работает часть с суммированием или не находит текст?
Посмотреть вложение 208432
У меня так сделано
Lua:
local statbizWeek = 0

    if id == 0 then
        for line in text:gmatch("[^\r\n]+") do
            if line:find("Вторник    {.-}%$(%d+){.-}") then
                bankbizWeek = line:match("Вторник    {.-}%$(%d+){.-}")
                statbizWeek = statbizWeek + bankbizWeek
            end
        end
    end

Не находит текст
 

chromiusj

модерирую шмодерирую
Модератор
5,986
4,299
У меня так сделано
Lua:
local statbizWeek = 0

    if id == 0 then
        for line in text:gmatch("[^\r\n]+") do
            if line:find("Вторник    {.-}%$(%d+){.-}") then
                bankbizWeek = line:match("Вторник    {.-}%$(%d+){.-}")
                statbizWeek = statbizWeek + bankbizWeek
            end
        end
    end

Не находит текст
ты уверен что у тебя айди диалога 0?проще по титулу сравнивать
 

Julimba

Участник
108
10
Lua:
lua_thread.create(function()
    for k, v in ipairs(logs) do
        table.remove(logs, 1)
        wait(1300)
        sampSendChat('/vr ' ..v.hid)
    end
end)
Как сделать задержку между каждым сообщением? hid содержит множество чисел, вообщем то реализация как таковой очереди
А то оно ждем одну 1.3 секунды и начинаем почти каждые пол секунды прописывать все числа из массива
 

Corrygan228

Участник
132
9
не могу понять, где там скобка нужна...
[07:25:09.912860] (error) Government Helper.lua: ...resources\projects\crmp\moonloader\Government Helper.lua:519: ')' expected near '='
[07:25:09.912860] (error) Government Helper.lua: Script died due to an error. (1BA5FE84)
Lua:
local binds_arr = {
    {name=u8'Приветствие', activation_arr={u8'На кнопку:', u8'По команде:'}, activation_select=imgui.ImInt(0), activation_command=imgui.ImBuffer(256), binds={stroke=imgui.ImBuffer(256)}}
}

local bind_name = imgui.ImBuffer(256)

--фрейм
imgui.Columns(2, '##main_part_4_select_binder')
imgui.SetColumnWidth(-1, 200)

imgui.BeginChild('##binds_first_column', imgui.ImVec2(186, 250), false)

for i, k in ipairs(binds_arr) do
    imgui.Button(binds_arr[i].name, imgui.ImVec2(74, 24))
end

imgui.SetCursorPosX(48)
if imgui.Button(u8'Добавить', imgui.ImVec2(74, 24)) then
    imgui.OpenPopup('##add_new_bind')
end

if imgui.BeginPopupModal('##add_new_bind', true, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize) then
    imgui.SetWindowSize(imgui.ImVec2(300, 200))
    imgui.InputText('Название бинда', bind_name)
    imgui.SetCursorPosX(53.3)
    if imgui.Button(u8'Добавить', imgui.ImVec2(70, 25)) then
        table.insert(binds_arr, {name = u8(bind_name.v), activation_arr={u8'На кнопку:', u8'По команде'}, activation_select=imgui.ImInt(0), binds={stroke=imgui.ImBuffer(256)}})
        imgui.CloseCurrentPopup()
    end
    imgui.SameLine()
    imgui.SetCursorPosX(166.7)
    if imgui.Button(u8'Отмена', imgui.ImVec2(70, 25)) then
        imgui.CloseCurrentPopup()
    end
    imgui.EndPopup()
end


imgui.EndChild()

imgui.NextColumn()

imgui.BeginChild('##binds_second_column', imgui.ImVec2(348, 250), false)

for i = 1, #binds_arr do
    if binds_arr[i] then
        imgui.CenterText(u8'Настройки бинда: ' .. binds_arr[i].name)
        imgui.Combo(u8'Активация', binds_arr[i].activation_select, binds_arr[i].activation_arr, #binds_arr[i].activation_arr)
        if binds_arr[i].activation_select == 0 then
            imgui.SameLine()
            imgui.Text(u8'Кнопка')
        else
            imgui.SameLine()
            imgui.InputText(u8'Команда для активации', binds_arr[i].activation_command)
        end
        imgui.Separator()
        for k, v in ipairs(binds_arr[i].binds) do
            imgui.InputText(u8'Строка №' .. #binds_arr[i].binds + 1, binds_arr[i].binds[v])
        end
        imgui.SameLine()
        if imgui.Button('+') then
            table.insert(binds_arr[i].binds, stroke = imgui.ImBuffer(256)) --ЗДЕСЬ ОШИБКА
        end
        imgui.SameLine()
        if imgui.Button('-') then
            table.remove(binds_arr[i].binds)
        end
    end
end

imgui.EndChild()

imgui.Columns(1)
 

XRLM

Против ветра рождённый
Модератор
1,636
1,295
не могу понять, где там скобка нужна...

Lua:
local binds_arr = {
    {name=u8'Приветствие', activation_arr={u8'На кнопку:', u8'По команде:'}, activation_select=imgui.ImInt(0), activation_command=imgui.ImBuffer(256), binds={stroke=imgui.ImBuffer(256)}}
}

local bind_name = imgui.ImBuffer(256)

--фрейм
imgui.Columns(2, '##main_part_4_select_binder')
imgui.SetColumnWidth(-1, 200)

imgui.BeginChild('##binds_first_column', imgui.ImVec2(186, 250), false)

for i, k in ipairs(binds_arr) do
    imgui.Button(binds_arr[i].name, imgui.ImVec2(74, 24))
end

imgui.SetCursorPosX(48)
if imgui.Button(u8'Добавить', imgui.ImVec2(74, 24)) then
    imgui.OpenPopup('##add_new_bind')
end

if imgui.BeginPopupModal('##add_new_bind', true, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize) then
    imgui.SetWindowSize(imgui.ImVec2(300, 200))
    imgui.InputText('Название бинда', bind_name)
    imgui.SetCursorPosX(53.3)
    if imgui.Button(u8'Добавить', imgui.ImVec2(70, 25)) then
        table.insert(binds_arr, {name = u8(bind_name.v), activation_arr={u8'На кнопку:', u8'По команде'}, activation_select=imgui.ImInt(0), binds={stroke=imgui.ImBuffer(256)}})
        imgui.CloseCurrentPopup()
    end
    imgui.SameLine()
    imgui.SetCursorPosX(166.7)
    if imgui.Button(u8'Отмена', imgui.ImVec2(70, 25)) then
        imgui.CloseCurrentPopup()
    end
    imgui.EndPopup()
end


imgui.EndChild()

imgui.NextColumn()

imgui.BeginChild('##binds_second_column', imgui.ImVec2(348, 250), false)

for i = 1, #binds_arr do
    if binds_arr[i] then
        imgui.CenterText(u8'Настройки бинда: ' .. binds_arr[i].name)
        imgui.Combo(u8'Активация', binds_arr[i].activation_select, binds_arr[i].activation_arr, #binds_arr[i].activation_arr)
        if binds_arr[i].activation_select == 0 then
            imgui.SameLine()
            imgui.Text(u8'Кнопка')
        else
            imgui.SameLine()
            imgui.InputText(u8'Команда для активации', binds_arr[i].activation_command)
        end
        imgui.Separator()
        for k, v in ipairs(binds_arr[i].binds) do
            imgui.InputText(u8'Строка №' .. #binds_arr[i].binds + 1, binds_arr[i].binds[v])
        end
        imgui.SameLine()
        if imgui.Button('+') then
            table.insert(binds_arr[i].binds, stroke = imgui.ImBuffer(256)) --ЗДЕСЬ ОШИБКА
        end
        imgui.SameLine()
        if imgui.Button('-') then
            table.remove(binds_arr[i].binds)
        end
    end
end

imgui.EndChild()

imgui.Columns(1)
Lua:
table.insert(binds_arr[i].binds, {stroke = imgui.ImBuffer(256)})
 
  • Клоун
Реакции: Air_Official

владикс

Потрачен
532
181
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Почему при нажатии на imgui.Button - не работает прожатие АЛЬТ, а при хуке текста из чата всё работает.


аа?:
-- работает
if text:find('test') then
    lua_thread.create(function()
        setVirtualKeyDown(18, true)
        wait(300)
        setVirtualKeyDown(18, false)
    end)
end

a&:
-- не работает
if imgui.Button("tes", imgui.ImVec2(20, 20))  then
    lua_thread.create(function()
        setVirtualKeyDown(18, true)
        wait(300)
        setVirtualKeyDown(18, false)
    end)
end