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

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Хочу вот так сделать: если я напишу в диалоговое окно что нибудь, тогда при нажатии на кнопку выведет в чат то что я написал.
local result, button, list, input = sampHasDialogRespond(1)
if result then -- или button , я с этой херней мало работал , через пакеты проще
print(input)
end
 

Cameron_Bawerman

Участник
99
1
как сделать акцент и что бы он сохранялся
а когда пишешь в что то тас он сам вставлял
 

samespoon

Известный
163
20
Возможно ли как-то обновить информацию о сервере (как при нажатии на Refresh в клиенте), дабы не было ошибки "The server didn't respond. Retrying.."?
 

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
как сделать акцент и что бы он сохранялся
а когда пишешь в что то тас он сам вставлял
sampSetChatInputText("[Итальянский акцент] ")
или через пакеты, просто при отправлении модифицировать
[TBODY] [/TBODY]
 

kektop1

Новичок
62
12
Нормальный код чи как обычно дрянь? Что можно улучшить?
Lua:
require 'lib.moonloader'
local Matrix3X3 = require 'matrix3x3'

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

function fast()
    if not isSampfuncsConsoleActive() and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() then
        local time = os.clock() * 1000
        if isKeyJustPressed(VK_F3) then -- suicide
            if not isCharInAnyCar(playerPed) then
                setCharHealth(playerPed, 0.0)
            else
                setCarHealth(storeCarCharIsInNoSave(playerPed), 0.0)
            end
        end

        if isKeyJustPressed(VK_OEM_5) then -- unfreeze
            if isCharInAnyCar(playerPed) then
                freezeCarPosition(storeCarCharIsInNoSave(playerPed), false)
            else
                setPlayerControl(playerHandle, true)
                freezeCharPosition(playerPed, false)
                clearCharTasksImmediately(playerPed)
            end
            restoreCameraJumpcut()
        end

        if isKeyJustPressed(VK_B) then -- jump
            if isCharInAnyCar(playerPed) then
                local cVecX, cVecY, cVecZ = getCarSpeedVector(storeCarCharIsInNoSave(playerPed))
                if cVecZ < 7.0 then applyForceToCar(storeCarCharIsInNoSave(playerPed), 0.0, 0.0, 0.1, 0.0, 0.0, 0.0) end
            else
                local pVecX, pVecY, pVecZ = getCharVelocity(playerPed)
                if pVecZ < 7.0 then setCharVelocity(playerPed, 0.0, 0.0, 10.0) end
            end
        end

        if isKeyJustPressed(VK_BACK) and isCharInAnyCar(playerPed) then -- turn back
            local cVecX, cVecY, cVecZ = getCarSpeedVector(storeCarCharIsInNoSave(playerPed))
            applyForceToCar(storeCarCharIsInNoSave(playerPed), -cVecX / 25, -cVecY / 25, -cVecZ / 25, 0.0, 0.0, 0.0)
            local x, y, z, w = getVehicleQuaternion(storeCarCharIsInNoSave(playerPed))
            local matrix = {convertQuaternionToMatrix(w, x, y, z)}
            matrix[1] = -matrix[1]
            matrix[2] = -matrix[2]
            matrix[4] = -matrix[4]
            matrix[5] = -matrix[5]
            matrix[7] = -matrix[7]
            matrix[8] = -matrix[8]
            local w, x, y, z = convertMatrixToQuaternion(matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8], matrix[9])
            setVehicleQuaternion(storeCarCharIsInNoSave(playerPed), x, y, z, w)
        end

        if isKeyJustPressed(VK_N) and isCharInAnyCar(playerPed) then -- fast exit
            local posX, posY, posZ = getCarCoordinates(storeCarCharIsInNoSave(playerPed))
            warpCharFromCarToCoord(playerPed, posX, posY, posZ)
        end

        if isCharPlayingAnim(playerPed, 'KO_SKID_BACK') or isCharPlayingAnim(playerPed, 'FALL_COLLAPSE') then -- no fall
            clearCharTasksImmediately(playerPed)
        end
       
        if chatstring == "Server closed the connection." or chatstring == "You are banned from this server." then
            local chatstring = sampGetChatString(99)
            sampDisconnectWithReason(false)
            wait(17000)
            sampSetGamestate(1)
        elseif isKeyDown(0x10) and isKeyDown(0x30) and not sampIsChatInputActive() then
            sampSetGamestate(1)
        end
       
        if testCheat("mm") then
            sampSendChat("/mm")
        end
    end
end
 

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Нормальный код чи как обычно дрянь? Что можно улучшить?
Lua:
require 'lib.moonloader'
local Matrix3X3 = require 'matrix3x3'

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

