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

papercut

Известный
125
25
Подскажите можно ли рендером нарисовать замкнутую фигуру и ее зафиллить каким нибудь цветом
или лучше сразу на каком нибудь имгуи делать подобное
Сейчас фигура рисуется если что таким способом
Lua:
 renderBegin(2)
    renderColor(color_good)
    renderVertex(start_x, curpos_y)
    renderVertex(start_x+box_lenght, curpos_y)
    renderVertex(start_x+box_lenght, curpos_y)
    renderVertex(start_x+box_lenght-10, curpos_y+width)
    renderVertex(start_x+box_lenght-10, curpos_y+width)
    renderVertex(start_x, curpos_y+width)
    renderVertex(start_x, curpos_y+width)
    renderVertex(start_x, curpos_y)
renderEnd()
ап
 

Wer_tyn

Участник
91
15
Как можно сделать чтобы если kaban=false 10 минут то выполнялось какое-то действие?
 

Wer_tyn

Участник
91
15
Как сделать чтобы если gametext был wow то выполнялось какое-то действие? RakSAMP
 

hihihehe

Потрачен
7
32
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
  • Влюблен
Реакции: Naito

kryoheart

Новичок
2
0
почему после того как скрипт включается, он крашится? вот код:

Lua:
function cmd()
 state = not state
 printStringNow("WHH "..(state and "enabled" or "disabled"), 2000)
 wait(0)
    while true do
     if state == true then
         for id = 0, 2048 do
             if sampIs3dTextDefined(id) then
                local text, color, x, y, z, distance, ignoreWalls, player, vehicle = sampGet3dTextInfoById(id)
                  if text:find("text1") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text2") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text3") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
            end
        end
     end
    end
end
 

papercut

Известный
125
25
почему после того как скрипт включается, он крашится? вот код:

Lua:
function cmd()
 state = not state
 printStringNow("WHH "..(state and "enabled" or "disabled"), 2000)
 wait(0)
    while true do
     if state == true then
         for id = 0, 2048 do
             if sampIs3dTextDefined(id) then
                local text, color, x, y, z, distance, ignoreWalls, player, vehicle = sampGet3dTextInfoById(id)
                  if text:find("text1") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text2") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text3") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
            end
        end
     end
    end
end
такой файл вообще не будет запускаться тк нету ни одного вызова ни одной функции. Зачем-то бесконечный цикл используется... еще и без задержки на каждый кадр. Короче, я бы рекомендовал ознакомиться с азами, тут слишком много изначально неверно написанного кода
 

kryoheart

Новичок
2
0
такой файл вообще не будет запускаться тк нету ни одного вызова ни одной функции. Зачем-то бесконечный цикл используется... еще и без задержки на каждый кадр. Короче, я бы рекомендовал ознакомиться с азами, тут слишком много изначально неверно написанного кода
там есть мэйн, я просто его сюда не вставил
вот весь код
Lua:
local state = false
local events = require "lib.samp.events"
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(200) end
    sampRegisterChatCommand("whh", cmd)
    wait(-1)
end
function cmd()
 state = not state
 printStringNow("WHH "..(state and "enabled" or "disabled"), 2000)
 wait(0)
    while true do
     if state == true then
         for id = 0, 2048 do
             if sampIs3dTextDefined(id) then
                local text, color, x, y, z, distance, ignoreWalls, player, vehicle = sampGet3dTextInfoById(id)
                  if text:find("text1") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text2") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text3") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
            end
        end
     end
    end
end
 

Masayuki

Участник
94
36
почему после того как скрипт включается, он крашится? вот код:

Lua:
function cmd()
 state = not state
 printStringNow("WHH "..(state and "enabled" or "disabled"), 2000)
 wait(0)
    while true do
     if state == true then
         for id = 0, 2048 do
             if sampIs3dTextDefined(id) then
                local text, color, x, y, z, distance, ignoreWalls, player, vehicle = sampGet3dTextInfoById(id)
                  if text:find("text1") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text2") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
                if text:find("text3") then
                     if isPointOnScreen(x, y, z, 3.0) then
                         xp, yp, zp = getCharCoordinates(PLAYER_PED)
                         x1, y2 = convert3DCoordsToScreen(x, y, z)
                         p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                         distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                         text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                         renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                         renderFontDrawText(font, text, x1, y2, -1)
                    end
                end
            end
        end
     end
    end
end
Lua:
local state = false
local events = require "lib.samp.events"
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function main()
    while not isSampAvailable() do wait(200) end
    sampRegisterChatCommand('whh', function()
        state = not state
    end)

    while true do
        wait(0)
        if state then
            for id = 0, 2048 do
                if sampIs3dTextDefined(id) then
                    local text, color, x, y, z, distance, ignoreWalls, player, vehicle = sampGet3dTextInfoById(id)
                    if text:find("text1") then
                        if isPointOnScreen(x, y, z, 3.0) then
                            xp, yp, zp = getCharCoordinates(PLAYER_PED)
                            x1, y2 = convert3DCoordsToScreen(x, y, z)
                            p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                            distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                            text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                            renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                            renderFontDrawText(font, text, x1, y2, -1)
                        end
                    end
                    if text:find("text2") then
                        if isPointOnScreen(x, y, z, 3.0) then
                            xp, yp, zp = getCharCoordinates(PLAYER_PED)
                            x1, y2 = convert3DCoordsToScreen(x, y, z)
                            p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                            distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                            text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                            renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                            renderFontDrawText(font, text, x1, y2, -1)
                        end
                    end
                    if text:find("text3") then
                        if isPointOnScreen(x, y, z, 3.0) then
                            xp, yp, zp = getCharCoordinates(PLAYER_PED)
                            x1, y2 = convert3DCoordsToScreen(x, y, z)
                            p3, p4 = convert3DCoordsToScreen(xp, yp, zp)
                            distance = string.format("%.0f", getDistanceBetweenCoords3d(x, y, z, xp, yp, zp))
                            text = ("{ffffff}text {ff0000}Дистанция: "..distance)
                            renderDrawLine(x1, y2, p3, p4, 1.1, 0xFFFF0000)
                            renderFontDrawText(font, text, x1, y2, -1)
                        end
                    end
                end
            end
        end
    end
end
 

m1racles

Активный
204
36
Lua:
function sendmessage(token, message, chatId)
    local url = "https://api.telegram.org/bot" .. token .. "/sendMessage?"
    local params = "chat_id=" .. chatId .. "&text=" .. message
   
    local response = request.get(url .. params)
   
    if response.status_code == 200 then
        print("sent: " .. message)
    else
        print("error " .. response.status_code)
    end
end
function sampev.onServerMessage(color, text)
    if text:find("прив") then
        message = text
        sendmessage(token, message, chatId)
    end
end
кулити, столкнулся с проблемой, text:find выполняет свою функцию, это видно по микрофризу после найденого сообщения, но если текст на кириллице, то ничего не работает, более того не хочет отправлять сообщение если оно не начинается с символа, допустим ic чат не отправляет, а ooc спокойно, в чем траблы?кодировка правильная