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

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Как оформить обычное диалоговое окно, чтобы текст не обрывался вопросом? Что пропустил?
Lua:
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8


if imgui.Text(u8"Глава 1. Нападение.\n1.1 За нападение на гражданское лицо и/или на сотрудника правоохранительных органов без применения способствующих для причинения вреда здоровью предметов и/или материалов, подозреваемому присваивается 3-я степень розыска.\n1.2 За умышленный вред причиненный автотранспортом гражданину или на сотрудника правоохранительных органов, подозреваемому присваивается 4-я степень розыска, а также полное изъятие лицензий на вождение.\nГлава 2. Вооруженное нападение и/или убийство.\n2.1 За вооруженное нападение на гражданина или на сотрудника правоохранительных органов и/или их убийство, подозреваемому присваивается 6-я степень розыска + разрешена нейтрализация.\nГлава 3. Транспортные средства.\n3.1 За попытку угона государственного или частного транспортного средства, подозреваемому присваивается 2-я степень розыска.\n3.2 За угон транспортного средства, подозреваемому присваивается 3-я степень розыска.\n3.3 За проникновение в транспортное средство без согласия его владельца, подозреваемому присваивается 2-ая степень розыска.\n3.4 За порчу автомобиля гражданского лица, подозреваемому присваивается 2-ая степень розыска.\nГлава 4. Использование государственного снаряжения.\n4.1 За ношение формы гос.служащего, её кражу и/или использование в личных целях, задержанному присваивается 3-ая степень розыска.\n4.2 За продажу или покупку формы гос. служащего и/или иных отличительных знаков гос.служащих, задержанному присваивается 4-ая степень розыска.\nГлава 5. Взятка.\n5.1 За дачу или попытку дачи взятки должностному лицу, подозреваемому присваивается 3-я степень розыска.\n5.2 За получение взятки должностным лицом, ему присваивается 6-я степень розыска так же попадание в ЧСМВД.\n(Обязательная видеофиксация)") then
end
Нафига делать проверку с текстом? Пиши просто imgui.Text(u8"Текст") и все
 

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Смотрите, вот появляется диалог, серверный, 1. получаю ИД, 2. Выбираю лист 3 и жму букву 1, покажите кодом пожалуйста, я функции нужные не могу найти
Lua:
local sampev = require 'lib.samp.events'

function sampev.onShowDialog(id, style, title, b1, b2, text)
    sampAddChatMessage(id, -1) -- Получаешь ид
end


-- Беск. цикл
local result, button, list, input = sampHasDialogRespond(тут id диалога)
    if result then
    -- Тут че хочешь делаешь
    end
 

Double Tap Inside

Известный
Проверенный
1,899
1,241
Смотрите, вот появляется диалог, серверный, 1. получаю ИД, 2. Выбираю лист 3 и жму букву 1, покажите кодом пожалуйста, я функции нужные не могу найти

Lua:
Смотрите, вот появляется диалог, серверный,
1. получаю ИД,
2. Выбираю лист 3
и жму букву 1, покажите кодом пожалуйста, я функции нужные не могу найти

sampev.onShowDialog(dialogId, style, title, button1, button2, text)
    if title == "Название диалога" -- я по названию всегда нахожу.
        sampSendDialogResponse(dialogId, 1, 2, -1) -- жму на третий пункт в списке
        --return false -- шобы скрыть диалог.
    elseif title == "Название диалога в которм надо отослать (1) " then
        sampSendDialogResponse(dialogId, 1, -1, "1") -- отсылаю единичку
        --return false -- шобы скрыть диалог.
    end
end
Как закрыть диалог?
никак только скрыть. а вообще можешь поебацца с https://blast.hk/wiki/lua:sampclosecurrentdialogwithbutton
 

Double Tap Inside

