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

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 · Просмотры: 2

Мира

Участник
455
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

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

legendabrn

Известный
Проверенный
122
173
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
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)

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

Sanchez.

Известный
704
187
Ничего что ты сравниваешь ник с пастербина с ID игрока в игре (sampGetPlayerIdByCharHandle)
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)

        wait(1000)
        asyncHttpRequest('GET', 'https://pastebin.com/raw/zAHhAkbs', nil,
        function(response)
            if nick ~= response.text then
               thisScript():unload()
            end
        end,
        function(err)
            print(err)
        end)

        --[[for k,v in pairs(nicknames) do
            if v ~= nick 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
Я сделал вот так, скрипт конечно выгружается, но когда я ставлю ник который есть в пастебине, то скрипт все равно выгружается
 

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]
 

Вложения

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

Мира

Участник
455
9
можно как-то этот текст по середине отцентрировать?
1629468982841.png

использую
Lua:
imgui.NewInputText('##SearchBar', text_buffer, 300, u8'Введите ФИ', 2)

function imgui.NewInputText(lable, val, width, hint, hintpos)
    local hint = hint and hint or ''
    local hintpos = tonumber(hintpos) and tonumber(hintpos) or 1
    local cPos = imgui.GetCursorPos()
    imgui.PushItemWidth(width)
    local result = imgui.InputText(lable, val)
    if #val.v == 0 then
        local hintSize = imgui.CalcTextSize(hint)
        if hintpos == 2 then imgui.SameLine(cPos.x + (width - hintSize.x) / 2)
        elseif hintpos == 3 then imgui.SameLine(cPos.x + (width - hintSize.x - 5))
        else imgui.SameLine(cPos.x + 5) end
        imgui.TextColored(imgui.ImVec4(1.00, 1.00, 1.00, 0.40), tostring(hint))
    end
    imgui.PopItemWidth()
    return result
end
 

abnomegd

Активный
335
35
Хотел сделать чтобы при наводке на игрока и нажатие на какую либо клавишу показывалось паспорт или что то другое человеку напротив, но чтобы можно было изменять текущую клавишу на ту которую хотим мы, в имгуи окне.
GOVNOcode:
require "lib.moonloader"
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
local inicfg = require 'inicfg'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local directIni = "moonloader\\settings.ini"

local mainIni = inicfg.load(nil, directIni)

local mainIni = inicfg.load({
    hotkey = {
        bindClock = "[18,82]", -- alt + r
    }
}, directIni)

local rkeys = require 'rkeys'
imgui.HotKey = require('imgui_addons').HotKey

local tLastKeys = {} -- тут будут храниться предыдущие хоткеи при переактивации

local ActiveClockMenu = {
    v = decodeJson(mainIni.hotkey.bindClock)
}

main_window_state = imgui.ImBool(false)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand("imgui", cmd_imgui)
    imgui.Process = false
    bindClock = rkeys.registerHotKey(ActiveClockMenu.v, true, clockFunc) -- создаем объект хоткея и регистрируем коллбэк функцию

    while true do
        wait(0)

    end
  end

        if main_window_state.v == false then
            imgui.Process = false
        end
    local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE) -- получить хендл персонажа, в которого целится игрок
    if valid and doesCharExist(ped) then -- если цель есть и персонаж существует
      local result, id = sampGetPlayerIdByCharHandle(ped) -- получить samp-ид игрока по хендлу персонажа
      if result then -- проверить, прошло ли получение ида успешно
        -- здесь любые действия с полученным идом игрока
        if isKeyJustPressed(VK_G) then
          function clockFunc()
            sampSendChat("/pass "..tostring(playerid)) --хз если так правильно
        end
    end  

function cmd_imgui(arg)
  main_window_state.v = not main_window_state.v
  imgui.Process = main_window_state.v
end

function clockFunc()
    sampSendChat("/c 60")
end

