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

BlackGoblin

Известный
519
215
я хочу чтобы все было отдельно


а нельзя чтобы было много?
Ты создаешь зачем то 150 переменных и каждую обращаешь к samp.events, для чего вообще?) Делаешь одну и в ней обрабатываешь весь чат, это же хук
 
  • Ха-ха
Реакции: Izvinisb

copypaste_scripter

Известный
1,218
224
Ты создаешь зачем то 150 переменных и каждую обращаешь к samp.events, для чего вообще?) Делаешь одну и в ней обрабатываешь весь чат, это же хук
я сделал как вы сказали и чат перестал обновляться, даже любой текст не отправлял, то есть отправлял но не отобразился
 

Tak

Известный
176
70
я сделал как вы сказали и чат перестал обновляться, даже любой текст не отправлял, то есть отправлял но не отобразился
Скинь код.
Если тебе не удобно смотреть на кучу кода, распредели его по функциям (передавая в функцию text), а вызывай всех их в onServerMessage (Где ловишь сообщения)
 
  • Нравится
Реакции: Qusaber

Fott

Простреленный
3,433
2,278
Lua:
script_name('CPS_Script')
script_author('Copy_Paste_from_Internet')
script_description('Something')

require "lib.moonloader"
require "lib.samp.events"

local sampev = require "lib.samp.events"
local CPS_Trash_Ad_Redact = require "lib.samp.events"
local CPS_SIM_Register = require "lib.samp.events"
local CPS_Trash_Ad_Donate = require "lib.samp.events"
local CPS_Trash_Inkasator = require "lib.samp.events"
local CPS_Trash_News_and_Interview = require "lib.samp.events"
local CPS_Trash_Smug = require "lib.samp.events"
local CPS_Trash_Car_Help = require "lib.samp.events"
local CPS_Trash_Car_Rent_Help = require "lib.samp.events"
local CPS_Trash_Phone_Call_Num_Help = require "lib.samp.events"
local CPS_Gos_Number_Help = require "lib.samp.events"
local CPS_Trash_Car_Health = require "lib.samp.events"

local keys = require "vkeys"
local main_color = 0x8B0000

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
  
    sampRegisterChatCommand("cg", cmd_cg)
    sampRegisterChatCommand("sellstuff", cmd_sellstuff)

    while true do
        wait(0)

        if isKeyJustPressed(VK_F3) then            --    F3        /s text
            sampSendChat("/s text")
        end
      
        if isKeyJustPressed(VK_F13) then        --    F13        /key
            sampSendChat("/key")
        end
      
        if isKeyJustPressed(VK_F14) then        --    F14        /lock
            sampSendChat("/lock")
        end
      
        if isKeyJustPressed(VK_F18) then        --    F18        /repcar
            sampSendChat("/repcar")
        end
      
        if isKeyJustPressed(VK_F19) then        --    F19        /fillcar
            sampSendChat("/fillcar")
        end
      
        if isKeyJustPressed(VK_F20) then        --    F20        /house
            sampSendChat("/house")
        end
      
        if isKeyJustPressed(VK_F16) then        --    F16        /cars
            sampSendChat("/cars")
        end
      
        if isKeyJustPressed(VK_NUMPAD0) then    --    Num0    /jlock
            sampSendChat("/jlock")
        end
      
        if isKeyJustPressed(VK_NUMPAD8) then    --    Num8    /beer
            sampSendChat("/beer")
        end
      
        if isKeyJustPressed(VK_F9) then            --    F9        /time
            sampSendChat("/time")
        end
      
        if isKeyJustPressed(VK_F2) then            --    F2        /unrentcar
            sampSendChat("/unrentcar")
        end
      
        if isKeyDown(VK_MENU) and isKeyJustPressed(VK_F11) then
            sampProcessChatInput("/fpslimit 90")
        end
      
        if isKeyDown(VK_MENU) and isKeyJustPressed(VK_F12) then
            sampProcessChatInput("/fpslimit 20")
        end
      
        if isKeyDown(VK_CONTROL) and isKeyJustPressed(VK_P) then
            sampSendChat("/phone")
            wait (300)
            setVirtualKeyDown(VK_RETURN)
        end
    end
end

--            CUSTOM COMMANDS

function cmd_cg(arg)                                                --    /creategun > /cg
    sampSendChat("/creategun")
end

