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

Curtis

Участник
282
10
В input строку вписываю некий текст, после чего он ниже в imgui окне отображает что я вписал в строку, но текст может быть разным, как сделать, чтобы результат( текст который выводится на окно) переносился на новую строку если он вылазит за рамки окна?
up
 

wulfandr

Известный
635
259
Hello , why magic character "$" doesn't work? when i type in chat "test give pie test" it says in chat "pie test" , but it shouldn't and when i type "test give pie" it should work because it ends with word from array.
Lua:
function sampev.onServerMessage(color,text)
if enabled then

    local words = {'banana', 'apple', 'pie'}
if text:find('(.*)%sgive%s(.*)$') then
    local word1, word2 = text:match('(.*)%sgive%s(.*)$')
    for i, v in ipairs(words) do
   if word2:lower():find(v) then
    sampAddChatMessage(word2,-1)
    end
    end
end


end
end
Lua:
function sampev.onServerMessage(color,text)
    if enabled then
        local words = {'banana', 'apple', 'pie'}
        if text:find('.+ give .+') then
            local word1, word2 = text:match('(.+) give (.+)')
            for i, v in ipairs(words) do
                if word2:lower():find(v) then
                    sampAddChatMessage(v,-1)
                end
            end
        end
    end
end
 

Warklot

Известный
112
3
Lua:
function sampev.onServerMessage(color,text)
    if enabled then
        local words = {'banana', 'apple', 'pie'}
        if text:find('.+ give .+') then
            local word1, word2 = text:match('(.+) give (.+)')
            for i, v in ipairs(words) do
                if word2:lower():find(v) then
                    sampAddChatMessage(v,-1)
                end
            end
        end
    end
end

but when i write lets say 'test give pietest" it still counts because "pietest" contains "pie" but i don't want for it to count.
 

Alexandr199921

Новичок
3
0
Не работает скрипт выдает ошибку. Помогите пожалуйста, в чём ошибка то?
Lua:
[/B]
Скрипт завершен:
Ошибка скрипта: luaj.o: load /storage/emulated/0/Download/sf3_1_25_7_AutoWin_jska_bin.lua: luaj.o: /storage/emulated/0/Download/sf3_1_25_7_AutoWin_jska_bin.lua:8
`"Exit"}, nil, "script 3.3 | game 1.25.5" | Autor: NIKKI)`
function arguments expected near )
    at luaj.LuaValue.a(src:997)
    at luaj.Globals.c_(src:255)
    at android.ext.Script.d(src:5992)
    at android.ext.Script$ScriptThread.run(src:5785)
Caused by: luaj.o: /storage/emulated/0/Download/sf3_1_25_7_AutoWin_jska_bin.lua:8
`"Exit"}, nil, "script 3.3 | game 1.25.5" | Autor: NIKKI)`
function arguments expected near )
    at luaj.a.h.a(src:295)
    at luaj.a.h.c(src:299)
    at luaj.a.h.a(src:1495)
    at luaj.a.h.i(src:1567)
    at luaj.a.h.j(src:1628)
    at luaj.a.h.b(src:1741)
    at luaj.a.h.b(src:1750)
    at luaj.a.h.k(src:1759)
    at luaj.a.h.g(src:1462)
    at luaj.a.h.a(src:1479)
    at luaj.a.h.i(src:1574)
    at luaj.a.h.j(src:1628)
    at luaj.a.h.b(src:1741)
    at luaj.a.h.k(src:1759)
    at luaj.a.h.g(src:1459)
    at luaj.a.h.a(src:1854)
    at luaj.a.h.x(src:2176)
    at luaj.a.h.z(src:2273)
    at luaj.a.h.A(src:2290)
    at luaj.a.h.a(src:1449)
    at luaj.a.h.N(src:2163)
    at luaj.a.h.z(src:2246)
    at luaj.a.h.A(src:2290)
    at luaj.a.h.a(src:2306)
    at luaj.a.u.a(src:121)
    at luaj.a.t.a(src:99)
    at luaj.Globals.a(src:364)
    at luaj.Globals.a(src:352)
    at luaj.Globals.a(src:267)
    at luaj.Globals.c_(src:249)
    ... 2 more [B]
