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

cheremuxa

Известный
430
200
ye
Добрый день! Попрошу вас объяснить, как работает данный код, а конкретнее обход игроков?
Lua:
function BeginToPoint(to_x, to_y, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9)
    slot10 = false

    repeat
        wait(0)

        slot11 = false
        x, y, z = getCharCoordinates(PLAYER_PED)
        slot15 = math.rad(getHeadingFromVector2d(to_x - x, to_y - y))
        dist = getDistanceBetweenCoords3d(to_x, to_y, slot2, x, y, slot2)

        for slot19 = -0.5, 2, 0.3 do
            for slot23 = -0.4, 0.4, 0.1 do
                sampCreate3dTextEx(1, "A", 4294967295.0, slot24, slot25, z + slot19, 5, true, -1, -1)

                boolUpClear = isLineOfSightClear(x, y, z + slot19, slot24, slot25, z + slot19, true, true, false, true, false)
                PedLine, _ = findAllRandomCharsInSphere(slot24, y + 2 * math.sin(slot15 + 1.55 + slot23), z, 1.5, false, true)

                if boolUpClear == false or PedLine then
                    break
                end
            end

            if PedLine then
                break
            end

            if boolUpClear and slot19 > -0.5 then
                slot11 = true

                break
            elseif boolUpClear and slot19 == -0.5 then
                break
            end
        end

        if boolUpClear == false or PedLine then
            for slot19 = 0.1, 2, 0.1 do
                slot20, slot21, slot22 = getCharCoordinates(PLAYER_PED)

                if isLineOfSightClear(slot20, slot21, slot22, slot23, slot21 + 2 * math.sin(slot15 + 1.2 - slot19), slot22 - 0.5, true, true, true, true, false) then
                    setCameraPositionUnfixed(-0.3, math.rad(getHeadingFromVector2d(slot20 + 2 * math.cos(slot15 + 1.2 - slot19) - slot20, slot21 + 2 * math.sin(slot15 + 1.2 - slot19) - slot21)) + 4.7)

                    break
                end

                if isLineOfSightClear(slot20, slot21, slot22, slot27, slot21 + 2 * math.sin(slot15 + 1.8 + slot19), slot22 - 0.5, true, true, true, true, false) then
                    setCameraPositionUnfixed(-0.3, math.rad(getHeadingFromVector2d(slot20 + 2 * math.cos(slot15 + 1.8 + slot19) - slot20, slot21 + 2 * math.sin(slot15 + 1.8 + slot19) - slot21)) + 4.7)

                    break
                end
            end
        else
            setCameraPositionUnfixed(-0.3, slot15 + 4.7)
        end

        setGameKeyState(1, -255)

        if slot4 and dist > 2 then
            if math.ceil(slot16) == math.floor(getHeadingFromVector2d(to_x - x, to_y - y)) and dist > 10 and getCharSpeed(PLAYER_PED) > 6.1 and getCharSpeed(PLAYER_PED) < 7 or slot11 and slot17 == slot18 then
                setGameKeyState(14, 255)
            elseif dist > 10 then
                setGameKeyState(16, 255)
            end
        end

        slot16 = os.time()

        if slot8 and dist < slot3 then
            repeat
                wait(400)

                boolSatiety = FuncNeedSatiety()
            until os.time() - slot16 > 10 or boolSatiety or enabled == false

            return
        end

        if slot6 and dist < slot3 then
            KeyDownMemory()

            repeat
                wait(500)
            until os.time() - slot16 > 15 or Success or enabled == false

            return
        end

        if slot7 and dist < slot3 then
            repeat
                wait(500)
            until os.time() - slot16 > 15 or Success == false or enabled == false

            return
        end

        if slot5 then
            slot10, _ = findAllRandomCharsInSphere(to_x, to_y, slot2, 3, false, true)
        end
    until slot5 and (slot10 or enabled == false or slot7 and (Success == false or slot6 and (Success or slot9 and dist < slot3)))
end

------------------------------------------------------------------------------------------------------------------------------------------------------------------------


