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

Royan_Millans

Известный
145
182
Lua:
imgui.Image(imgui_images.banner, imgui.ImVec2(520, 100))

            imgui.SetCursorPosY(84)
            imgui.SetCursorPosX(480)
            imgui.TextColoredRGB(u8"{FFFFFF}Версия скрипта: "..thisScript().version)

            imgui.SetCursorPosY(80)
            imgui.SetCursorPosX(610)
            if imgui.Button(u8"Что нового?") then
                selected = 101

                if update_information == nil then
                    lua_thread.create(function ()
                        wait(0)
                        asyncHttpRequest("GET", "TUT URL", nil,
                        function(response)
                            if response.text:find("version") then
                                update_information = decodeJson(response.text)
                            else
                                update_information = "error"
                            end

                        end,
                        function(err)
                            update_information = "error"
                        end)
                    end)

                end

            end

            imgui.Spacing()


            imgui.SetCursorPosY(150)
            imgui.Text(u8"Информация о Вас:")

            imgui.BeginChild("about_me", imgui.ImVec2(200, 65), true)

                if secure_info.hospital == 1 then
                    imgui.TextColoredRGB(u8"Мед. Центр: {c24f00}Floris")
                elseif secure_info.hospital == 2 then
                    imgui.TextColoredRGB(u8"Мед. Центр: {c24f00}St. Francis")
                elseif secure_info.hospital == 3 then
                    imgui.TextColoredRGB(u8"Мед. Центр: {c24f00}Kindred")
                elseif secure_info.hospital == 4 then
                    imgui.TextColoredRGB(u8"Место работы: {c24f00}АП")
                else
                    imgui.TextColoredRGB(u8"Мед. Центр: {595959}Проверка")
                end

            if secure_info.rang ~= nil then
                imgui.TextColoredRGB(u8"Ранг: {c24f00}"..secure_info.rang)
            else
                imgui.TextColoredRGB(u8"Ранг: {595959}Проверка")
            end

            imgui.EndChild()

            imgui.Spacing()

            imgui.Text(u8"Техническая информация:")

            imgui.BeginChild("status_script", imgui.ImVec2(200, 109), true, imgui.WindowFlags.NoScrollWithMouse + imgui.WindowFlags.NoScrollbar)

                if script_status == "active" then

                    imgui.TextColoredRGB(u8"Проверка обновлений: \n{15ff00}Последняя версия")
                    imgui.SetCursorPos(imgui.ImVec2(130, 34))
                    if imgui.Button(fa.ICON_FA_REDO) then
                        message("Проверка обновлений..")
                        lua_thread.create(function ()
                            wait(0)
                            asyncHttpRequest("GET", "TUT_URL", nil,
                            function(response)
                                if response.text:find("version_number") then
                                    local update_info = decodeJson(response.text)

                                    if tonumber(update_info['version_number']) ~= thisScript().version_num then
                                        message("Происходит обновление до версии "..update_info['version']..'..')

                                        downloadUrlToFile(update_info['url'], thisScript().path, function (id, status, p1, p2)
                                            if status == dlstatus.STATUS_ENDDOWNLOADDATA then

                                                message("Обновление успешно завершено!")

                                                if not doesFileExist(getWorkingDirectory() .. "\\AutoReboot.lua") then
                                                    script_reload()
                                                else
                                                    script_reload_status = true
                                                end

                                            end 
                                        end)
                                    else
                                        message("Обновлений не найдено.")
                                    end
                                else
                                    message("Скрипту не удалось проверить обновления.")
                                end

                            end,
                            function(err)
                                message("Скрипту не удалось проверить обновления.")
                            end)
                        end)

                    end

                elseif script_status == "offline_active" then

                    imgui.TextColoredRGB(u8"Проверка обновлений: \n{cc0030}Оффлайн режим")

                end

                imgui.SetCursorPosY(65)

                if secure_info.status == "wait_stats" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{15ff00}Установлено")

                elseif secure_info.status == "wait" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{e65800}Авторизация..")

                elseif secure_info.status == "error" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{cc0030}Ошибка авторизации")

                elseif secure_info.status == "active" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{e65800}Ожидание..")

                end

            imgui.EndChild()

            imgui.SetCursorPosX(390)
            imgui.SetCursorPosY(150)
            imgui.Text(u8"Новости от министра:")


            imgui.SetCursorPosX(390)
            imgui.SetCursorPosY(172)
            imgui.BeginChild("news", imgui.ImVec2(0, 0), true)

                if (secure_info.rang == 11 or GetNickName() == "Royan_Millans") and secure_info.token ~= nil then
                    if imgui.RedButton(fa.ICON_FA_TABLET_ALT..u8" Панель Министра [СЕКРЕТНО]", imgui.ImVec2(-0.1, 50)) then

                        selected = 102

                    end

                elseif (secure_info.rang == 11 or GetNickName() == "Royan_Millans") and secure_info.token == nil then

                    imgui.DisableButton(u8"Происходит авторизация..", imgui.ImVec2(-0.1, 50))

                end

                if news_list == nil then

                    imgui.Text(imgui.Text(fa.ICON_FA_SPINNER..u8(" Получение данных с сервера..")))

                elseif news_list == "error" then

                    imgui.Text(fa.ICON_FA_EXCLAMATION..u8(" Произошла ошибка во время получения данных с сервера, попробуйте позже."))

                elseif news_list == "nope" then


                    imgui.SetCursorPosX(70)
                    imgui.Text(fa.ICON_FA_SEARCH..u8(" Новостей не найдено"))

                else

                    for k, v in pairs(news_list) do

                        local status = true
  
                        for k2, v2 in pairs(check_news) do
                            if v2 == v.id then
                               status = false
                            end
                        end
                      
                        if status then
                               if imgui.NotificationButton(fa.ICON_FA_BELL.." #"..v.id.." "..v.caption, imgui.ImVec2(-0.1, 30)) then


                                   table.insert(check_news, v.id)
                                   lua_thread.create(function ()
                                    wait(0)
                                       local json = encodeJson(check_news)
                                    local handle = io.open(getWorkingDirectory() .. "\\MZ Senior\\check_news.json", "w")
                                    handle:write(json)
                                    handle:close()
                                end)

                                news_info.key = k

                                selected = 110


                               end
                        else
                            if imgui.Button("#"..v.id.." "..v.caption, imgui.ImVec2(-0.1, 30)) then

                                news_info.key = k
                                news_info.selected = selected

                                selected = 110
                            end
                        end

                    end

                end

            imgui.EndChild()

