Вопросы по 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,481
1,113
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        result, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        if sampGetPlayerHealth(id) <= 20 then
        sampSendChat(string.format("/heal %s 5000", select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))))
        end
    end
end
Я же тебе ссылку дал с кодом. Возьми оттуда код и замени sampSendChat с того кода на sampSendChat, который я дал.
 
  • Нравится
Реакции: qdIbp

Marat Krutoi

Участник
56
9
Как делать такие 3д есп боксы
1693232607362.png
дайте код пожалуйста
пол бх поискал нашел но код то не понятный то не рабочий
Зарание блогадарен
 

sssilvian

Активный
230
25
Есть ли способ создать скрипт, который выдает ложный урон от проезжавшего мимо автомобиля конкретного игрока?
 

Dmitriy Makarov

25.05.2021
Проверенный
2,481
1,113
Как делать такие 3д есп боксы Посмотреть вложение 213491 дайте код пожалуйста
пол бх поискал нашел но код то не понятный то не рабочий
Зарание блогадарен
 

Marat Krutoi

Участник
56
9
можно как то сделать чтобы оно для других игроков рендерило а то только меня показывает
1693234880410.png
 
  • Ха-ха
Реакции: Andrinall

Rice.

Известный
Модератор
1,698
1,466
можно как то сделать чтобы оно для других игроков рендерило а то только меня показывает
Посмотреть вложение 213497
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do wait(0)
       for k, v in ipairs(getAllChars()) do
          getCharModelCornersIn2d(getCharModel(v), select(2, sampGetPlayerIdByCharHandle(v)))
       end
    end
end

function getCharModelCornersIn2d(id, handle)
    local x1, y1, z1, x2, y2, z2 = getModelDimensions(id)
    local t = {
        [1] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1         , y1 * -1.1, z1))}, -- {x = x1, y = y1 * -1.0, z = z1},
        [2] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1 * -1.0  , y1 * -1.1, z1))}, -- {x = x1 * -1.0, y = y1 * -1.0, z = z1},
        [3] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1 * -1.0  , y1       , z1))}, -- {x = x1 * -1.0, y = y1, z = z1},
        [4] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1         , y1       , z1))}, -- {x = x1, y = y1, z = z1},
        [5] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2 * -1.0  , y2       , z2))}, -- {x = x2 * -1.0, y = 0, z = 0},
        [6] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2 * -1.0  , y2 * -0.9, z2))}, -- {x = x2 * -1.0, y = y2 * -1.0, z = z2},
        [7] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2         , y2 * -0.9, z2))}, -- {x = x2, y = y2 * -1.0, z = z2},
        [8] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2         , y2       , z2))}, -- {x = x2, y = y2, z = z2},
    }
    return t
end
 
  • Вау
  • Влюблен
Реакции: qdIbp и Marat Krutoi

Marat Krutoi

Участник
56
9
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do wait(0)
       for k, v in ipairs(getAllChars()) do
          getCharModelCornersIn2d(getCharModel(v), select(2, sampGetPlayerIdByCharHandle(v)))
       end
    end
end

function getCharModelCornersIn2d(id, handle)
    local x1, y1, z1, x2, y2, z2 = getModelDimensions(id)
    local t = {
        [1] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1         , y1 * -1.1, z1))}, -- {x = x1, y = y1 * -1.0, z = z1},
        [2] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1 * -1.0  , y1 * -1.1, z1))}, -- {x = x1 * -1.0, y = y1 * -1.0, z = z1},
        [3] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1 * -1.0  , y1       , z1))}, -- {x = x1 * -1.0, y = y1, z = z1},
        [4] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x1         , y1       , z1))}, -- {x = x1, y = y1, z = z1},
        [5] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2 * -1.0  , y2       , z2))}, -- {x = x2 * -1.0, y = 0, z = 0},
        [6] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2 * -1.0  , y2 * -0.9, z2))}, -- {x = x2 * -1.0, y = y2 * -1.0, z = z2},
        [7] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2         , y2 * -0.9, z2))}, -- {x = x2, y = y2 * -1.0, z = z2},
        [8] = {convert3DCoordsToScreen(getOffsetFromCharInWorldCoords(handle, x2         , y2       , z2))}, -- {x = x2, y = y2, z = z2},
    }
    return t