Сам код lua:
Lua:
[/B]
gg.alert("Need arm-v7 (32bit) game version.\nDownload it from apkmirror.\nUse GameGuardian 95.5 for fast script execution.\nBy @nikki", "START☄️")
on = "🍏ON"
off = "🍎OFF"
fn1 = on
function main()
menu = gg.choice({
fn1.." AutoWin",
"Exit"}, nil, "script 3.3 | game 1.25.5" | Autor: NIKKI)
if menu == 1 then
if fn1 == off then
fn1 = on
else
fn1 = off
end
fn2()
elseif menu == 2 then
print("By @NIKKI \nhttps://t.me/fates_end\n🐈")
os.exit()
end
end
function fn2()
if fn1 == off then
fn3()
gg.toast("AutoWin ON🌄️", true)
else
fn4()
gg.toast("AutoWin OFF🌅", true)
end
end
function fn3()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("10h;80h;E5h;1Eh;FFh;2Fh;E1h;80h;00h;D0h;E5h;1Eh;FFh;2Fh;E1h;80h;10h;C0h::18",gg.TYPE_BYTE, false,gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("10h;80h;E5h;1Eh;FFh;2Fh;E1h;01h;00h;A0h;E3h;1Eh;FFh;2Fh;E1h;88h;10h;C0h",gg.TYPE_BYTE)
gg.clearResults()
end
function fn4()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("10h;80h;E5h;1Eh;FFh;2Fh;E1h;01h;00h;A0h;E3h;1Eh;FFh;2Fh;E1h;88h;10h;C0h::18",gg.TYPE_BYTE, false,gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("10h;80h;E5h;1Eh;FFh;2Fh;E1h;80h;00h;D0h;E5h;1Eh;FFh;2Fh;E1h;80h;10h;C0h",gg.TYPE_BYTE)
gg.clearResults()
end
while true do
if gg.isVisible() then
gg.setVisible(false)
main()
end
end
[B]
 

Вложения

  • qgIxqfF5_zE.jpg
    qgIxqfF5_zE.jpg
    244.8 KB · Просмотры: 56
  • sf3_1_25_7_AutoWin_jska_bin.lua
    1.3 KB · Просмотры: 4
Последнее редактирование:
  • Bug
Реакции: ShitKatsan

Sanchez.

Известный
704
190
Lua:
require 'lib.moonloader'

local effil = require 'effil'

local nicknames = {}

function main()
    while not isSampAvailable() do wait(0) end
    
        --[[_, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        nick = sampGetPlayerNickname(id)--]]
        
        asyncHttpRequest('GET', 'https://pastebin.com/raw/zAHhAkbs', nil,
        function(response)
            table.insert(nicknames, response.text)
        end,
        function(err)
            print(err)
        end)

        for k,v in pairs(nicknames) do
            if v ~= select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)) then
                thisScript():unload()
            end
        end

    while true do
        wait(0)
        
    end
end

function asyncHttpRequest(method, url, args, resolve, reject)
    local request_thread = effil.thread(function (method, url, args)
       local requests = require 'requests'
       local result, response = pcall(requests.request, method, url, args)
       if result then
          response.json, response.xml = nil, nil
          return true, response
       else
          return false, response
       end
    end)(method, url, args)
    -- Если запрос без функций обработки ответа и ошибок.
    if not resolve then resolve = function() end end
    if not reject then reject = function() end end
    -- Проверка выполнения потока
    lua_thread.create(function()
       local runner = request_thread
       while true do
          local status, err = runner:status()
          if not err then
             if status == 'completed' then
                local result, response = runner:get()
                if result then
                   resolve(response)
                else
                   reject(response)
                end
                return
             elseif status == 'canceled' then
                return reject(status)
             end
          else
             return reject(err)
          end
          wait(0)
       end
    end)
 end

Почему у меня не работает? Ввожу абсолютно другой ник, которого нету в pastebin, но скрипт не выгружается. (сори за код, первый раз в effil)
Не работает скрипт выдает ошибку. Помогите пожалуйста, в чём ошибка то?
Lua:
[/B]
Скрипт завершен:
Ошибка скрипта: luaj.o: load /storage/emulated/0/Download/sf3_1_25_7_AutoWin_jska_bin.lua: luaj.o: /storage/emulated/0/Download/sf3_1_25_7_AutoWin_jska_bin.lua:8
`"Exit"}, nil, "script 3.3 | game 1.25.5" | Autor: NIKKI)`
function arguments expected near )
    at luaj.LuaValue.a(src:997)
    at luaj.Globals.c_(src:255)
    at android.ext.Script.d(src:5992)
    at android.ext.Script$ScriptThread.run(src:5785)