Открывается, все вроде бы работает, но через пару секунд крашит игру, в чем проблема?
 

McLore

Известный
559
279
Lua:
imgui.Image(imgui_images.banner, imgui.ImVec2(520, 100))

            imgui.SetCursorPosY(84)
            imgui.SetCursorPosX(480)
            imgui.TextColoredRGB(u8"{FFFFFF}Версия скрипта: "..thisScript().version)

            imgui.SetCursorPosY(80)
            imgui.SetCursorPosX(610)
            if imgui.Button(u8"Что нового?") then
                selected = 101

                if update_information == nil then
                    lua_thread.create(function ()
                        wait(0)
                        asyncHttpRequest("GET", "TUT URL", nil,
                        function(response)
                            if response.text:find("version") then
                                update_information = decodeJson(response.text)
                            else
                                update_information = "error"
                            end

                        end,
                        function(err)
                            update_information = "error"
                        end)
                    end)

                end

            end

            imgui.Spacing()


            imgui.SetCursorPosY(150)
            imgui.Text(u8"Информация о Вас:")

            imgui.BeginChild("about_me", imgui.ImVec2(200, 65), true)

                if secure_info.hospital == 1 then
                    imgui.TextColoredRGB(u8"Мед. Центр: {c24f00}Floris")
                elseif secure_info.hospital == 2 then
                    imgui.TextColoredRGB(u8"Мед. Центр: {c24f00}St. Francis")
                elseif secure_info.hospital == 3 then
                    imgui.TextColoredRGB(u8"Мед. Центр: {c24f00}Kindred")
                elseif secure_info.hospital == 4 then
                    imgui.TextColoredRGB(u8"Место работы: {c24f00}АП")
                else
                    imgui.TextColoredRGB(u8"Мед. Центр: {595959}Проверка")
                end

            if secure_info.rang ~= nil then
                imgui.TextColoredRGB(u8"Ранг: {c24f00}"..secure_info.rang)
            else
                imgui.TextColoredRGB(u8"Ранг: {595959}Проверка")
            end

            imgui.EndChild()

            imgui.Spacing()

            imgui.Text(u8"Техническая информация:")

            imgui.BeginChild("status_script", imgui.ImVec2(200, 109), true, imgui.WindowFlags.NoScrollWithMouse + imgui.WindowFlags.NoScrollbar)

                if script_status == "active" then

                    imgui.TextColoredRGB(u8"Проверка обновлений: \n{15ff00}Последняя версия")
                    imgui.SetCursorPos(imgui.ImVec2(130, 34))
                    if imgui.Button(fa.ICON_FA_REDO) then
                        message("Проверка обновлений..")
                        lua_thread.create(function ()
                            wait(0)
                            asyncHttpRequest("GET", "TUT_URL", nil,
                            function(response)
                                if response.text:find("version_number") then
                                    local update_info = decodeJson(response.text)

                                    if tonumber(update_info['version_number']) ~= thisScript().version_num then
                                        message("Происходит обновление до версии "..update_info['version']..'..')

                                        downloadUrlToFile(update_info['url'], thisScript().path, function (id, status, p1, p2)
                                            if status == dlstatus.STATUS_ENDDOWNLOADDATA then

                                                message("Обновление успешно завершено!")

                                                if not doesFileExist(getWorkingDirectory() .. "\\AutoReboot.lua") then
                                                    script_reload()
                                                else
                                                    script_reload_status = true
                                                end

                                            end
                                        end)
                                    else
                                        message("Обновлений не найдено.")
                                    end
                                else
                                    message("Скрипту не удалось проверить обновления.")
                                end

                            end,
                            function(err)
                                message("Скрипту не удалось проверить обновления.")
                            end)
                        end)

                    end

                elseif script_status == "offline_active" then

                    imgui.TextColoredRGB(u8"Проверка обновлений: \n{cc0030}Оффлайн режим")

                end

                imgui.SetCursorPosY(65)

                if secure_info.status == "wait_stats" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{15ff00}Установлено")

                elseif secure_info.status == "wait" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{e65800}Авторизация..")

                elseif secure_info.status == "error" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{cc0030}Ошибка авторизации")

                elseif secure_info.status == "active" then

                    imgui.TextColoredRGB(u8"Соеденение с сервером MZS: \n{e65800}Ожидание..")

                end

            imgui.EndChild()

            imgui.SetCursorPosX(390)
            imgui.SetCursorPosY(150)
            imgui.Text(u8"Новости от министра:")


            imgui.SetCursorPosX(390)
            imgui.SetCursorPosY(172)
            imgui.BeginChild("news", imgui.ImVec2(0, 0), true)

                if (secure_info.rang == 11 or GetNickName() == "Royan_Millans") and secure_info.token ~= nil then
                    if imgui.RedButton(fa.ICON_FA_TABLET_ALT..u8" Панель Министра [СЕКРЕТНО]", imgui.ImVec2(-0.1, 50)) then

                        selected = 102

                    end

                elseif (secure_info.rang == 11 or GetNickName() == "Royan_Millans") and secure_info.token == nil then

                    imgui.DisableButton(u8"Происходит авторизация..", imgui.ImVec2(-0.1, 50))

                end

                if news_list == nil then

                    imgui.Text(imgui.Text(fa.ICON_FA_SPINNER..u8(" Получение данных с сервера..")))

                elseif news_list == "error" then

                    imgui.Text(fa.ICON_FA_EXCLAMATION..u8(" Произошла ошибка во время получения данных с сервера, попробуйте позже."))

                elseif news_list == "nope" then


                    imgui.SetCursorPosX(70)
                    imgui.Text(fa.ICON_FA_SEARCH..u8(" Новостей не найдено"))

                else

                    for k, v in pairs(news_list) do

                        local status = true
 
                        for k2, v2 in pairs(check_news) do
                            if v2 == v.id then
                               status = false
                            end
                        end
                     
                        if status then
                               if imgui.NotificationButton(fa.ICON_FA_BELL.." #"..v.id.." "..v.caption, imgui.ImVec2(-0.1, 30)) then


                                   table.insert(check_news, v.id)
                                   lua_thread.create(function ()
                                    wait(0)
                                       local json = encodeJson(check_news)
                                    local handle = io.open(getWorkingDirectory() .. "\\MZ Senior\\check_news.json", "w")
                                    handle:write(json)
                                    handle:close()
                                end)

                                news_info.key = k

                                selected = 110


                               end
                        else
                            if imgui.Button("#"..v.id.." "..v.caption, imgui.ImVec2(-0.1, 30)) then

                                news_info.key = k
                                news_info.selected = selected

                                selected = 110
                            end
                        end

                    end

                end

            imgui.EndChild()

