Полезные сниппеты и функции

meowprd

Тот самый Котовский
Проверенный
1,280
712
можно объединить в одну проверку

аналогично
Знаю, но мне очень сложно читать такие большие проверки, поэтому принял решение оставить так.
Если кому-то такое не нравится - может сам исправить под себя, ведь так?
 

Vintik

Мечтатель
Проверенный
1,466
915
Знаю, но мне очень сложно читать такие большие проверки, поэтому принял решение оставить так.
Если кому-то такое не нравится - может сам исправить под себя, ведь так?
Lua:
if
(angle > -0.1 and angle < 0.03) or
(angle < -5.7 and angle > -5.93) or
(angle < -6.0 and angle > -6.4)
then
setCameraPositionUnfixed(-0.3, GetAngleBeetweenTwoPoints(x,y))
end
Вроде должно работать
 
  • Нравится
Реакции: meowprd

Cosmo

Известный
Друг
646
2,597
Описание:
Получает время бездействия пользователя за ПК (Устройств ввода) в секундах:
Lua:
local ffi = require 'ffi'
ffi.cdef[[
    typedef unsigned long DWORD;
    typedef unsigned int UINT;

    typedef struct tagLASTINPUTINFO {
        UINT  cbSize;
        DWORD dwTime;
    } LASTINPUTINFO, *PLASTINPUTINFO;

    bool GetLastInputInfo(
        PLASTINPUTINFO plii
    );

    DWORD GetTickCount();
]]

function lastActivity()
    local info = ffi.new("LASTINPUTINFO[1]")
    info[0].cbSize = 8
    ffi.C.GetLastInputInfo(info)
    return (ffi.C.GetTickCount() - info[0].dwTime) / 1000
end

Пример использования:
Lua:
function main()
    while true do
        local sec = lastActivity()
        print('Вы бездействуете уже: ' .. sec .. ' секунд!')
        wait(0)
    end
end

-- output: Вы бездействуете уже: 9.234 секунд!
 

_raz0r

t.me/sssecretway | ТГК: t.me/razor_code
Модератор
1,889
3,050
Описание: Изменяет цвет HP бара у игроков над головами
Lua:
function setHealthColor(hpHigh, hpLow)
     local samp = getModuleHandle("samp.dll")
     memory.setuint32(samp + 0x68B0C, hpHigh, true) -- полная полоска хп
     memory.setuint32(samp + 0x68B33, hpLow, true) -- задний фон
end
Пример использования:
Lua:
setHealthColor(0xFFFFFFFF, 0xFF000000)
1617645513747.png
 

invilso.

Известный
249
89
Описание: sampSetChatInputText, но вводящий текст последовательно и с указанной задержкой. Кто-то просил скрипт с таким в разделе "Помощь", я подумал почему нет.
Код:
Дёшево, но сердито:
function sampSetChatInputTextWithDelay(text, delay)
    local array = {}
    for i in text:gmatch('[^%z]') do
        wait(delay)
        table.insert(array, i)
        sampSetChatInputText(table.concat(array))
    end
end

Пример использования:
Lua:
local vk = require 'vkeys'

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

    while true do wait(0)
        if isKeyJustPressed(vk.VK_P) then
            sampSetChatInputEnabled(true)
            sampSetChatInputTextWithDelay('Текст вводится последовательно с указанной задержкой.', 5)
        end
    end
end
Добавим реалистичности.
ФУНКЦИЯ:
function sampSetChatInputTextWithRandomDelay(text, delay1, delay2)
    for i = 1, text:len() do
        math.randomseed(os.clock())
        wait(math.random(delay1, delay2))
        sampSetChatInputText(text:sub(1, i))
    end
end
ПРИМЕР:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while true do
        wait(0)
        if isKeyJustPressed(0x39) then --триггер на нажатие клавиши 9
            sampSetChatInputTextWithRandomDelay('Привет, этот текст выводится с рандомной задержкой от 50 до 200мс', 50, 200)
        end
    end