if main_window_state.v then
  local sw, sh = getScreenResolution()
      imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
      imgui.SetNextWindowSize(imgui.ImVec2(300, 200), imgui.Cond.FirstUseEver)
  imgui.Begin(u8'HZzzz', main_window_state)
  imgui.Text(u8"Посмотреть время")
  imgui.SameLine()
  if imgui.HotKey("##1", ActiveClockMenu, tLastKeys, 100) then
    rkeys.changeHotKey(bindClock, ActiveClockMenu.v)
    sampAddChatMessage("Успешно! Старое значение: {F4A460}" .. table.concat(rkeys.getKeysName(tLastKeys.v), " + ") .. "{ffffff} | Новое: {F4A460}" .. table.concat(rkeys.getKeysName(ActiveClockMenu.v), " + "), -1)
    sampAddChatMessage("Строчное значение: {F4A460}" .. encodeJson(ActiveClockMenu.v), -1)

    mainIni.hotkey.bindClock = encodeJson(ActiveClockMenu.v)
    inicfg.save(mainIni, directIni)
  end
      imgui.End()
  end
end
безуспешный up
 

Мира

Участник
455
9
как сохранить текст в Input`е?
Lua:
local mainIni = inicfg.load({
    settings =
    {
        user = ''
    }
}, 'Random.ini')
if not doesFileExist("moonloader/config/Random.ini") then inicfg.save(mainIni, "Random.ini") end

--main


--imgui

imgui.NewInputText('##SearchBar', user, 300, u8'Введите ФИ', 2)
mainIni.settings.user = user.v
inicfg.save(mainIni, "Random.ini")
 

#SameLine

Активный
424
37
Как сделать вот такую кнопку? которая в этом скрипте включает / отключает бинд, просто другого скрипта не нашёл где такая кнопка есть
 

Вложения

  • Модификации.png
    Модификации.png
    91.4 KB · Просмотры: 28

kin4stat

mq-team · kin4@naebalovo.team
Всефорумный модератор
2,736
4,742
Как сделать вот такую кнопку? которая в этом скрипте включает / отключает бинд, просто другого скрипта не нашёл где такая кнопка есть

Lua:
local imadd = require 'imgui_addons'
imadd.ToggleButton("##active", ImBool)
 

Мира

Участник
455
9
как цвет поменять? тут есть что-то (0.11, 0.11, 0.11, 1.00)), но это разве цвет? цвет синий стоит по умолчанию
Lua:
function imgui.Hint(text, delay, action)
    if imgui.IsItemHovered() then
        if go_hint == nil then go_hint = os.clock() + (delay and delay or 0.0) end
        local alpha = (os.clock() - go_hint) * 5
        if os.clock() >= go_hint then
            imgui.PushStyleVar(imgui.StyleVar.WindowPadding, imgui.ImVec2(10, 10))
            imgui.PushStyleVar(imgui.StyleVar.Alpha, (alpha <= 1.0 and alpha or 1.0))
                imgui.PushStyleColor(imgui.Col.PopupBg, imgui.ImVec4(0.11, 0.11, 0.11, 1.00))
                    imgui.BeginTooltip()
                    imgui.PushTextWrapPos(450)
                    imgui.TextColored(imgui.GetStyle().Colors[imgui.Col.ButtonHovered], u8'Подсказка:')
                    imgui.TextUnformatted(text)
                    if action ~= nil then
                        imgui.TextColored(imgui.GetStyle().Colors[imgui.Col.TextDisabled], '\n '..action)
                    end
                    if not imgui.IsItemVisible() and imgui.GetStyle().Alpha == 1.0 then go_hint = nil end
                    imgui.PopTextWrapPos()
                    imgui.EndTooltip()
                imgui.PopStyleColor()
            imgui.PopStyleVar(2)
        end
    end
end
 

BARRY BRADLEY

Известный
711
176
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)

        wait(1000)
        asyncHttpRequest('GET', 'https://pastebin.com/raw/zAHhAkbs', nil,
        function(response)
            if nick ~= response.text then
               thisScript():unload()
            end
        end,
        function(err)
            print(err)
        end)

        --[[for k,v in pairs(nicknames) do
            if v ~= nick 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
Я сделал вот так, скрипт конечно выгружается, но когда я ставлю ник который есть в пастебине, то скрипт все равно выгружается
У тебя в response.text все ники, это не таблица.