Открывается, все вроде бы работает, но через пару секунд крашит игру, в чем проблема?
Ну так лог дай
 

Стэнфорд

Потрачен
1,058
540
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
q, можно ли как-то отследить когда кто-то садится к персу в такси?
 

encore:

Новичок
26
1
Я не могу засунуть в название кнопки переменную, так вообще можно?Если да буду благодарен, если ещё и подскажите как)
 

Tak

Известный
176
70
Привет ребятишки, кто мне сможет расписать данную функцию? (особенно строчку function runTo(x, y, z, runKey, xcam, plusChange) что за атрибуты runKey, xcam, plusChange)

Lua:
local jumpThr
function runTo(x, y, z, runKey, xcam, plusChange)
repeat
local pX, pY, pZ = getCharCoordinates(playerPed)
local gg = fix(representIntAsFloat(readMemory(0xB6F258, 4, false)))
local wp = fix(representIntAsFloat(readMemory(0xB6F248, 4, false)))
local gg = gg + math.pi
local nad = GetAngleBeetweenTwoPoints(x,y)
local test = GetAngleBeetweenTwoPoints(x,y) - gg - math.pi
local dist = getDistanceBetweenCoords3d(x,y,z, pX, pY, pZ)

if plusChange == nil then plusChange = 0.0 end
local ot = 1.5
local waitTime = representIntAsFloat(readMemory(0xB7CB5C, 4, false))/42
wait(waitTime)
if runKey ~= nil then
setGameKeyState(1, -128)
else
setGameKeyState(1, -128)
end
if runKey == 1 then
setGameKeyState(16, 255)
elseif runKey == 2 then
setGameKeyState(21, 255)
elseif runKey == 3 then
if dist >= 5.4 then
if jumpThr == nil then
local x = math.random(1, 100000)
if x >= 94000 then
jumpThr = lua_thread.create(function()
wait(200)
setGameKeyState(14, 255) -- its not jump
jumpThr = nil
end)
end
end
end
elseif runKey == 4 then
setGameKeyState(17, 255)
end
local changeFloat = 0.04 --DEFAULT 0.04
if runKey == 1 then
if dist > 5.0 then changeFloat = 0.08 +plusChange
elseif dist > 3.0 then changeFloat = 0.1 +plusChange
elseif dist > 1.8 then changeFloat = 0.04 + plusChange
end
elseif runKey == 0 then
if dist > 5.0 then changeFloat = 0.08 + plusChange
elseif dist > 3.0 then changeFloat = 0.12 + plusChange
elseif dist > 1.8 then changeFloat = 0.14 +plusChange
end
elseif runKey == 3 then
if dist > 5.0 then changeFloat = 0.08 + plusChange
elseif dist > 3.0 then changeFloat = 0.12 + plusChange
elseif dist > 1.8 then changeFloat = 0.14 +plusChange
end
end
if dist > 1.8 then
if test > -0.1 and test < 0.03 then setCameraPositionUnfixed(xcam, GetAngleBeetweenTwoPoints(x,y))
elseif test < -5.7 and test > -5.93 then setCameraPositionUnfixed(xcam, GetAngleBeetweenTwoPoints(x,y))
elseif test < -6.0 and test > -6.4 then setCameraPositionUnfixed(xcam, GetAngleBeetweenTwoPoints(x,y))
elseif test > 0.04 then setCameraPositionUnfixed(xcam, fix(representIntAsFloat(readMemory(0xB6F258, 4, false)))+changeFloat)
elseif test < -3.5 and test > -5.67 then setCameraPositionUnfixed(xcam, fix(representIntAsFloat(readMemory(0xB6F258, 4, false)))+changeFloat)
else setCameraPositionUnfixed(xcam, fix(representIntAsFloat(readMemory(0xB6F258, 4, false)))-changeFloat)
end
else
setCameraPositionUnfixed(wp, GetAngleBeetweenTwoPoints(x,y))
end
until dist < ot
end