function cmd_sellstuff(arg)
    lua_thread.create(function()
        sampSendChat("/s Продам: ")
        wait (3500)
        sampSendChat("/s text")
        wait (3500)
        sampSendChat("/s text")
        wait (3500)
        sampSendChat("/s text")
        wait (3500)
        sampSendChat("/s text")
    end)
end

--            CHAT HELP

function CPS_SIM_Register.onServerMessage(color, text)                --    sim karta
    if text:find("Вы успешно зарегистрировали новую SIM карту. Ваш новый номер телефона:") then
        lua_thread.create(function()
            wait (30000)
            sampAddChatMessage("SIM карта", main_color)
        end)
    end
end

function CPS_Gos_Number_Help.onServerMessage(color, text)            --    nomer help
    if text:find("Номера телефонов государственных служб:") then
        sampAddChatMessage("111 - баланс | 060 - время | 911 - полиция | 912 - скорая | 913 - такси | 914 - механик | 8828 - банк", main_color)
    end
end

--            CHAT TRASH

function CPS_Trash_Ad_Redact.onServerMessage(color, text)            --    ad otredaktiroval
    if text:find("Отредактировал сотрудник СМИ") then
        return false
    end
end

function CPS_Trash_Ad_Donate.onServerMessage(color, text)            --    reklama donat
    if text:find("В нашем магазине ты можешь приобрести нужное количество игровых денег и потратить") or text:find("их на желаемый тобой бизнес, дом, аксессуар или на покупку каких-нибудь безделушек") or text:find("- Игроки со статусом VIP имеют большие возможности, подробнее /help [Преимущества VIP]") or text:find("В магазине так-же можно приобрести редкие автомобили, аксессуары, воздушные шары") or text:find("предметы, которые выделят тебя из толпы! Наш сайт: arizona-rp.com") then
        return false
    end
end

function CPS_Trash_Inkasator.onServerMessage(color, text)            --    inkasator
    if text:find("начал работу новый инкассатор!") or text:find("Убив его, вы сможете получить деньги!") then
        return false
    end
end

function CPS_Trash_News_and_Interview.onServerMessage(color, text)    --    news, interviu
    if text:find(" Репортёр") or text:find(" Гость ") or text:find(" [ News LS ]") or text:find(" [ News SF ]") or text:find(" [ News LV ]") then
        return false
    end
end

function CPS_Trash_Smug.onServerMessage(color, text)                --    smug
    if text:find("[Внимание] Быстрее отправляйтесь на его разгрузку, чтобы его не забрали другие!") then
        return false
    end
end

function CPS_Trash_Car_Help.onServerMessage(color, text)            --    car
    if text:find("Чтобы завести двигатель введите") or text:find("Для управления поворотниками используйте клавиши") or text:find("В транспорте присутствует радио") then
        return false
    end
end

function CPS_Trash_Car_Rent_Help.onServerMessage(color, text)        --    arenda
    if text:find("Чтобы закрыть автомобиль используйте ") or text:find("Чтобы отказаться от аренды") then
        return false
    end
end

function CPS_Trash_Phone_Call_Num_Help.onServerMessage(color, text)    --    telefon help
    if text:find("111 - Проверить баланс телефона") or text:find("060 - Служба точного времени") or text:find("911 - Полицейский участок") or text:find("912 - Скорая помощь") or text:find("913 - Такси") or text:find("914 - Механик") or text:find("8828 - Справочная центрального банка") then
        return false
    end
end

function CPS_Trash_Car_Health.onServerMessage(color, text)            --    sostoianie mashini
    if text:find("Состояние вашего авто крайне плохое! Машина может сломаться!") or text:find("Необходимо заехать на станцию тех. обслуживания!") then
        return false
    end
end

почему не работает выделенные функции?
Держи
Lua:
script_name('CPS_Script')
script_author('Copy_Paste_from_Internet')
script_description('Something')

require "lib.moonloader"

local samp = require 'samp.events'