end
не пашит(
[ML] (error) teeet.lua: opcode '04C4' call caused an unhandled exception
stack traceback:
[C]: in function 'getOffsetFromCharInWorldCoords'
D:\original pidors\moonloader\teeet.lua:13: in function 'getCharModelCornersIn2d'
D:\original pidors\moonloader\teeet.lua:5: in function <D:\summer for feldan\moonloader\teeet.lua:1>
 
  • Злость
Реакции: qdIbp

tsunamiqq

Участник
429
16
Как добавить смену цвета иконки --text[1]
Lua:
function imgui.MenuButton(text, size)
    local dl = imgui.GetWindowDrawList()
    local p = imgui.GetCursorScreenPos()

    local result = imgui.Button('##' .. text[2], size)
    dl:AddText(imgui.ImVec2(p.x + 10, p.y + (size.y - imgui.CalcTextSize(text[1]).y) / 2), imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col['Text']]), text[1])
    dl:AddText(imgui.ImVec2(p.x + 50, p.y + (size.y - imgui.CalcTextSize(text[2]).y) / 2), imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col['Text']]), text[2])

    return result
end
 

Rice.

Известный
Модератор
1,698
1,466
не пашит(
[ML] (error) teeet.lua: opcode '04C4' call caused an unhandled exception
stack traceback:
[C]: in function 'getOffsetFromCharInWorldCoords'
D:\original pidors\moonloader\teeet.lua:13: in function 'getCharModelCornersIn2d'
D:\original pidors\moonloader\teeet.lua:5: in function <D:\summer for feldan\moonloader\teeet.lua:1>
Lua:
getCharModelCornersIn2d(getCharModel(v), v)
моя ошибка
 

Rice.

Известный
Модератор
1,698
1,466
Спасибо, я ошибся!
но как можно сделать чтобы меня не рендерило а только игроков кроме меня

Посмотреть вложение 213503

Посмотреть вложение 213504

Посмотреть вложение 213502
Lua:
function main()
    while not isSampAvailable() do wait(0) end
    while true do wait(0)
       for k, v in ipairs(getAllChars()) do
          if v ~= PLAYER_PED then
              getCharModelCornersIn2d(getCharModel(v), v)
          end
       end
    end
end
 
  • Нравится
Реакции: MLycoris

tsunamiqq

Участник
429
16
Как настроить что-бы в imgui.MenuButton мог сам выбирать цвет иконки --text[1]
Lua:
function imgui.MenuButton(text, size)
    local dl = imgui.GetWindowDrawList()
    local p = imgui.GetCursorScreenPos()
    local color = imgui.ImVec4(0, 1, 0, 0.63)
    local result = imgui.Button('##' .. text[2], size)

    dl:AddText(imgui.ImVec2(p.x + 10, p.y + (size.y - imgui.CalcTextSize(text[1]).y) / 2), imgui.GetColorU32Vec4(color), text[1])
    dl:AddText(imgui.ImVec2(p.x + 40, p.y + (size.y - imgui.CalcTextSize(text[2]).y) / 2), imgui.GetColorU32Vec4(imgui.GetStyle().Colors[imgui.Col['Text']]), text[2])
    return result
end
 

Marat Krutoi

Участник
56
9
У меня такая проблема что если у меня сзади стоит игрок то renderDrawLine показывает его спереди
(в бх я фотку загрузить не могу и на это есть причина но загрузил в imgur)
Скрин с игры где я вперед смотрю
Скрин с игры где я назад смотрю

Код
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    while true do
        wait(0)
        for k, v in pairs(getAllChars()) do
            if v ~= PLAYER_PED then
                local c = getCharModelCornersIn2d(getCharModel(v), v)
                local X, Y = getScreenResolution()
                renderFigure2D(X/2, Y/2, 100, 250, 0xFF4682B4) -- нарисует круг с белой
                local x, y, z = getCharCoordinates(PLAYER_PED)
                local possaX, possaY, possaZ = getScreenResolution()
                local posX, posY = convert3DCoordsToScreen(x, y, z)
                local player = getNearCharToCenter(200)
                local color = tonumber("0xFF"..(("%X"):format(sampGetPlayerColor(id))):gsub(".*(......)", "%1"))--sampGetPlayerColor(id)
                local result, id = sampGetPlayerIdByCharHandle(v)
            end
            if player then
                local playerId = select(2, sampGetPlayerIdByCharHandle(player))
                local playerNick = sampGetPlayerNickname(playerId)
                local x2, y2, z2 = getCharCoordinates(player)
                local isScreen = isPointOnScreen(x2, y2, z2, 200)
            end   
            if isScreen then
                renderDrawLine(c[1][1], c[1][2], c[2][1], c[2][2], 2, 0xFF4682B4)
                renderDrawLine(c[2][1], c[2][2], c[3][1], c[3][2], 2, 0xFF4682B4)
                renderDrawLine(c[3][1], c[3][2], c[4][1], c[4][2], 2, 0xFF4682B4)
                renderDrawLine(c[4][1], c[4][2], c[1][1], c[1][2], 2, 0xFF4682B4)
                renderDrawLine(c[5][1], c[5][2], c[6][1], c[6][2], 2, 0xFF4682B4)
                renderDrawLine(c[6][1], c[6][2], c[7][1], c[7][2], 2, 0xFF4682B4)
                renderDrawLine(c[7][1], c[7][2], c[8][1], c[8][2], 2, 0xFF4682B4)
                renderDrawLine(c[8][1], c[8][2], c[5][1], c[5][2], 2, 0xFF4682B4)
                renderDrawLine(c[1][1], c[1][2], c[5][1], c[5][2], 2, 0xFF4682B4)
                renderDrawLine(c[2][1], c[2][2], c[8][1], c[8][2], 2, 0xFF4682B4)
                renderDrawLine(c[3][1], c[3][2], c[7][1], c[7][2], 2, 0xFF4682B4)
                renderDrawLine(c[4][1], c[4][2], c[6][1], c[6][2], 2, 0xFF4682B4)
                renderDrawPolygon(X/2, Y/2, 10, 10, 7, 5, 0xFF4682B4)
                local posX2, posY2 = convert3DCoordsToScreen(x2, y2, z2)
                renderDrawLine(X/2, Y/2, posX2, posY2, 2.0, 0xFF4682B4)
                renderDrawPolygon(posX2, posY2, 10, 10, 40, 0, 0xFF4682B4)
                local distance = math.floor(getDistanceBetweenCoords3d(x, y, z, x2, y2, z2))
                renderFontDrawTextAlign(font, string.format('%s[%d]', playerNick, playerId),posX2, posY2-30, 0xFF4682B4, 2)
                renderFontDrawTextAlign(font, string.format('Дистанция: %s', distance),X/2, Y/2+210, 0xFF4682B4, 2)
                renderFontDrawTextAlign(font, 'R - OnFoot Rvanka\nX - Incar Rvanka',X/2+300, Y/2-30, 0xFF4682B4, 1)
                if isKeyJustPressed(VK_1) then
                    sampSendChat('/re '..playerId)
                end
                if isKeyJustPressed(VK_2) then
                    sampSendChat('/frem '..playerId)
                end
                if isKeyJustPressed(VK_3) then
                    sampSendChat('/spawn '..playerId)
                end
                if isKeyJustPressed(VK_4) then
                    sampSendChat('/sethp '..playerId..' 100')
                end
                if isKeyJustPressed(VK_5) then
                    sampSendChat('/gethere '..playerId)
                end
            end
        end   
    end
end