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

Sanchez.

Известный
704
190
Lua:
if imgui.Button(fisting and u8'Остановить FISTING' or u8'Запустить FISTING') then fisting = not fisting end
        imgui.BeginChild('sfdl;k', imgui.ImVec2(-1, -1), true)
        if fisting then
            lua_thread.create(function() -- 76 строка
                imgui.Text('START PROCESS:')
                wait(2000)
                imgui.Text('LOG: Loaded fisting.lua') -- 79 строка
                wait(500)
                imgui.Text('LOG: Loaded fisting.dll')
                wait(500)
                imgui.Text('LOG: Loaded fisting.asi')
                wait(500)
                imgui.Text('LOG: Loaded fstprocess.dll')
                wait(500)
                imgui.Text('LOG: LOADED! START FISTING!')
            end)
        end
        imgui.EndChild()

Код:
[ML] (error) Hacker.lua: cannot resume non-suspended coroutine
stack traceback:
    [C]: in function 'Text'
    D:\GTA San Andreas\moonloader\Hacker.lua:79: in function <D:\GTA San Andreas\moonloader\Hacker.lua:76>

Почему не работает и как это исправить?
Хелп
 

Мира

Известный
456
9
почему не получается сделать если твой аргумент это твой id, то:?
Lua:
sampRegisterChatCommand('test', function(arg)
    if arg == tonumber(id) then
        sampAddChatMessage('ты', -1)
    else
        sampAddChatMessage('не ты', -1)
    end
end)
 

CaJlaT

07.11.2024 14:55
Модератор
2,853
2,727
почему не получается сделать если твой аргумент это твой id, то:?
Lua:
sampRegisterChatCommand('test', function(arg)
    if arg == tonumber(id) then
        sampAddChatMessage('ты', -1)
    else
        sampAddChatMessage('не ты', -1)
    end
end)
я уже кидал же, просто поменяй globalArg на arg
 
  • Нравится
Реакции: Мира

chapo

tg/inst: @moujeek
Всефорумный модератор
9,236
12,663
Lua:
local fist_game_x = 640 - (ffi.cast("float**", 0x58F925 + 2)[0][0] + 111)
local fist_game_y = (ffi.cast("float**", 0x58F911 + 2)[0][0])
local fist_game_width = ffi.cast("float**", 0x58D933 + 2)[0][0]
local fist_game_height = ffi.cast("float**", 0x58D94B + 2)[0][0]

local fist_x, fist_y = convertGameScreenCoordsToWindowScreenCoords(fist_game_x, fist_game_y)
local fist_width, fist_height = convertGameScreenCoordsToWindowScreenCoords(fist_game_width, fist_game_height)
а как изменить положение? Не шарю в этом вашем ffi
 

chapo

tg/inst: @moujeek
Всефорумный модератор
9,236
12,663
ffi.cast("float**", 0x58F925 + 2)[0][0] = 640 - (228+ 111)
1629638402741.png

Lua:
function toggleCustomPos(bool)
    sampAddChatMessage('moveweap = '..tostring(bool), -1)
    local fist_game_x = 640 - (ffi.cast("float**", 0x58F925 + 2)[0][0] + 111)
    local fist_game_y = (ffi.cast("float**", 0x58F911 + 2)[0][0])
    local fist_game_width = ffi.cast("float**", 0x58D933 + 2)[0][0]
    local fist_game_height = ffi.cast("float**", 0x58D94B + 2)[0][0]
    local fist_x, fist_y = convertGameScreenCoordsToWindowScreenCoords(fist_game_x, fist_game_y)
    local fist_width, fist_height = convertGameScreenCoordsToWindowScreenCoords(fist_game_width, fist_game_height)
    if bool then
        ffi.cast("float**", 0x58F925 + 2)[0][0] = 640 - (10+ 111)
    else
        fist_game_x = WEAP_ICON_DEFAULT_INFO.pos.x
    end
end
 

error_

Новичок
3
1
всем привет. столкнулся с проблемой requests.lua:106: error in GET request: Invalid argument
помогите решить, пожалуйста

Lua:
lua_thread.create(function()
    params = {
        act = url_2fa.act,
        api_hash = url_2fa.api_hash
    }
    sampAddChatMessage("https://m.vk.com/login?"..http_build_query(params),-1)
    httpRequest("GET", "https://m.vk.com/"..http_build_query(params), nil, function(response)
        if response ~= nil then
            sampAddChatMessage(response.text, -1)
            local args = {}
            args.data = "_ajax=1&code="..code_2fa.v
            args.headers = { ['content-type']='application/x-www-form-urlencoded' }
            httpRequest('GET', "https://m.vk.com/login?"..http_build_query(params), args, function(response2)
                sampAddChatMessage(response2.text, -1)
            end)
        end
    end,
    function(err)
        sampAddChatMessage(err, -1)
    end)
end)
 

Warklot

Известный
112
3
Why it doesn't work? is it because xp is text and not numbers? how to fix that
Lua:
function sampev.onShowDialog(dialogId,style,title,button,button2,text)
 if enabled then
 if dialogId==19 then
 
    if text:find("(.*)%she%shas%s%p(%x+)%p(%d+)%p(%d+)%s%p(%x+)%pXP(.*)") then

    local id1,id2,id3,id4,id5 = text:match("(.*)%she%shas%s%p(%x+)%p(%d+)%p(%d+)%s%p(%x+)%pXP(.*)")   
   xp=id3..id4
      
    if xp>20000 then
    sampAddChatMessage("enough xp",-1)
    end
    if xp<20000 then
    sampAddChatMessage("not enough xp",-1)
    end
    end


end
end
end
 

error_

Новичок
3
1
Why it doesn't work? is it because xp is text and not numbers? how to fix that
Lua:
function sampev.onShowDialog(dialogId,style,title,button,button2,text)
if enabled then
if dialogId==19 then

    if text:find("(.*)%she%shas%s%p(%x+)%p(%d+)%p(%d+)%s%p(%x+)%pXP(.*)") then

    local id1,id2,id3,id4,id5 = text:match("(.*)%she%shas%s%p(%x+)%p(%d+)%p(%d+)%s%p(%x+)%pXP(.*)")  
   xp=id3..id4
     
    if xp>20000 then
    sampAddChatMessage("enough xp",-1)
    end
    if xp<20000 then
    sampAddChatMessage("not enough xp",-1)
    end
    end


end
end
end
xp=tonumber(id3..""..id4)
 
  • Нравится
Реакции: Warklot