local keys = require "vkeys"
local main_color = 0x8B0000

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand("cg", cmd_cg)
    sampRegisterChatCommand("sellstuff", cmd_sellstuff)

    while true do
        wait(0)

        if isKeyJustPressed(VK_F3) then            --    F3        /s text
            sampSendChat("/s text")
        end
   
        if isKeyJustPressed(VK_F13) then        --    F13        /key
            sampSendChat("/key")
        end
   
        if isKeyJustPressed(VK_F14) then        --    F14        /lock
            sampSendChat("/lock")
        end
   
        if isKeyJustPressed(VK_F18) then        --    F18        /repcar
            sampSendChat("/repcar")
        end
   
        if isKeyJustPressed(VK_F19) then        --    F19        /fillcar
            sampSendChat("/fillcar")
        end
   
        if isKeyJustPressed(VK_F20) then        --    F20        /house
            sampSendChat("/house")
        end
   
        if isKeyJustPressed(VK_F16) then        --    F16        /cars
            sampSendChat("/cars")
        end
   
        if isKeyJustPressed(VK_NUMPAD0) then    --    Num0    /jlock
            sampSendChat("/jlock")
        end
   
        if isKeyJustPressed(VK_NUMPAD8) then    --    Num8    /beer
            sampSendChat("/beer")
        end
   
        if isKeyJustPressed(VK_F9) then            --    F9        /time
            sampSendChat("/time")
        end
   
        if isKeyJustPressed(VK_F2) then            --    F2        /unrentcar
            sampSendChat("/unrentcar")
        end
   
        if isKeyDown(VK_MENU) and isKeyJustPressed(VK_F11) then
            sampProcessChatInput("/fpslimit 90")
        end
   
        if isKeyDown(VK_MENU) and isKeyJustPressed(VK_F12) then
            sampProcessChatInput("/fpslimit 20")
        end
   
        if isKeyDown(VK_CONTROL) and isKeyJustPressed(VK_P) then
            sampSendChat("/phone")
            wait (300)
            setVirtualKeyDown(VK_RETURN)
        end
    end
end

--            CUSTOM COMMANDS

function cmd_cg(arg)                                                --    /creategun > /cg
    sampSendChat("/creategun")
end

function cmd_sellstuff(arg)
    lua_thread.create(function()
        sampSendChat("/s Продам: ")
        wait (3500)
        sampSendChat("/s text")
        wait (3500)
        sampSendChat("/s text")
        wait (3500)
        sampSendChat("/s text")
        wait (3500)
        sampSendChat("/s text")
    end)
end

--            CHAT HELP

function samp.onServerMessage(color, text)                --    sim karta
    if text:find("Вы успешно зарегистрировали новую SIM карту. Ваш новый номер телефона:") then
        lua_thread.create(function()
            wait (30000)
            sampAddChatMessage("SIM карта", main_color)
        end)
    end
--------------------------------------------------------------------------------------------------
    if text:find("Номера телефонов государственных служб:") then
        sampAddChatMessage("111 - баланс | 060 - время | 911 - полиция | 912 - скорая | 913 - такси | 914 - механик | 8828 - банк", main_color)
    end
--------------------------------------------------------------------------------------------------
    if text:find("Отредактировал сотрудник СМИ") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find("В нашем магазине ты можешь приобрести нужное количество игровых денег и потратить") or text:find("их на желаемый тобой бизнес, дом, аксессуар или на покупку каких-нибудь безделушек") or text:find("- Игроки со статусом VIP имеют большие возможности, подробнее /help [Преимущества VIP]") or text:find("В магазине так-же можно приобрести редкие автомобили, аксессуары, воздушные шары") or text:find("предметы, которые выделят тебя из толпы! Наш сайт: arizona-rp.com") then
        return false
    end
     --------------------------------------------------------------------------------------------------
    if text:find("начал работу новый инкассатор!") or text:find("Убив его, вы сможете получить деньги!") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find(" Репортёр") or text:find(" Гость ") or text:find(" [ News LS ]") or text:find(" [ News SF ]") or text:find(" [ News LV ]") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find("[Внимание] Быстрее отправляйтесь на его разгрузку, чтобы его не забрали другие!") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find("Чтобы завести двигатель введите") or text:find("Для управления поворотниками используйте клавиши") or text:find("В транспорте присутствует радио") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find("Чтобы закрыть автомобиль используйте ") or text:find("Чтобы отказаться от аренды") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find("111 - Проверить баланс телефона") or text:find("060 - Служба точного времени") or text:find("911 - Полицейский участок") or text:find("912 - Скорая помощь") or text:find("913 - Такси") or text:find("914 - Механик") or text:find("8828 - Справочная центрального банка") then
        return false
    end