function GetAngleBeetweenTwoPoints(x2,y2)
local x1, y1, z1 = getCharCoordinates(playerPed)
local plus = 0.0
local mode = 1
if x1 < x2 and y1 > y2 then plus = math.pi/2; mode = 2; end
if x1 < x2 and y1 < y2 then plus = math.pi; end
if x1 > x2 and y1 < y2 then plus = math.pi*1.5; mode = 2; end
local lx = x2 - x1
local ly = y2 - y1
lx = math.abs(lx)
ly = math.abs(ly)
if mode == 1 then ly = ly/lx;
else ly = lx/ly; end
ly = math.atan(ly)
ly = ly + plus
return ly
end

function GetXAngle(startDist, dist, startXAngle, x,y,z)
local x1, y1, z1 = getCharCoordinates(playerPed)
local xAngle
if mnum(z) > mnum(z1) then
xAngle = 2
elseif -68 >= z and dist > 2.8 and z1 <= -67.0 then
xAngle = 0
else
local interest = (dist*100)/startDist
if interest == 0 then
interest = 100
end
if interest > 65 then
xAngle = 2*(100-interest)/100-2
else
xAngle = 2*interest/100-2
end
end
return xAngle
end


function mnum(number)
return (number - (number % 0.1))+0.1
end

function fix(angle)
while angle > math.pi do
angle = angle - (math.pi*2)
end
while angle < -math.pi do
angle = angle + (math.pi*2)
end
return angle
end
Похоже на аим, где прицеливание идет с помощью камеры
 

damag

Женюсь на официантке в моем любимом баре
Проверенный
1,152
1,194
У меня есть бот вк, и мне нужно когда чел написал ему, бот ответил ему
Подскажите как сделать
 

danywa

Активный
358
50
Lua:
function main()
    repeat wait(0) until isSampAvailable()
    wait(2000)
  sampRegisterChatCommand('ru', cmd_ru)
 
   while true do
  wait(0)

end
end

function cmd_ru()
 if text:match('Можно открывать только с 3-го уровня!') then
        msg = text:match('Можно открывать только с 3-го уровня!')
    sampAddChatMessage('11111', -1)     
    end
end
В чем проблема и еще как сделать,чтобы активация была не на команду,а как только этот текст появится в чате?