Lua:
function cmd_linvite()
    lua_thread.create(function()
        sampSendChat("/do В левой руке кейс.")
            wait(2000)
        sampSendChat("/me взял кейс в две руки, затем нажал на кнопку")
            wait(2000)
        sampSendChat("/do Кейс раскрылся.")
            wait(2000)
        sampSendChat("/me достал из кейса пакет с формой и бейджиком")
            wait(2000)
        sampSendChat("/do Пакет в руке.")
            wait(2000)
        sampSendChat("/todo В этом пакете Ваша форма и бейджик* передавая пакет человеку напротив")
            wait(2000)
        sampSendChat("/invite [ID]")
            wait(2000)
        sampSendChat("/me закрыл кейс обеими руками, затем взял кейс в левую руку")
            wait(2000)
    end)
end
ну наверное проверяет если координаты близкие к игроку то он жмет D или A. логично же.
 

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Как прочитать ТОЛЬКО ПОСЛЕДНЮЮ строку текстового файла, через io.read ?
Текст в переменную, перебираешь её через "*n" и проверяешь, не равна ли строка == nil, если нет - заносишь в одну и ту же переменную каждую строку до тех пор, пока новая строка не будет == nil.
 

MR_Lua

Участник
41
0
нет
Вот не робит, че делать?

Lua:
if imgui.Checkbox(u8'Отыгровка оружия в руках', gun) then
    if gun.v then
    weapon = getCurrentCharWeapon(playerPed)
      if weapon == 24 then
        sampSendChat('/me спрятал оружие')
      end
    end
end
 

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Добрый день! Попрошу вас объяснить, как работает данный код, а конкретнее обход игроков?
Lua:
function BeginToPoint(to_x, to_y, slot2, slot3, slot4, slot5, slot6, slot7, slot8, slot9)
slot10 = false

repeat
wait(0)

slot11 = false
x, y, z = getCharCoordinates(PLAYER_PED)
slot15 = math.rad(getHeadingFromVector2d(to_x - x, to_y - y))
dist = getDistanceBetweenCoords3d(to_x, to_y, slot2, x, y, slot2)

for slot19 = -0.5, 2, 0.3 do
for slot23 = -0.4, 0.4, 0.1 do
sampCreate3dTextEx(1, "A", 4294967295.0, slot24, slot25, z + slot19, 5, true, -1, -1)

boolUpClear = isLineOfSightClear(x, y, z + slot19, slot24, slot25, z + slot19, true, true, false, true, false)
PedLine, _ = findAllRandomCharsInSphere(slot24, y + 2 * math.sin(slot15 + 1.55 + slot23), z, 1.5, false, true)

if boolUpClear == false or PedLine then
break
end
end

if PedLine then
break
end

if boolUpClear and slot19 > -0.5 then
slot11 = true

break
elseif boolUpClear and slot19 == -0.5 then
break
end
end

if boolUpClear == false or PedLine then
for slot19 = 0.1, 2, 0.1 do
slot20, slot21, slot22 = getCharCoordinates(PLAYER_PED)

if isLineOfSightClear(slot20, slot21, slot22, slot23, slot21 + 2 * math.sin(slot15 + 1.2 - slot19), slot22 - 0.5, true, true, true, true, false) then
setCameraPositionUnfixed(-0.3, math.rad(getHeadingFromVector2d(slot20 + 2 * math.cos(slot15 + 1.2 - slot19) - slot20, slot21 + 2 * math.sin(slot15 + 1.2 - slot19) - slot21)) + 4.7)

break
end

if isLineOfSightClear(slot20, slot21, slot22, slot27, slot21 + 2 * math.sin(slot15 + 1.8 + slot19), slot22 - 0.5, true, true, true, true, false) then
setCameraPositionUnfixed(-0.3, math.rad(getHeadingFromVector2d(slot20 + 2 * math.cos(slot15 + 1.8 + slot19) - slot20, slot21 + 2 * math.sin(slot15 + 1.8 + slot19) - slot21)) + 4.7)

break
end
end
else
setCameraPositionUnfixed(-0.3, slot15 + 4.7)
end