--------------------------------------------------------------------------------------------------
    if text:find("Состояние вашего авто крайне плохое! Машина может сломаться!") or text:find("Необходимо заехать на станцию тех. обслуживания!") then
        return false
    end
end
 
  • Нравится
Реакции: copypaste_scripter

БеzликиЙ

Автор темы
Проверенный
802
452
Есть вот такой вот скриптик

Lua:
function main()
while not isSampAvailable() do wait(200) end
x, y = getScreenResolution()
font = renderCreateFont("a_AvanteBS", 16, 0) -- 12
namefont = renderCreateFont("a_AvanteBS", 8, 0)
    while true do
        wait(0)
    resid, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    name = sampGetPlayerNickname(id)
    color = sampGetPlayerColor(id)
    renderDrawLine(0, 0, x+15, 0, 24, color)
    renderFontDrawText(namefont, name, 0, 0, 0xFFFFFFFF)
    renderDrawLine(0, 12, x+15, 12, 2, 0xFFFFFFFF)
    renderDrawLine(x-98, y-13, x+15, y-13, 26, 0xFF000000)
    renderDrawLine(x-130, y+30, x-98, y-13, 26, 0xFF000000)
    renderFontDrawText(font, "{FFFFFF}GRAV{FF6600}I{FFFFFF}TOS" , x-110 , y-25 , 0xFFFFFFFF)
    renderDrawLine(x-130, y, x-110, y-26, 2, 0xFFFFFFFF)
    renderDrawLine(x-110, y-26, x+15, y-26, 2, 0xFFFFFFFF)
    end
end
Вот результаты его работы: строка вверху и правый нижний угол.
mg 03-05-2020 14-18-01 [1].png

В общем. Нужно сделать так, чтобы надпись в углу динамически менялась:
500 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
200 мс - GRAVITOS
И так по кругу. Строчка с надписью в коде выделена.
 

#M1SKA

Новичок
10
10

Как сделать что бы скрипт сам нажимал клавиши которые показываются на мониторе?
 

Izvinisb

Известный
Проверенный
964
598
ну чет тип такого, 🤷‍♂️
Lua:
local k = require'vkeys'
function main()
    repeat wait(0) until isSampAvailable()
    while true do
        wait(0)
        if isKeyJustPressed(k.VK_CAPITAL) then -- caps
            wait(100)
            setVirtualKeyDown(k.VK_LMENU, true) -- аlt
            setVirtualKeyDown(k.VK_LSHIFT, true) -- shift
            wait(100)
            setVirtualKeyDown(k.VK_LMENU, false)
            setVirtualKeyDown(k.VK_LSHIFT, false)
        end
    end
end
 
  • Нравится
Реакции: copypaste_scripter

СЛожно

Известный
222
35
Почему не работает, ид диалога 222 закрыть кнопкой ентер, но не получается
Lua:
function sampev.onSendDialogResponse(dialogId, button, listboxId, input)
if dialogId == 222 then
  sampCloseCurrentDialogWithButton(1)
  end
end
? Не бейте по шапке)
 

Fott

Простреленный
3,433
2,278
Как получить ID игрока за которым я слежу ? ( В реконе )
Вроде так
Lua:
function samp.onSendCommand(cmd)
    local reId = string.match(cmd, "^%/re (%d+)")
    if reId then
        lastCmdRe = tonumber(reId)
    end
end

function samp.onTogglePlayerSpectating(state)
    spec = state
end

function samp.onSpectatePlayer(playerid, camtype)
    plid = playerid
end

function samp.onSpectateVehicle(carid, camtype)
    if plid ~= lastCmdRe and lastCmdRe >= 0 then
        plid = lastCmdRe
    end
end
 

Izvinisb

Известный
Проверенный
964
598
Почему не работает, ид диалога 222 закрыть кнопкой ентер, но не получается
Lua:
function sampev.onSendDialogResponse(dialogId, button, listboxId, input)
if dialogId == 222 then
  sampCloseCurrentDialogWithButton(1)
  end
end
? Не бейте по шапке)
вот это юзай {'onShowDialog', {dialogId = 'int16'}, {style = 'int8'}, {title = 'string8'}, {button1 = 'string8'}, {button2 = 'string8'}, {text = 'encodedString4096'}}
 

Anton Nixon

Активный
474
48
Как скриптом загрузить либу, чтобы обходило краш скрипта?
upd: moon v0.26
upd_2: получается загрузить пока что все библиотеки, кроме imgui