Caused by: luaj.o: /storage/emulated/0/Download/sf3_1_25_7_AutoWin_jska_bin.lua:8
`"Exit"}, nil, "script 3.3 | game 1.25.5" | Autor: NIKKI)`
function arguments expected near )
    at luaj.a.h.a(src:295)
    at luaj.a.h.c(src:299)
    at luaj.a.h.a(src:1495)
    at luaj.a.h.i(src:1567)
    at luaj.a.h.j(src:1628)
    at luaj.a.h.b(src:1741)
    at luaj.a.h.b(src:1750)
    at luaj.a.h.k(src:1759)
    at luaj.a.h.g(src:1462)
    at luaj.a.h.a(src:1479)
    at luaj.a.h.i(src:1574)
    at luaj.a.h.j(src:1628)
    at luaj.a.h.b(src:1741)
    at luaj.a.h.k(src:1759)
    at luaj.a.h.g(src:1459)
    at luaj.a.h.a(src:1854)
    at luaj.a.h.x(src:2176)
    at luaj.a.h.z(src:2273)
    at luaj.a.h.A(src:2290)
    at luaj.a.h.a(src:1449)
    at luaj.a.h.N(src:2163)
    at luaj.a.h.z(src:2246)
    at luaj.a.h.A(src:2290)
    at luaj.a.h.a(src:2306)
    at luaj.a.u.a(src:121)
    at luaj.a.t.a(src:99)
    at luaj.Globals.a(src:364)
    at luaj.Globals.a(src:352)
    at luaj.Globals.a(src:267)
    at luaj.Globals.c_(src:249)
    ... 2 more [B]
Щас бы код кидать картинкой...
 
Последнее редактирование:

Alexandr199921

Новичок
3
0
Lua:
require 'lib.moonloader'

local effil = require 'effil'

local nicknames = {}

function main()
    while not isSampAvailable() do wait(0) end
  
        --[[_, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        nick = sampGetPlayerNickname(id)--]]
      
        asyncHttpRequest('GET', 'https://pastebin.com/raw/zAHhAkbs', nil,
        function(response)
            table.insert(nicknames, response.text)
        end,
        function(err)
            print(err)
        end)

        for k,v in pairs(nicknames) do
            if v ~= select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)) then
                thisScript():unload()
            end
        end

    while true do
        wait(0)
      
    end
end

function asyncHttpRequest(method, url, args, resolve, reject)
    local request_thread = effil.thread(function (method, url, args)
       local requests = require 'requests'
       local result, response = pcall(requests.request, method, url, args)
       if result then
          response.json, response.xml = nil, nil
          return true, response
       else
          return false, response
       end
    end)(method, url, args)
    -- Если запрос без функций обработки ответа и ошибок.
    if not resolve then resolve = function() end end
    if not reject then reject = function() end end
    -- Проверка выполнения потока
    lua_thread.create(function()
       local runner = request_thread
       while true do
          local status, err = runner:status()
          if not err then
             if status == 'completed' then
                local result, response = runner:get()
                if result then
                   resolve(response)
                else
                   reject(response)
                end
                return
             elseif status == 'canceled' then
                return reject(status)
             end
          else
             return reject(err)
          end
          wait(0)
       end
    end)
end

Почему у меня не работает? Ввожу абсолютно другой ник, которого нету в pastebin, но скрипт не выгружается. (сори за код, первый раз в effil)

