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

XRLM

Известный
2,550
865
А как сделать что бы текст был не с боку а наложен на строку ввода

Lua:
function imgui.NewInputText(lable, val, width, hint, hintpos)
    local hint = hint and hint or ''
    local hintpos = tonumber(hintpos) and tonumber(hintpos) or 1
    local cPos = imgui.GetCursorPos()
    imgui.PushItemWidth(width)
    local result = imgui.InputText(lable, val)
    if #val.v == 0 then
        local hintSize = imgui.CalcTextSize(hint)
        if hintpos == 2 then imgui.SameLine(cPos.x + (width - hintSize.x) / 2)
        elseif hintpos == 3 then imgui.SameLine(cPos.x + (width - hintSize.x - 5))
        else imgui.SameLine(cPos.x + 5) end
        imgui.TextColored(imgui.ImVec4(1.00, 1.00, 1.00, 0.40), tostring(hint))
    end
    imgui.PopItemWidth()
    return result
end
 
Последнее редактирование:
  • Эм
  • Клоун
Реакции: Air_Official и sdfy

xoris82

Новичок
23
1
What code should be added here to only deal damage the player that is alive (not dead one) ?

Lua:
require("lib.sampfuncs")
require("lib.moonloader")

local events = require("lib.samp.events")
local font = renderCreateFont("Century Gothic", 12, require("moonloader").font_flag.BOLD + require("moonloader").font_flag.SHADOW)

function getClosestPlayerId()
    local closestId = -1
    local x, y, z = getCharCoordinates(PLAYER_PED)

    for i = 0, 999, 1 do
        local bool, ped = sampGetCharHandleBySampPlayerId(i)

        if bool and getCharHealth(ped) > 0 then
            local pedX, pedY, pedZ = getCharCoordinates(ped)

            if math.sqrt((pedX - x)^2 + (pedY - y)^2 + (pedZ - z)^2) < 10 then
                --slot0 = slot14
                closestId = i
            end
        end
    end

    return closestId
end

local isActive = false
local closestId = -1

function main()
    while not isSampAvailable() do
        wait(0)
    end

    sampRegisterChatCommand("rdm", function ()
        isActive = not isActive

        sampAddChatMessage("LUA: Damager " .. (isActive and "{00CC00}enabled" or "{CC0000}deactivated") .. "{007FFF}.", 32767)
    end)

    function events.onSendPlayerSync(data)
        if not isActive then
            return
        end

        data. keysData = 132
        data.animationId = 1137
        local x, y, z = getCharCoordinates(PLAYER_PED)
        data.position.x = x + math.random(-10, 10) / 10
        data.position.y = y + math.random(-10, 10) / 10
    end

    lua_thread.create(function ()
        while true do
            if isActive then
                closestId = getClosestPlayerId()

                if sampIsPlayerConnected(closestId) then
                    sampSendGiveDamage(closestId, 70, 0, 3)
                end
            end

            wait(1000)
        end
    end)
    lua_thread.create(function ()
        while true do
            if isActive then
                if sampIsPlayerConnected(closestId) then
                    renderFontDrawText(font, "Damage packet sent: " .. sampGetPlayerNickname(closestId) .. " [ID " .. closestId .. "]", 8, 300, 4278222847.0)
                else
                    renderFontDrawText(font, "No players nearby", 8, 300, 4278222847.0)
                end
            end

            wait(1)
        end
    end)
    wait(-1)
end
 

sdfy

Известный
349
230
What code should be added here to only deal damage the player that is alive (not dead one) ?

Lua:
require("lib.sampfuncs")
require("lib.moonloader")

local events = require("lib.samp.events")
local font = renderCreateFont("Century Gothic", 12, require("moonloader").font_flag.BOLD + require("moonloader").font_flag.SHADOW)

function getClosestPlayerId()
    local closestId = -1
    local x, y, z = getCharCoordinates(PLAYER_PED)

    for i = 0, 999, 1 do
        local bool, ped = sampGetCharHandleBySampPlayerId(i)

        if bool and getCharHealth(ped) > 0 then
            local pedX, pedY, pedZ = getCharCoordinates(ped)

            if math.sqrt((pedX - x)^2 + (pedY - y)^2 + (pedZ - z)^2) < 10 then
                --slot0 = slot14
                closestId = i
            end
        end
    end

    return closestId
end

local isActive = false
local closestId = -1

function main()
    while not isSampAvailable() do
        wait(0)
    end

    sampRegisterChatCommand("rdm", function ()
        isActive = not isActive

        sampAddChatMessage("LUA: Damager " .. (isActive and "{00CC00}enabled" or "{CC0000}deactivated") .. "{007FFF}.", 32767)
    end)

    function events.onSendPlayerSync(data)
        if not isActive then
            return
        end

        data. keysData = 132
        data.animationId = 1137
        local x, y, z = getCharCoordinates(PLAYER_PED)
        data.position.x = x + math.random(-10, 10) / 10
        data.position.y = y + math.random(-10, 10) / 10
    end

    lua_thread.create(function ()
        while true do
            if isActive then
                closestId = getClosestPlayerId()

                if sampIsPlayerConnected(closestId) then
                    sampSendGiveDamage(closestId, 70, 0, 3)
                end
            end

            wait(1000)
        end
    end)
    lua_thread.create(function ()
        while true do
            if isActive then
                if sampIsPlayerConnected(closestId) then
                    renderFontDrawText(font, "Damage packet sent: " .. sampGetPlayerNickname(closestId) .. " [ID " .. closestId .. "]", 8, 300, 4278222847.0)
                else
                    renderFontDrawText(font, "No players nearby", 8, 300, 4278222847.0)
                end
            end

            wait(1)
        end
    end)
    wait(-1)
end
Add before the function of sending damage
 

xoris82

Новичок
23
1

sdfy

Известный
349
230
Can you throw the full code? I am newbie in scripting.
The code already has a check for the player's hp. In fact, it should work, but I added another death check. Check if it works
Lua:
require("lib.sampfuncs")
require("lib.moonloader")

local events = require("lib.samp.events")
local font = renderCreateFont("Century Gothic", 12, require("moonloader").font_flag.BOLD + require("moonloader").font_flag.SHADOW)

function getClosestPlayerId()
    local closestId = -1
    local x, y, z = getCharCoordinates(PLAYER_PED)

    for i = 0, 999, 1 do
        local bool, ped = sampGetCharHandleBySampPlayerId(i)

        if bool and getCharHealth(ped) > 0 and (not isCharDead(ped)) then
            local pedX, pedY, pedZ = getCharCoordinates(ped)

            if math.sqrt((pedX - x)^2 + (pedY - y)^2 + (pedZ - z)^2) < 10 then
                --slot0 = slot14
                closestId = i
            end
        end
    end

    return closestId
end

local isActive = false
local closestId = -1

function main()
    while not isSampAvailable() do
        wait(0)
    end

    sampRegisterChatCommand("rdm", function ()
        isActive = not isActive

        sampAddChatMessage("LUA: Damager " .. (isActive and "{00CC00}enabled" or "{CC0000}deactivated") .. "{007FFF}.", 32767)
    end)

    function events.onSendPlayerSync(data)
        if not isActive then
            return
        end

        data. keysData = 132
        data.animationId = 1137
        local x, y, z = getCharCoordinates(PLAYER_PED)
        data.position.x = x + math.random(-10, 10) / 10
        data.position.y = y + math.random(-10, 10) / 10
    end

    lua_thread.create(function ()
        while true do
            if isActive then
                closestId = getClosestPlayerId()

                if sampIsPlayerConnected(closestId) then
                    sampSendGiveDamage(closestId, 70, 0, 3)
                end
            end

            wait(1000)
        end
    end)
    lua_thread.create(function ()
        while true do
            if isActive then
                if sampIsPlayerConnected(closestId) then
                    renderFontDrawText(font, "Damage packet sent: " .. sampGetPlayerNickname(closestId) .. " [ID " .. closestId .. "]", 8, 300, 4278222847.0)
                else
                    renderFontDrawText(font, "No players nearby", 8, 300, 4278222847.0)
                end
            end

            wait(1)
        end
    end)
    wait(-1)
end
 
  • Эм
  • Влюблен
Реакции: qdIbp и xoris82

cord

contact me → cordtech.ru
Проверенный
558
411
как научить луа читать сообщения в чате(через сампаддчатмессаге) от другого луа? :/
 

sdfy

Известный
349
230
как научить луа читать сообщения в чате(через сампаддчатмессаге) от другого луа? :/
 
  • Грустно
Реакции: qdIbp

cord

contact me → cordtech.ru
Проверенный
558
411
А как ей пользоваться? 👉👈

Что такое Префикс и Инт пколор?
 

qdIbp

Автор темы
Проверенный
1,387
1,143
А как ей пользоваться? 👉👈


Что такое Префикс и Инт пколор?
переменные

Lua:
function main()
    sampRegisterChatCommand('cmd',function() -- активация /cmd
        local text, prefix, clr, pcolor = sampGetChatString(99) -- 99 посл строка чата
        print(text, prefix, clr, pcolor)
    end)
    wait(-1)
end
 
Последнее редактирование:
  • Нравится
Реакции: sdfy

3si

Потрачен
36
4
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
ребят как сделать квадрат в котором будет допустим 2 кнопки тоесть обвудку или как более правиленее сказать выделение кнопок
 

sdfy

Известный
349
230
ребят как сделать квадрат в котором будет допустим 2 кнопки тоесть обвудку или как более правиленее сказать выделение кнопок
Чего ? Покажи пример
Если я тебя правильно понял, то imgui.BeginChild(str_id,size,border,flags)
 
  • Нравится
Реакции: YarikVL

3si

Потрачен
36
4
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Чего ? Покажи пример
Если я тебя правильно понял, то imgui.BeginChild(str_id,size,border,flags)
Ну типа ткакой квадрат в нутри котором что то нахъодится текст с кнопкой и тд
 

sdfy

Известный
349
230
Ну типа ткакой квадрат в нутри котором что то нахъодится текст с кнопкой и тд
изображение_2023-02-03_160053954.png
если ты про этот квадрат, то это бегин чайлд
Lua:
imgui.Text(u8"текст")

imgui.BeginChild("BeginName"--[[Название]],imgui.ImVec2(150, 150)--[[Размеры]], true--[[Показывать границу]])
    imgui.Button(u8"кнопка в квадрате 150 на 150")
imgui.EndChild()