function fast()
    if not isSampfuncsConsoleActive() and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() then
        local time = os.clock() * 1000
        if isKeyJustPressed(VK_F3) then -- suicide
            if not isCharInAnyCar(playerPed) then
                setCharHealth(playerPed, 0.0)
            else
                setCarHealth(storeCarCharIsInNoSave(playerPed), 0.0)
            end
        end

        if isKeyJustPressed(VK_OEM_5) then -- unfreeze
            if isCharInAnyCar(playerPed) then
                freezeCarPosition(storeCarCharIsInNoSave(playerPed), false)
            else
                setPlayerControl(playerHandle, true)
                freezeCharPosition(playerPed, false)
                clearCharTasksImmediately(playerPed)
            end
            restoreCameraJumpcut()
        end

        if isKeyJustPressed(VK_B) then -- jump
            if isCharInAnyCar(playerPed) then
                local cVecX, cVecY, cVecZ = getCarSpeedVector(storeCarCharIsInNoSave(playerPed))
                if cVecZ < 7.0 then applyForceToCar(storeCarCharIsInNoSave(playerPed), 0.0, 0.0, 0.1, 0.0, 0.0, 0.0) end
            else
                local pVecX, pVecY, pVecZ = getCharVelocity(playerPed)
                if pVecZ < 7.0 then setCharVelocity(playerPed, 0.0, 0.0, 10.0) end
            end
        end

        if isKeyJustPressed(VK_BACK) and isCharInAnyCar(playerPed) then -- turn back
            local cVecX, cVecY, cVecZ = getCarSpeedVector(storeCarCharIsInNoSave(playerPed))
            applyForceToCar(storeCarCharIsInNoSave(playerPed), -cVecX / 25, -cVecY / 25, -cVecZ / 25, 0.0, 0.0, 0.0)
            local x, y, z, w = getVehicleQuaternion(storeCarCharIsInNoSave(playerPed))
            local matrix = {convertQuaternionToMatrix(w, x, y, z)}
            matrix[1] = -matrix[1]
            matrix[2] = -matrix[2]
            matrix[4] = -matrix[4]
            matrix[5] = -matrix[5]
            matrix[7] = -matrix[7]
            matrix[8] = -matrix[8]
            local w, x, y, z = convertMatrixToQuaternion(matrix[1], matrix[2], matrix[3], matrix[4], matrix[5], matrix[6], matrix[7], matrix[8], matrix[9])
            setVehicleQuaternion(storeCarCharIsInNoSave(playerPed), x, y, z, w)
        end

        if isKeyJustPressed(VK_N) and isCharInAnyCar(playerPed) then -- fast exit
            local posX, posY, posZ = getCarCoordinates(storeCarCharIsInNoSave(playerPed))
            warpCharFromCarToCoord(playerPed, posX, posY, posZ)
        end

        if isCharPlayingAnim(playerPed, 'KO_SKID_BACK') or isCharPlayingAnim(playerPed, 'FALL_COLLAPSE') then -- no fall
            clearCharTasksImmediately(playerPed)
        end
      
        if chatstring == "Server closed the connection." or chatstring == "You are banned from this server." then
            local chatstring = sampGetChatString(99)
            sampDisconnectWithReason(false)
            wait(17000)
            sampSetGamestate(1)
        elseif isKeyDown(0x10) and isKeyDown(0x30) and not sampIsChatInputActive() then
            sampSetGamestate(1)
        end
      
        if testCheat("mm") then
            sampSendChat("/mm")
        end
    end
end
-- turn back
это че за фича такая?
 

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
1,417
1,030
Возможно ли как-то обновить информацию о сервере (как при нажатии на Refresh в клиенте), дабы не было ошибки "The server didn't respond. Retrying.."?
можно, например, с использованием библиотеки luasocket
Библиотеки(https://blast.hk/threads/16031/) в файле _libs_test есть пример.
 

Jason2222

Известный
180
3
Не могу найти код, который эмулирует нажатие клавиши,
Это не подходит. Подскажите, если есть. Нужно так, чтоб одной командой клавиша активировалась и сразу же деактивировалась.
Код:
setVirtualKeyDown(32, true)
wait(20)
    setVirtualKeyDown(32, false)
 

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Не могу найти код, который эмулирует нажатие клавиши,
Это не подходит. Подскажите, если есть. Нужно так, чтоб одной командой клавиша активировалась и сразу же деактивировалась.
Код:
setVirtualKeyDown(32, true)
wait(20)
    setVirtualKeyDown(32, false)
setGameKeyState(int key, int state)