Щас бы код кидать картинкой...
Сам код lua:
Lua:
[/B]
gg.alert("Need arm-v7 (32bit) game version.\nDownload it from apkmirror.\nUse GameGuardian 95.5 for fast script execution.\nBy @nikki", "START☄️")
on = "🍏ON"
off = "🍎OFF"
fn1 = on
function main()
menu = gg.choice({
fn1.." AutoWin",
"Exit"}, nil, "script 3.3 | game 1.25.5" | Autor: NIKKI)
if menu == 1 then
if fn1 == off then
fn1 = on
else
fn1 = off
end
fn2()
elseif menu == 2 then
print("By @NIKKI \nhttps://t.me/fates_end\n🐈")
os.exit()
end
end
function fn2()
if fn1 == off then
fn3()
gg.toast("AutoWin ON🌄️", true)
else
fn4()
gg.toast("AutoWin OFF🌅", true)
end
end
function fn3()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("10h;80h;E5h;1Eh;FFh;2Fh;E1h;80h;00h;D0h;E5h;1Eh;FFh;2Fh;E1h;80h;10h;C0h::18",gg.TYPE_BYTE, false,gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("10h;80h;E5h;1Eh;FFh;2Fh;E1h;01h;00h;A0h;E3h;1Eh;FFh;2Fh;E1h;88h;10h;C0h",gg.TYPE_BYTE)
gg.clearResults()
end
function fn4()
gg.clearResults()
gg.setRanges(gg.REGION_CODE_APP)
gg.searchNumber("10h;80h;E5h;1Eh;FFh;2Fh;E1h;01h;00h;A0h;E3h;1Eh;FFh;2Fh;E1h;88h;10h;C0h::18",gg.TYPE_BYTE, false,gg.SIGN_EQUAL, 0, -1)
gg.getResults(99)
gg.editAll("10h;80h;E5h;1Eh;FFh;2Fh;E1h;80h;00h;D0h;E5h;1Eh;FFh;2Fh;E1h;80h;10h;C0h",gg.TYPE_BYTE)
gg.clearResults()
end
while true do
if gg.isVisible() then
gg.setVisible(false)
main()
end
end
[B]
 

Вложения

  • sf3_1_25_7_AutoWin_jska_bin.lua
    1.3 KB · Просмотры: 4

Мира

Известный
456
9
вместо ранга выводится весь текст диалога
Lua:
if text:find('{ffffff}Должность: {DC143C}(.+) %((.+)%)') then
    post, rank = text:match('{ffffff}Должность: {DC143C}(.+) %((.+)%)')
    --sampSendDialogResponse(dialogId, 1, -1, _)
    sampAddChatMessage(rank, -1)
    --return false
end
 

CaJlaT

07.11.2024 14:55
Модератор
2,854
2,729
вместо ранга выводится весь текст диалога
Lua:
if text:find('{ffffff}Должность: {DC143C}(.+) %((.+)%)') then
    post, rank = text:match('{ffffff}Должность: {DC143C}(.+) %((.+)%)')
    --sampSendDialogResponse(dialogId, 1, -1, _)
    sampAddChatMessage(rank, -1)
    --return false
end
Почитай, там есть решение твоей проблемы, да и просто полезно будет почитать
 
  • Грустно
Реакции: Мира

legendabrn

Известный
Проверенный
121
172
Lua:
function SetAngle(x, y)
    local posX, posY, posZ = getCharCoordinates(PLAYER_PED)
    x1 = x - posX
    y1 = y - posY
    vec2 = getHeadingFromVector2d(x1, y1)
    shit = math.rad(vec2)
    shit = shit + 4.7
    setCameraPositionUnfixed(-0.3, shit)
end


function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        for k, v in ipairs(getAllObjects()) do
            if getObjectModel(v) == 1517 then
                result, ox, oy, oz = getObjectCoordinates(v)
                if result then
                    roX, roY = convert3DCoordsToScreen(ox, oy, oz)
                    SetAngle(ox, oy)
                    break;
                end
            end
        end
    end
end
почему прицел ставится не на объект, а левее и ниже?
 

Sanchez.

Известный
704
190
Lua:
require 'lib.moonloader'

local effil = require 'effil'

local nicknames = {}

function main()
    while not isSampAvailable() do wait(0) end
   
        --[[_, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        nick = sampGetPlayerNickname(id)--]]
       
        asyncHttpRequest('GET', 'https://pastebin.com/raw/zAHhAkbs', nil,
        function(response)
            table.insert(nicknames, response.text)
        end,
        function(err)
            print(err)
        end)

        for k,v in pairs(nicknames) do
            if v ~= select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)) then
                thisScript():unload()
            end
        end

    while true do
        wait(0)
       
    end
end

function asyncHttpRequest(method, url, args, resolve, reject)
    local request_thread = effil.thread(function (method, url, args)
       local requests = require 'requests'
       local result, response = pcall(requests.request, method, url, args)
       if result then
          response.json, response.xml = nil, nil
          return true, response
       else
          return false, response
       end
    end)(method, url, args)
    -- Если запрос без функций обработки ответа и ошибок.
    if not resolve then resolve = function() end end
    if not reject then reject = function() end end
    -- Проверка выполнения потока
    lua_thread.create(function()
       local runner = request_thread
       while true do
          local status, err = runner:status()
          if not err then
             if status == 'completed' then
                local result, response = runner:get()
                if result then
                   resolve(response)
                else
                   reject(response)
                end
                return
             elseif status == 'canceled' then
                return reject(status)
             end
          else
             return reject(err)
          end
          wait(0)
       end
    end)
end

Почему у меня не работает? Ввожу абсолютно другой ник, которого нету в pastebin, но скрипт не выгружается. (сори за код, первый раз в effil)

Щас бы код кидать картинкой...
actual