setGameKeyState(1, -255)

if slot4 and dist > 2 then
if math.ceil(slot16) == math.floor(getHeadingFromVector2d(to_x - x, to_y - y)) and dist > 10 and getCharSpeed(PLAYER_PED) > 6.1 and getCharSpeed(PLAYER_PED) < 7 or slot11 and slot17 == slot18 then
setGameKeyState(14, 255)
elseif dist > 10 then
setGameKeyState(16, 255)
end
end

slot16 = os.time()

if slot8 and dist < slot3 then
repeat
wait(400)

boolSatiety = FuncNeedSatiety()
until os.time() - slot16 > 10 or boolSatiety or enabled == false

return
end

if slot6 and dist < slot3 then
KeyDownMemory()

repeat
wait(500)
until os.time() - slot16 > 15 or Success or enabled == false

return
end

if slot7 and dist < slot3 then
repeat
wait(500)
until os.time() - slot16 > 15 or Success == false or enabled == false

return
end

if slot5 then
slot10, _ = findAllRandomCharsInSphere(to_x, to_y, slot2, 3, false, true)
end
until slot5 and (slot10 or enabled == false or slot7 and (Success == false or slot6 and (Success or slot9 and dist < slot3)))
end
Никак он не работает, у тебя псевдокод в функции.
Объяснить как работает обход игроков трудно из-за псевдокода, перепутаны переменные. Скрипт перебирает небольшие значения и добавляет их к твоим координатам, далее проверяет свободно ли пространство между твоими координатами и координатами, которым добавлены некоторые значения(скорее всего)
 
  • Нравится
Реакции: cheremuxa

Adventurer

Известный
151
69
нет
Вот не робит, че делать?

Lua:
if imgui.Checkbox(u8'Отыгровка оружия в руках', gun) then
    if gun.v then
    weapon = getCurrentCharWeapon(playerPed)
      if weapon == 24 then
        sampSendChat('/me спрятал оружие')
      end
    end
end
Чтобы у тебя этот код работал, нужно всегда держать активным окно, в котором находится этот чекбокс.
Перенеси следующий код в независимый постоянный поток.
if gun.v then weapon = getCurrentCharWeapon(playerPed) if weapon == 24 then sampSendChat('/me спрятал оружие') end end
 

Joni Scripts

Известный
535
374
Что делать если закидываешь lua скрипт в мун и после захода на сервер он не коннектится к серверу, че делать
 
  • Нравится
Реакции: ~Justie~

ZAKO

Известный
43
25
Здрасьте, всю жизнь разбираю строки, используя ограничители {}

На,к примеру на PHP: ([А-Яа-я+]{10,30}) вход в шаблон от 10 до 30 символов, в ЛУА почему-то не работает, чем они заменены:?
 

EmilkaL

Известный
85
5
Кто-нибудь пользовался attachCameraToVehicle , как оно работает?
И как можно приблизить камеру?Например как в снайперке, фотоаппарате?
 
Последнее редактирование:

astynk

Известный
Проверенный
742
530
Здрасьте, всю жизнь разбираю строки, используя ограничители {}

На,к примеру на PHP: ([А-Яа-я+]{10,30}) вход в шаблон от 10 до 30 символов, в ЛУА почему-то не работает, чем они заменены:?
Ничем. В луа не совсем регэкспы, там паттерны, со своими особенностями.
Придется юзать циклы или найти библиотеку lua regex, видел где-то.
 

Ettoress

Новичок
2
0
Как сделать ра отыгровку /mask и рп через lua как я сделал так
не работает:
function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('mask',command)
    while true do wait(0) end end
    function command()
    sampSendChat('/me одел маску на голову') end end
 

yarsuetolog

Участник
67
7
Как сделать ра отыгровку /mask и рп через lua как я сделал так
не работает:
function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('mask',command)
    while true do wait(0) end end
    function command()
    sampSendChat('/me одел маску на голову') end end
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("mask", command)
    else
    while true do
        wait(0)
        end
    end

function command()
    sampSendChat("/me одел маску на голову")
    sampSendChat("/mask")
end