Известный
Проверенный
1,899
1,241
Что не так?
Lua:
time_one = 0
        time_two = 0
       
        if active_report and isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
            time_one = time_one + os.clock(tonumber(1))
            sampSendChat("/"..cmd.." "..other.." || "..admin_nick)
            active_report = false
        elseif not active_report and isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampAddChatMessage("{FF0000}[RH] {FF8C00}В данный момент недоступно!", 0xFFFF0000)
        elseif active_report and time_one - os.clock() == 1 then
            printStyledString('Until the end of the form 1', 1000, 4)
        elseif active_report and time_one - os.clock() == 2 then
            printStyledString('Until the end of the form 2', 1000, 4)
        elseif active_report and time_one - os.clock() == 3 then
            printStyledString('Until the end of the form 3', 1000, 4)
        elseif active_report and time_one - os.clock() == 4 then
            printStyledString('Until the end of the form 4', 1000, 4)
        elseif active_report and time_one - os.clock() == 5 then
            printStyledString('Until the end of the form 5', 1000, 4)
        elseif active_report and time_one - os.clock() == 6 then
            printStyledString('Until the end of the form 6', 1000, 4)
        elseif active_report and time_one - os.clock() == 7 then
            printStyledString('Until the end of the form 7', 1000, 4)
        elseif active_report and time_one - os.clock() == 8 then
            printStyledString('Until the end of the form 8', 1000, 4)
        elseif active_report and time_one - os.clock() == 9 then
            printStyledString('Until the end of the form 9', 1000, 4)
        elseif active_report and time_one - os.clock() == 10 then
            printStyledString('Form skipped automatically', 1000, 4)
            active_report = false
        end
       
        if active_report1 and isKeyJustPressed(VK_L) and not sampIsChatInputActive() and not sampIsDialogActive() then
            time_two = time_two + os.clock(tonumber(1))
            sampSendChat('/'..cmd1..' '..other1..' || '..admin_nick1)
            active_report1 = false
        elseif not active_report1 and isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampAddChatMessage("{FF0000}[RH] {FF8C00}В данный момент недоступно!", 0xFFFF0000)
        elseif active_report1 and time_two - os.clock() == 1 then
            printStyledString('Until the end of the form 1', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 2 then
            printStyledString('Until the end of the form 2', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 3 then
            printStyledString('Until the end of the form 3', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 4 then
            printStyledString('Until the end of the form 4', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 5 then
            printStyledString('Until the end of the form 5', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 6 then
            printStyledString('Until the end of the form 6', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 7 then
            printStyledString('Until the end of the form 7', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 8 then
            printStyledString('Until the end of the form 8', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 9 then
            printStyledString('Until the end of the form 9', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 10 then
            printStyledString('Form skipped automatically', 1000, 4)
            active_report1 = false
        end
       
        if active_report and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('You missed the form', 1000, 4)
            active_report = false
        elseif active_report1 and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('You missed the form', 1000, 4)
            active_report1 = false
        elseif not active_report and not active_report1 and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('You can’t skip the form temporarily', 1000, 4)
        end
       
        if not active_report and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('Do not miss the form', 1000, 4)
        elseif not active_report1 and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('Do not miss the form', 1000, 4)
        end
куда смотреть?
 

Double Tap Inside

Известный
Проверенный
1,899
1,241
Что не так?
Lua:
time_one = 0
        time_two = 0
    
        if active_report and isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
            time_one = time_one + os.clock(tonumber(1))
            sampSendChat("/"..cmd.." "..other.." || "..admin_nick)
            active_report = false
        elseif not active_report and isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampAddChatMessage("{FF0000}[RH] {FF8C00}В данный момент недоступно!", 0xFFFF0000)
        elseif active_report and time_one - os.clock() == 1 then
            printStyledString('Until the end of the form 1', 1000, 4)
        elseif active_report and time_one - os.clock() == 2 then
            printStyledString('Until the end of the form 2', 1000, 4)
        elseif active_report and time_one - os.clock() == 3 then
            printStyledString('Until the end of the form 3', 1000, 4)
        elseif active_report and time_one - os.clock() == 4 then
            printStyledString('Until the end of the form 4', 1000, 4)
        elseif active_report and time_one - os.clock() == 5 then
            printStyledString('Until the end of the form 5', 1000, 4)
        elseif active_report and time_one - os.clock() == 6 then
            printStyledString('Until the end of the form 6', 1000, 4)
        elseif active_report and time_one - os.clock() == 7 then
            printStyledString('Until the end of the form 7', 1000, 4)
        elseif active_report and time_one - os.clock() == 8 then
            printStyledString('Until the end of the form 8', 1000, 4)
        elseif active_report and time_one - os.clock() == 9 then
            printStyledString('Until the end of the form 9', 1000, 4)
        elseif active_report and time_one - os.clock() == 10 then
            printStyledString('Form skipped automatically', 1000, 4)
            active_report = false
        end
    
        if active_report1 and isKeyJustPressed(VK_L) and not sampIsChatInputActive() and not sampIsDialogActive() then
            time_two = time_two + os.clock(tonumber(1))
            sampSendChat('/'..cmd1..' '..other1..' || '..admin_nick1)
            active_report1 = false
        elseif not active_report1 and isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
            sampAddChatMessage("{FF0000}[RH] {FF8C00}В данный момент недоступно!", 0xFFFF0000)
        elseif active_report1 and time_two - os.clock() == 1 then
            printStyledString('Until the end of the form 1', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 2 then
            printStyledString('Until the end of the form 2', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 3 then
            printStyledString('Until the end of the form 3', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 4 then
            printStyledString('Until the end of the form 4', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 5 then
            printStyledString('Until the end of the form 5', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 6 then
            printStyledString('Until the end of the form 6', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 7 then
            printStyledString('Until the end of the form 7', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 8 then
            printStyledString('Until the end of the form 8', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 9 then
            printStyledString('Until the end of the form 9', 1000, 4)
        elseif active_report1 and time_two - os.clock() == 10 then
            printStyledString('Form skipped automatically', 1000, 4)
            active_report1 = false
        end
    
        if active_report and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('You missed the form', 1000, 4)
            active_report = false
        elseif active_report1 and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('You missed the form', 1000, 4)
            active_report1 = false
        elseif not active_report and not active_report1 and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('You can’t skip the form temporarily', 1000, 4)
        end
    
        if not active_report and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('Do not miss the form', 1000, 4)
        elseif not active_report1 and isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() then
            printStyledString('Do not miss the form', 1000, 4)
        end
За исправление этого я 500р возьму, не меньше.
os.clock(tonumber(1)) -- это как так
time_two - os.clock() == 6 -- никогда блять в жизне не будет равно тебе целому числу. мб надо поставить что то типо < или >
Я ж блять тебе в дс кинул пример. как ты. ой. всё. я ливаю нахуй =)
 

Lucifer Melton

Активный
164
57
Lua:
function checker()
    while true do
        wait(0)
  
  
        local result, button, listitem, input = sampHasDialogRespond(228)
  
        if result and not sampIsDialogActive() then
            if button == 0 then
                return
            end
      
            if button == 1 then
                if listitem == 0 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 12:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 1 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 13:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 2 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 14:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 3 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 15:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 4 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 16:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 5 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 17:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 6 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 18:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 7 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 19:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 8 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 20:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 9 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 21:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 10 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 22:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 11 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 22:30 РАБОТАЕМ ', -1)
                  
                elseif listitem == 12 then
                    sampSendChat('/a Админы работаем отвечаем на репорты иначе получите выговор!!!', -1)
                end
              
                return
            end
        end
    end
end

если другой диалог перебьет этот диалог, то тогда поток не сдохнет и будет ебашить. а это очень очень плохо. Развлекайся =)
может так укоротить? :D
Lua:
if listitem >= 1 and listitem <= 12 then
    sampSendChat("/a Внимание!!! Раздача пизды будет проходить в "..sampGetListboxItemText(list).." РАБОТАЕМ", -1)
end
Текст всё ровно обрывается
Lua:
imgui.TextWrapped(u8"Глава 1. Нападение.\n1.1 За нападение на гражданское лицо и/или на сотрудника правоохранительных органов без применения способствующих для причинения вреда здоровью предметов и/или материалов, подозреваемому присваивается 3-я степень розыска.\n1.2 За умышленный вред причиненный автотранспортом гражданину или на сотрудника правоохранительных органов, подозреваемому присваивается 4-я степень розыска, а также полное изъятие лицензий на вождение.\nГлава 2. Вооруженное нападение и/или убийство.\n2.1 За вооруженное нападение на гражданина или на сотрудника правоохранительных органов и/или их убийство, подозреваемому присваивается 6-я степень розыска + разрешена нейтрализация.\nГлава 3. Транспортные средства.\n3.1 За попытку угона государственного или частного транспортного средства, подозреваемому присваивается 2-я степень розыска.\n3.2 За угон транспортного средства, подозреваемому присваивается 3-я степень розыска.\n3.3 За проникновение в транспортное средство без согласия его владельца, подозреваемому присваивается 2-ая степень розыска.\n3.4 За порчу автомобиля гражданского лица, подозреваемому присваивается 2-ая степень розыска.\nГлава 4. Использование государственного снаряжения.\n4.1 За ношение формы гос.служащего, её кражу и/или использование в личных целях, задержанному присваивается 3-ая степень розыска.\n4.2 За продажу или покупку формы гос. служащего и/или иных отличительных знаков гос.служащих, задержанному присваивается 4-ая степень розыска.\nГлава 5. Взятка.\n5.1 За дачу или попытку дачи взятки должностному лицу, подозреваемому присваивается 3-я степень розыска.\n5.2 За получение взятки должностным лицом, ему присваивается 6-я степень розыска так же попадание в ЧСМВД.\n(Обязательная видеофиксация)")
 

cheremuxa

Известный
430
200
Как проверить пустой InputText или нет ?
Lua:
if #переменная.v == 0 then

end
Есть две функции которые ввели меня в ступор...
Как получить одно без другого? Мне нужно хендл машины
чужие машины (И СВОЯ):

Lua:
for k, v in ipairs(getAllVehicles()) do
_, vehHandle = sampGetVehicleIdByCarHandle(v)
end

просто своя:
Lua:
myCarHandle = storeCarCharIsInNoSave(PLAYER_PED)
 

mark0005675

Участник
30
3
А как сделать что бы не ебашило? если пробьёт
Lua:
function checker()
    while true do
        wait(0)
  
  
        local result, button, listitem, input = sampHasDialogRespond(228)
  
        if result and not sampIsDialogActive() then
            if button == 0 then
                return
            end
      
            if button == 1 then
                if listitem == 0 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 12:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 1 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 13:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 2 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 14:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 3 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 15:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 4 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 16:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 5 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 17:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 6 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 18:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 7 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 19:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 8 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 20:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 9 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 21:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 10 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 22:00 РАБОТАЕМ ', -1)
                  
                elseif listitem == 11 then
                    sampSendChat('/a Внимание!!! Раздача пизды будет проходить в 22:30 РАБОТАЕМ ', -1)
                  
                elseif listitem == 12 then
                    sampSendChat('/a Админы работаем отвечаем на репорты иначе получите выговор!!!', -1)
                end
              
                return
            end
        end
    end
end

если другой диалог перебьет этот диалог, то тогда поток не сдохнет и будет ебашить. а это очень очень плохо. Развлекайся =)
а как сделать что бы не ебашило?