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

CanslerW

Участник
54
1
Как сделать когда при закрытие меню на кнопку, то все сохраняется до закрытия и после, тоесть открыл 2 менюшки и закрыл их через кнопку(всё закрылось), открываю на кнопку(и они остались в том же месте и открыти)
 

Tak

Известный
176
70
Как сделать когда при закрытие меню на кнопку, то все сохраняется до закрытия и после, тоесть открыл 2 менюшки и закрыл их через кнопку(всё закрылось), открываю на кнопку(и они остались в том же месте и открыти)
Что за меню? Imgui?
Получать и записывать координаты окна: imgui.GetWindowPos().x, а при открытии устанавливать окно на эти координаты:
imgui.SetNextWindowPos(imgui.ImVec2(50, 50), imgui.Cond.FirstUseEver)
 
  • Нравится
Реакции: Qusaber

CanslerW

Участник
54
1
Что за меню? Imgui?
Получать и записывать координаты окна: imgui.GetWindowPos().x, а при открытии устанавливать окно на эти координаты:
imgui.SetNextWindowPos(imgui.ImVec2(50, 50), imgui.Cond.FirstUseEver)
Нет, типа я у меня было 2 открытых окна, и когда я закрыл все и открыл снова они остались в том же месте. Как такое сделать?
 

NIET

Участник
80
24
Как получить цвета пикселя с определенными координатами?
 

черный кот

Известный
167
182
+, рил песда, часа 2 голову себе ебал и нихуя, в инете нашел только примеры использования 3двектора на сишарапе:
C#:
BASS_3DVECTOR vec = new BASS_3DVECTOR(vecpos.X, vecpos.Y, vecpos.Z);
Bass.BASS_ChannelSet3DPosition(this.Handle, vec, null, null);
Bass.BASS_Apply3D();
Почаны кто в ffi шарит?
 

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Капец это муть, я тоже сижу мучаюсь, пытаясь передать в BASS_3DVECTOR координаты. Но он мне пишет что не может преобразовать массив в BASS_3DVECTOR:
Lua:
-- cannot convert 'table' to 'const struct BASS_3DVECTOR если пытаться запускать пример ниже

local vec = {0.0, 0.0, 0.0}
bass.BASS_ChannelSet3DPosition(radio, vec, nil, nil);

-- Если заглянуть в lib, то там:

-- И как это записать на lua непонятно

// 3D vector (for 3D positions/velocities/orientations)
typedef struct BASS_3DVECTOR {
    float x;    // +=right, -=left
    float y;    // +=up, -=down
    float z;    // +=front, -=behind
} BASS_3DVECTOR;
попробуй так:
vec = {x = 0.0, y = 0.0, z = 0.0} bass.BASS_ChannelSet3DPosition(radio, vec, nil, nil)
 

copypaste_scripter

Известный
1,218
223
как сделать чтобы при нажатии CapsLock отправился нажатие клавиш Alt+Shift или если можно без этого сменить язык ввода
 

copypaste_scripter

Известный
1,218
223
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

почему не работает выделенные функции?
 

Anton Nixon

Активный
474
48
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

почему не работает выделенные функции?
А зачем столько раз вызывать samp.events?
 

Tak

Известный
176
70
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

почему не работает выделенные функции?
Емае, сделай одну функцию с onServerMessage, и все туда запихай. Поэтому и не работает

По типу:

Lua:
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
    if text:find("Номера телефонов государственных служб:") then
        sampAddChatMessage("111 - баланс | 060 - время | 911 - полиция | 912 - скорая | 913 - такси | 914 - механик | 8828 - банк", main_color)
    end
end
 
  • Нравится
Реакции: Qusaber

|DEVIL|

Известный
359
273
пацаны, как сделать чтобы с mn высчитывалась определенная информация
Посмотреть вложение 55231

а именно: Ник, уровень, номер телефона, организация, подразделение, ранг
Можно ловить диалог через хук onShowDialog (Айди диалога тоже можно узнать по нему) , а потом через string:match находить нужную инфу (тык)
 

copypaste_scripter

Известный
1,218
223