end

function sampSetChatInputTextWithRandomDelay(text, delay1, delay2)
    for i = 1, text:len() do
        math.randomseed(os.clock())
        wait(math.random(delay1, delay2))
        sampSetChatInputText(text:sub(1, i))
    end
end
 
  • Нравится
Реакции: ChromiusJ и BARRY BRADLEY

xdswd

Известный
365
251
Описание: Проверяет, целится ли игрок с пассажирского места
Lua:
function isCharTargettingAsPassenger()
    return memory.getint8(0xB6FC70) == 1
end
Пример использования:
Lua:
if isCharTargettingAsPassenger() then
    setCharAmmo(1, getCurrentCharWeapon(1), 500) -- выдаём патроны при прицеливании
end
 
Последнее редактирование:
  • Нравится
  • Вау
Реакции: Mintha, _raz0r и THERION

ufdhbi

Известный
Проверенный
1,455
861
Описание: Проверяет, целится ли игрок с пассажирского места
Lua:
function isCharTargettingAsPassenger()
    if memory.getint8(getModuleHandle("gta_sa.exe") + 0x76FC70) == 1 then
        return true
    end
    return false
end
Пример использования:
Lua:
if isCharTargettingAsPassenger() then
    setCharAmmo(1, getCurrentCharWeapon(1), 500) -- выдаём патроны при прицеливании
end
Lua:
function isCharTargettingAsPassenger()
    return memory.getint8(getModuleHandle("gta_sa.exe") + 0x76FC70) == 1
end
 
  • Нравится
Реакции: xdswd

xdswd

Известный
365
251
Описание: Изменяет яркость игры
Lua:
function setBrightness(int)
    memory.setint32(0x00BA6784, int)
end
Пример использования:
Lua:
sampRegisteChatCommand("setbright", function(int)
    setBrightness(int)
end)
 

moreveal

Известный
Проверенный
850
525
Описание: Отправка файлов на сервер в формате multipart/form-data
Делал на примере передачи файла в ВК, поэтому, возможно, потребуется немного изменить код. Тут лишь принцип.
Lua:
function uploadFile(uploadUrl, filePath, fieldName)
    local socket = require 'luasocket.socket'
    local copas = require 'copas'
    local http = require 'copas.http'
    local function rand_str(len)
        len = tonumber(len) or 1
        math.randomseed(os.time())
        local function rand_char()
            return math.random() > 0.5
                and string.char(math.random(65, 90))
                or string.char(math.random(97, 122))
        end
        local function rand_num()
            return string.char(math.random(48, 57))
        end
    
        local str = ""
        for i = 1, len do
            str = str .. (math.random() > 0.5 and rand_char() or rand_num())
        end
        return str
    end

    local file = io.open(filePath, 'rb')
    local bin_file = file:read('*a')
    file:close()
    local boundary = rand_str(16)
    local data = '--'..boundary..'\r\nContent-Disposition: form-data; name="'..fieldName..'"; filename="'..filePath:match([[\?/?(.+%..+)]])..'"\r\n\r\n'..bin_file..'\r\n--'..boundary..'--'
    local respbody = {}
    local body, code, headers, status = http.request {
        url = uploadUrl,
        method = "POST",
        headers = {
            ['content-type'] = 'multipart/form-data; boundary='..boundary,
            ['content-length'] = string.len(data)
        },
        source = ltn12.source.string(data),
        sink = ltn12.sink.table(respbody)
    }
    local result1, result2, result3, result4 = respbody[1], code, headers, status -- тут лютый пиздец, но иначе возвращаются непонятные данные)0)
    return result1, result2, result3, result4
end
Пример использования:
Lua:
local response, code, headers, status = uploadFile(uploadUrl, filePath, 'photo')
print(response, code, headers, status)
--[[
    uploadUrl - адрес, куда нужно загрузить изображение
    filePath - локальный путь к файлу
    'photo' - название поля в POST-запросе, где должен быть файл
]]
 
Последнее редактирование:

leekyrave

Известный
419
223
Разбивает HEX на r,g,b,a

Lua:
function hextoargb(hex)
    local hex = hex:gsub("#","")
    r = tonumber("0x"..hex:sub(1,2))
    g = tonumber("0x"..hex:sub(3,4))
    b = tonumber("0x"..hex:sub(5,6))
    a = tonumber("0x"..hex:sub(7,8))
   
    if a == nil then a = 255 end
    print('HEX = '.. hex .. ' | R = '.. r .. ' | G =' .. g .. ' | B = '.. b .. ' | A =' .. a)
    return a,r,g,b
end

Из R,G,B or R,G,B,A формирует hex цвет в формате FFFFFFFF
Lua:
--         print(rgbtohex({r,g,b,a})) or print(rgbtohex({r,g,b}))

function rgbtohex(rgb)

    local hexadecimal = ''



    for key = 1, #rgb do

        local value = rgb[key]

        local hex = ''



        while(value > 0)do

            local index = math.fmod(value, 16) + 1

            value = math.floor(value / 16)

            hex = string.sub('0123456789ABCDEF', index, index) .. hex          

        end



        if(string.len(hex) == 0)then

            hex = '00'

        elseif(string.len(hex) == 1)then

            hex = '0' .. hex

        end

        hexadecimal = hexadecimal .. hex

    end

    return hexadecimal

end

Из хекса в р,г,б,а
Lua:
function hextorgba(hex)
    a,r,g,b = hextoargb(hex)
    return r,g,b,a
end

Есть еще похожий код на гитхабе - колорист либа
 
  • Нравится
Реакции: DGarson

imring

Ride the Lightning
Всефорумный модератор
2,355
2,516
Разбивает HEX на r,g,b,a

Lua:
function hextoargb(hex)
    local hex = hex:gsub("#","")
    r = tonumber("0x"..hex:sub(1,2))
    g = tonumber("0x"..hex:sub(3,4))
    b = tonumber("0x"..hex:sub(5,6))
    a = tonumber("0x"..hex:sub(7,8))
  
    if a == nil then a = 255 end
    print('HEX = '.. hex .. ' | R = '.. r .. ' | G =' .. g .. ' | B = '.. b .. ' | A =' .. a)
    return a,r,g,b
end

Из R,G,B or R,G,B,A формирует hex цвет в формате FFFFFFFF
Lua:
--         print(rgbtohex({r,g,b,a})) or print(rgbtohex({r,g,b}))

function rgbtohex(rgb)

    local hexadecimal = ''



    for key = 1, #rgb do

        local value = rgb[key]

        local hex = ''



        while(value > 0)do

            local index = math.fmod(value, 16) + 1

            value = math.floor(value / 16)

            hex = string.sub('0123456789ABCDEF', index, index) .. hex         

        end



        if(string.len(hex) == 0)then

            hex = '00'

        elseif(string.len(hex) == 1)then

            hex = '0' .. hex

        end

        hexadecimal = hexadecimal .. hex

    end

    return hexadecimal

end

Из хекса в р,г,б,а
Lua:
function hextorgba(hex)
    a,r,g,b = hextoargb(hex)
    return r,g,b,a
end

Есть еще похожий код на гитхабе - колорист либа
Lua:
-- hextoargb
local string_color = 'ffffffff'
local a, r, g, b = explode_argb(tonumber(string_color, 16))

-- rgbtohex
print(bit.tohex(0xffffffff))
-- или
print(('0x%x'):format(0xffffffff))
 

leekyrave

Известный
419
223
Lua:
-- hextoargb
local string_color = 'ffffffff'
local a, r, g, b = explode_argb(tonumber(string_color, 16))

-- rgbtohex
print(bit.tohex(0xffffffff))
-- или
print(('0x%x'):format(0xffffffff))
на производительность как-то влияет чи не?