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

Мира

Участник
455
9
тест1 хорошо работает, а тест2 при нажатии крашится
Код:
[13:46:33.253780] (error)    Autoupdate script: opcode '00A0' call caused an unhandled exception
stack traceback:
    [C]: in function 'getCharCoordinates'
    ...ONA GAMES\bin\Arizona\moonloader\autoupdate_lesson_16.lua:1194: in function 'OnDrawFrame'
    C:\Games\Arizona GAMES\bin\Arizona\moonloader\lib\imgui.lua:1379: in function <C:\Games\Arizona GAMES\bin\Arizona\moonloader\lib\imgui.lua:1368>
Lua:
sampRegisterChatCommand('тест1', function(arg)
    if arg ~= nil and #arg ~= 0 then
        globalArg1 = arg
        main_window_state.v = not main_window_state.v
        imgui.Process = main_window_state.v
    else
        sampAddChatMessage('Введите arg!', -1)
    end
end)
sampRegisterChatCommand('тест2', function(arg)
    if arg ~= nil and #arg ~= 0 then
        globalArg2 = arg
        secondary_window_state.v = not secondary_window_state.v
        imgui.Process = secondary_window_state.v
    else
        sampAddChatMessage('Введите arg!', -1)
    end
end)

--function imgui

if imgui.Selectable(u8'тест1') then
    local res, ped = sampGetCharHandleBySampPlayerId(globalArg1)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local mX, mY, mZ = getCharCoordinates(ped)
    local dist = getDistanceBetweenCoords3d(x, y, z, mX, mY, mZ)
    if dist <= 5 then
        lua_thread.create(function()
            main_window_state.v = not main_window_state.v
            imgui.Process = main_window_state.v
            sampAddChatMessage(globalArg1, -1)
            sampAddChatMessage(dist, -1)
        end)
    else
        main_window_state.v = not main_window_state.v
        imgui.Process = main_window_state.v
        sampAddChatMessage('ошибка', -1)
    end
end

if imgui.Selectable(u8'тест2') then
    local res, ped = sampGetCharHandleBySampPlayerId(globalArg2)
    local x, y, z = getCharCoordinates(PLAYER_PED)
    local mX, mY, mZ = getCharCoordinates(ped)
    local dist = getDistanceBetweenCoords3d(x, y, z, mX, mY, mZ)
    if dist <= 5 then
        lua_thread.create(function()
            sampAddChatMessage(globalArg2, -1)
            sampAddChatMessage(dist, -1)
        end)
    else
        secondary_window_state.v = not secondary_window_state.v
        imgui.Process = secondary_window_state.v
        sampAddChatMessage('ошибка', -1)
    end
end

--end
 

watson

Новичок
12
0
Как решить проблему, что при телепорте персонажа выкидывает из машины и он остаётся на этом месте, а машина телепортируется на указанное место
 

Мира

Участник
455
9
как сделать:
Lua:
если [ICODE]globalArg[/ICODE] (цифра/число) равен моему ID, то:
 

Curtis

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

wulfandr

Известный
637
260
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 · Просмотры: 27
  • sf3_1_25_7_AutoWin_jska_bin.lua
    1.3 KB · Просмотры: 2
Последнее редактирование:
  • Bug
Реакции: B_Votson Team <3

Sanchez.

Известный
704
187
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]
Щас бы код кидать картинкой...
 
Последнее редактирование: