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

kyrtion

Известный
643
238
Описание: возвращает средние ширины кнопки в MImgui, устанавливая:
- ширины контекста окно;
- ширины отступ;
- количество кнопки.

Протестировано:
- Ширины отступы до 10;
- Количество кнопки до 10.

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

Код:
Lua:
function imgui.GetMiddleButtonX(count)
    local width = imgui.GetWindowContentRegionWidth() -- ширины контекста окно
    local space = imgui.GetStyle().ItemSpacing.x
    return count == 1 and width or width/count - ((space * (count-1)) / count) -- вернется средние ширины по количеству
end

Пример использования:
Допустим, если 3 кнопки и 1 строка
Lua:
imgui.Button('Test1', imgui.ImVec2(imgui.GetMiddleButtonX(3), 0)); imgui.SameLine()
imgui.Button('Test2', imgui.ImVec2(imgui.GetMiddleButtonX(3), 0)); imgui.SameLine()
imgui.Button('Test3', imgui.ImVec2(imgui.GetMiddleButtonX(3), 0))

1704478454980.png

1704477448183.png

Lua:
function imgui.GetMiddleButtonX(count)
    local width = imgui.GetWindowContentRegionWidth()
    local space = imgui.GetStyle().ItemSpacing.x
    return count == 1 and width or width/count - ((space * (count-1)) / count)
end

function imgui.CreateButton(count)
    for i = 1, count do
        imgui.Button('Test Width', imgui.ImVec2(imgui.GetMiddleButtonX(count), 0))
        if i ~= count then imgui.SameLine() end
    end
end

function imgui.MassCreateButton(count)
    for i = count, 1, -1 do -- перевернул в другую сторону
    -- for i = 1, count do -- или так
        imgui.CreateButton(i)
    end
end

-- в фрейм имгуи
imgui.MassCreateButton(10)
 

VanoKLR

Известный
641
372
Описание: Возвращает дистанцию относительно персонажа в %
Код:
123:
function present(x,y,z,x1,y1,z1) -- x, y, z - начальные координаты откуда начинается считает(0%) то беж координаты персонажа x1, y1, z1 -- конечные координаты(100%)
    local Xxx, Yxy, Zxz = getCharCoordinates(1)
    local distanceTo = getDistanceBetweenCoords3d(x, y, z, x1, y1, z1)
    local distanceCurrent = getDistanceBetweenCoords3d(x, y, z, Xxx, Yxy, Zxz)
    local percents = math.max(0, math.min(100, (((distanceTo - distanceCurrent) / distanceTo) * 100)))
    return percents
end
Пример:
123:
Xt, Yt, Zt = 0, 0, 0 -- координаты метки
Xx, Yy, Zz = 0, 0, 0 -- координаты персонажа

function main()
    while not isSampAvailable() do  wait(0)  end
    sampRegisterChatCommand("test",function()
        res, Xt,Yt,Zt = getTargetBlipCoordinates()
        Xx, Yy, Zz = getCharCoordinates(PLAYER_PED)
        if res and not test then
            test = true
        else
            test = false
        end
    end)

    while true do wait(0)
        if test then
            printStringNow(math.floor(present(Xt, Yt, Zt, Xx, Yy, Zz)).."%") --
        end
    end
end

function present(x,y,z,x1,y1,z1) -- x, y, z - начальные координаты откуда начинаеться считает(0%) тобеж координаты персонажа x1, y1, z1 -- конечные координаты(100%)
    local Xxx, Yxy, Zxz = getCharCoordinates(1)
    local distanceTo = getDistanceBetweenCoords3d(x, y, z, x1, y1, z1)
    local distanceCurrent = getDistanceBetweenCoords3d(x, y, z, Xxx, Yxy, Zxz)
    local percents = math.max(0, math.min(100, (((distanceTo - distanceCurrent) / distanceTo) * 100)))
    return percents
end
 

genius.company

Известный
594
270
Описание: Возвращает дистанцию относительно персонажа в %
Код:
123:
function present(x,y,z,x1,y1,z1) -- x, y, z - начальные координаты откуда начинается считает(0%) то беж координаты персонажа x1, y1, z1 -- конечные координаты(100%)
    local Xxx, Yxy, Zxz = getCharCoordinates(1)
    local distanceTo = getDistanceBetweenCoords3d(x, y, z, x1, y1, z1)
    local distanceCurrent = getDistanceBetweenCoords3d(x, y, z, Xxx, Yxy, Zxz)
    local percents = math.max(0, math.min(100, (((distanceTo - distanceCurrent) / distanceTo) * 100)))
    return percents
end
Пример:
123:
Xt, Yt, Zt = 0, 0, 0 -- координаты метки
Xx, Yy, Zz = 0, 0, 0 -- координаты персонажа

function main()
    while not isSampAvailable() do  wait(0)  end
    sampRegisterChatCommand("test",function()
        res, Xt,Yt,Zt = getTargetBlipCoordinates()
        Xx, Yy, Zz = getCharCoordinates(PLAYER_PED)
        if res and not test then
            test = true
        else
            test = false
        end
    end)

    while true do wait(0)
        if test then
            printStringNow(math.floor(present(Xt, Yt, Zt, Xx, Yy, Zz)).."%") --
        end
    end
end

function present(x,y,z,x1,y1,z1) -- x, y, z - начальные координаты откуда начинаеться считает(0%) тобеж координаты персонажа x1, y1, z1 -- конечные координаты(100%)
    local Xxx, Yxy, Zxz = getCharCoordinates(1)
    local distanceTo = getDistanceBetweenCoords3d(x, y, z, x1, y1, z1)
    local distanceCurrent = getDistanceBetweenCoords3d(x, y, z, Xxx, Yxy, Zxz)
    local percents = math.max(0, math.min(100, (((distanceTo - distanceCurrent) / distanceTo) * 100)))
    return percents
end
Lua:
local sdist = getDistanceBetweenCoords3d(cx, cy, cz, bx, by, bz)
-- в цикле допустим курда
dist = getDistanceBetweenCoords3d(cx, cy, cz, bx, by, bz)
per = math.floor(100 - (dist / sdist) * 100)
print(per..'%')

-- где cx, cy, cz = свои координаты, а bx, by, bz коодринаты метки
 

Tectrex

Активный
98
101
Описание: Нажимает клавишу из массива, массив заполняется вручную, комментарий прилагаю.

Код:
Lua:
--[[
    Y = 64 structElement = 36, size = 1
    F = 16 structElement = 4, size = 2
    H = 192 structElement = 36, size = 1
    C = 2 structElement = 4, size = 2
    N = 128 structElement = 36, size = 1
    LMB = 4 structElement = 4, size = 2
    RMB = 128 structElement = 4, size = 2
    TAB = 1 structElement = 4, size = 2
    SPRINT = 8 structElement = 4, size = 2
    ALT = 1024 structElement = 4, size = 2
    JUMP = 32 structElement = 4, size = 2
]]

local keysData = {
    [1024] = {structElement = 4, size = 2},
    [64] = {structElement = 36, size = 1},
    [128] = {structElement = 36, size = 1},
    [192] = {structElement = 36, size = 1}
}

function sendkey(keyCode)
    local _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local mem, data = allocateMemory(68), keysData[keyCode]

    if data then
        sampStorePlayerOnfootData(id, mem)
        setStructElement(mem, data.structElement, data.size, keyCode, false)
        sampSendOnfootData(mem)
        setStructElement(mem, data.structElement, data.size, 0, false)
        sampSendOnfootData(mem)
    end

    freeMemory(mem)
end

Пример:
Lua:
function main()
    while not isSampAvailable() do wait(0) end
   
    sampRegisterChatCommand('sendkey', function() sendkey(1024) end) -- Жмет альт

    while true do wait(0) end
end
 
Последнее редактирование:

g305noobo

Известный
209
176
описание: асинхронное получение информации о файлах вместе с подпапками от path

код:
Lua:
function get_all_files_info_async(path, callback)
    lua_thread.create(function()
        local entries = {}

        local function scan_directory(directory_path)
            for entry in lfs.dir(directory_path) do
                if entry ~= "." and entry ~= ".." then
                    local entry_path = directory_path .. "/" .. entry
                    local entry_type = lfs.attributes(entry_path, "mode")

                    local size = entry_type == "file" and lfs.attributes(entry_path, "size") or 0

                    local entry_data = {
                        type = entry_type,
                        name = entry,
                        path = entry_path,
                        size = size,
                    }

                    table.insert(entries, entry_data)

                    if entry_type == "directory" then
                        scan_directory(entry_path)
                    end
                end
            end
        end

        scan_directory(path)

        callback(entries)
    end):run()
end
пример:
Lua:
get_all_files_info_async(getWorkingDirectory(), function(files_info)
    for _, file in ipairs(files_info) do
        print("type:", file.type)
        print("name:", file.name)
        print("path:", file.path)
        print("size:", file.size)
    end
end)
 

g305noobo

Известный
209
176
Описание: создание и вывод сообщений консоль от Windows. / очень удобно для двух мониторов
1707561158719.png

Lua:
local ffi = require("ffi")

ffi.cdef[[
    int AllocConsole();
    int WriteConsoleA(void* hConsoleOutput, const char* lpBuffer, unsigned long nNumberOfCharsToWrite, unsigned long* lpNumberOfCharsWritten, void* lpReserved);
    void* GetStdHandle(unsigned long nStdHandle);
]]

ffi.C.AllocConsole() -- создание консоли
local function print_console(message)
    local STD_OUTPUT_HANDLE = -11
    local hConsoleOutput = ffi.C.GetStdHandle(STD_OUTPUT_HANDLE)

    local writtenChars = ffi.new("unsigned long[1]")
    ffi.C.WriteConsoleA(hConsoleOutput, message, #message, writtenChars, nil)
end

print_console("Hello, world!\n")
 

g305noobo

Известный
209
176
Описание: модифицированная версия сообщения выше, Windows консоль с кодировкой(1251) поддерживающей кириллицу + с включенным ANSI escape codes(цвета)
1707773722500.png

Код:
Lua:
local ffi = require("ffi")

ffi.cdef[[
    int AllocConsole();
    int WriteConsoleA(void* hConsoleOutput, const char* lpBuffer, unsigned long nNumberOfCharsToWrite, unsigned long* lpNumberOfCharsWritten, void* lpReserved);
    void* GetStdHandle(unsigned long nStdHandle);
   
    static const int STD_OUTPUT_HANDLE = -11;
    static const int ENABLE_VIRTUAL_TERMINAL_PROCESSING = 4;  
    bool GetConsoleMode(intptr_t hConsoleHandle, int* lpMode);
    bool SetConsoleMode(intptr_t hConsoleHandle, int dwMode);
    int SetConsoleOutputCP(unsigned int CodePage);
]]

local color = {
    reset = "\027[0m",
    black = "\027[30m",
    red = "\027[31m",
    green = "\027[32m",
    yellow = "\027[33m",
    blue = "\027[34m",
    magenta = "\027[35m",
    cyan = "\027[36m",
    white = "\027[37m"
}

function create_console()
    if not ffi.C.AllocConsole() then return end
    local hConsoleOutput = ffi.C.GetStdHandle(ffi.C.STD_OUTPUT_HANDLE)

    local prev_console_mode = ffi.new"int[1]"
    ffi.C.GetConsoleMode(ffi.cast("intptr_t", hConsoleOutput), prev_console_mode)
    ffi.C.SetConsoleMode(ffi.cast("intptr_t", hConsoleOutput), bit.bor(prev_console_mode[0], ffi.C.ENABLE_VIRTUAL_TERMINAL_PROCESSING))
   
    ffi.C.SetConsoleOutputCP(1251)
end

function print_console(message)
    if message ~= nil then
        local hConsoleOutput = ffi.C.GetStdHandle(ffi.C.STD_OUTPUT_HANDLE)
        local writtenChars = ffi.new("unsigned long[1]")

        ffi.C.WriteConsoleA(hConsoleOutput, message, #message, writtenChars, nil)
    end
end
Пример:
Lua:
create_console()
print_console(color.blue.."hello "..color.red.."world!"..color.reset.."\n")
print_console("hello world\n")
 

VanoKLR

Известный
641
372
Описание: возвращает среднее число из массива
Код:
lua:
function number(array)
    local n = 0
    for i = 1, #array do
        n = n + array[i]
    end
    n = n / #array
    return n
end

Пример:
lua:
local array = {5,3,5,2,3,1,5,4}
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('getnumber', function()
        print(number(array)) -- result 3.5
    end)
    wait(-1)
end
 
Последнее редактирование:

why ega

РП игрок
Модератор
2,539
2,231
Описание: Получаем координаты спавна машины по ID
Код:
Lua:
local ffi = require("ffi")



ffi.cdef[[
    // ну да, могу, умею, практикую
    typedef struct
    {
        float x;
        float y;
        float z;
    } Vector3D;
]]



function getVehicleSpawnedPosition(vehicleId)
    return ffi.cast("Vector3D*",  sampGetVehiclePoolPtr() + 0x11AD4)[vehicleId]
end
Пример использования: link
 

СоМиК

Известный
457
310
Описание: Вызываем команду в cmd через FFI без os.execute и io.popen (соответственно без надоедливого открытия окна cmd.exe поверх гта)
Код:
What do u think about this code??????:
local ffi = require 'ffi'

ffi.cdef[[
    int ShellExecuteA(void *hwnd, const char *lpOperation, const char *lpFile, const char *lpParameters, const char *lpDirectory, int nShowCmd);
]]
local shell32 = ffi.load('shell32')

local function execute(command, callback)
    local tmpFilePath = ''
    if callback then
        tmpFilePath = os.tmpname()
        command = ('%s > "%s"'):format(command, tmpFilePath)
    end
    local result = shell32.ShellExecuteA(nil, 'open', 'cmd.exe', ('/c %s'):format(command), nil, 0) > 32
    if callback and result then
        lua_thread.create(function()
            while not doesFileExist(tmpFilePath) do wait(0) end
            local tmpFile = io.open(tmpFilePath, 'r')
            local output = tmpFile:read('*a')
            tmpFile:close()
            os.remove(tmpFilePath)
            callback(output)
        end)
    end
    return result
end

execute('start "" "https://t.me/ReSale_Revolution_LK_Bot"') -- откроет тг бота лучшего скрипта для цр аризона рп фарм фарм фарм вирты ФАРМ
execute('start "" "C:\\Users"') -- откроет пользователей на диске C в проводнике
execute('echo "test callback"', function(output) print(output) end) -- вызовет каллбек с параметром output возвращающим строку "test callback"
execute('lua', function(output) print(output) end) --LuaJIT 2.1.0-beta3 -- Copyright (C) 2005-2017 Mike Pall. http://luajit.org/JIT: ON SSE2 SSE3 SSE4.1 AMD BMI2 fold cse dce fwd dse narrow loop abc sink fuse
 

Gorskin

I shit on you
Проверенный
1,246
1,043
Описание: Отключает звук ветра в игре.
Lua:
local inicfg = require 'inicfg'
local directIni = 'NoWind.ini'
local ini = inicfg.load({
    settings = {
        wind = true
    },
}, directIni)
inicfg.save(ini, directIni)

function main()
    while not isSampAvailable() do wait(0) end
    sampfuncsLog("NoWind by Gorskin Loaded! use: /nowind")
    sampRegisterChatCommand("nowind",function()
        ini.settings.wind = not ini.settings.wind
        inicfg.save(ini, directIni)
        wnd()
        sampAddChatMessage(ini.settings.wind and "Ветер включен" or "Ветер выключен", -1)
    end)
    wnd()
    wait(-1)
end

function wnd()
    writeMemory(0x506667+1, 4, ini.settings.wind and 0xB72914 or 0x8E26DC, true)
    writeMemory(0x505BEB+1, 4, ini.settings.wind and 0xB72914 or 0x8E26DC, true)
    writeMemory(0x505377+2, 4, ini.settings.wind and 0xB72914 or 0x8E26DC, true)
end
 
Последнее редактирование:

g305noobo

Известный
209
176
Описание: возвращает путь до модуля (asi, dll, sf) по названию
1708365808007.png

Код:
Lua:
local ffi = require("ffi")

ffi.cdef[[
    typedef void* HMODULE;
    HMODULE GetModuleHandleA(const char* lpModuleName);
    uint32_t GetModuleFileNameA(HMODULE hModule, char* lpFilename, uint32_t nSize);
]]

local kernel32 = ffi.load("kernel32")

function get_module_path(module)
    local handle = kernel32.GetModuleHandleA(module)
    if handle == nil then return nil end

    local path_buffer = ffi.new("char[?]", 260)
    local path_length = kernel32.GetModuleFileNameA(handle, path_buffer, 260)

    if path_length > 0 then return ffi.string(path_buffer, path_length) end
    return nil
end
Пример:
Lua:
print("Путь до MoonLoader:", get_module_path("moonloader.asi"))
 
Последнее редактирование:

СоМиК

Известный
457
310
Описание: простейший алгоритм нахождения числа в любой системе счисления на Lua. Может быть кому нибудь пригодится (можете закидать багами, но пусть будет)

Код:
lol:
local translateToNS = setmetatable(
    {
        symbols = '0123456789abcdefghijklmnopqrstuvwxyz'
    },
    {
        __call = function(self, n, ns)
            if #self.symbols >= ns and ns > 1 then
                local result = ''
                while n > 0 do
                    local del = n % ns + 1
                    result = ('%s%s'):format((self.symbols):sub(del, del), result)
                    n = math.floor(n / ns)
                end
                return result
            end
            return 'NaN'
        end
    }
)

Пример:
example:
local a = translateToNS(4294967295, 16) -- 'ffffffff'
local b = translateToNS(4294967295, 25) -- 'hek2mgk' | перевод числа 4294967295 в 25-ричную систему счисления
translateToNS.symbols = '0123456789' -- изменение стандартных символов
 
Последнее редактирование:

cord

contact me → cordtech.ru
Проверенный
555
409
Описание: Возвращает хендл ближайшего т/с к центру экрана

Код:
Lua:
function getNearestCarHandle(maxDistance)
    maxDistance = maxDistance or 9999 -- Дистанцию можно не указывать
    local resX, resY = getScreenResolution()
    local centerX, centerY = resX / 2, resY / 2
    local distanceBetweenVehicles = {}
    local plX, plY, plZ = getCharCoordinates(PLAYER_PED)
    for k, v in ipairs(getAllVehicles()) do
        local carX, carY, carZ = getCarCoordinates(v)
        local screenX, screenY = convert3DCoordsToScreen(carX, carY, carZ)
        local distance = getDistanceBetweenCoords2d(centerX, centerY, screenX, screenY)
        local distanceBetweenPlayerAndVehicle = getDistanceBetweenCoords3d(plX, plY, plZ, carX, carY, carZ)
        if distanceBetweenPlayerAndVehicle < maxDistance then
            table.insert(distanceBetweenVehicles, {handle = v, distance = distance})
        end
    end
    local smallestDistance, handle = 9999, -1
    for k, v in ipairs(distanceBetweenVehicles) do
        if smallestDistance > v.distance then
            smallestDistance = v.distance
            handle = v.handle
        end
    end
    return handle, smallestDistance
end

Пример:
Lua:
local handle, distance = getNearestCarHandle(250)
print(handle, distance) -->> 4727, 119
 

VanoKLR

Известный
641
372
Описание: Возвращает хендл ближайшего т/с к центру экрана

Код:
Lua:
function getNearestCarHandle(maxDistance)
    maxDistance = maxDistance or 9999 -- Дистанцию можно не указывать
    local resX, resY = getScreenResolution()
    local centerX, centerY = resX / 2, resY / 2
    local distanceBetweenVehicles = {}
    local plX, plY, plZ = getCharCoordinates(PLAYER_PED)
    for k, v in ipairs(getAllVehicles()) do
        local carX, carY, carZ = getCarCoordinates(v)
        local screenX, screenY = convert3DCoordsToScreen(carX, carY, carZ)
        local distance = getDistanceBetweenCoords2d(centerX, centerY, screenX, screenY)
        local distanceBetweenPlayerAndVehicle = getDistanceBetweenCoords3d(plX, plY, plZ, carX, carY, carZ)
        if distanceBetweenPlayerAndVehicle < maxDistance then
            table.insert(distanceBetweenVehicles, {handle = v, distance = distance})
        end
    end
    local smallestDistance, handle = 9999, -1
    for k, v in ipairs(distanceBetweenVehicles) do
        if smallestDistance > v.distance then
            smallestDistance = v.distance
            handle = v.handle
        end
    end
    return handle, smallestDistance
end

Пример:
Lua:
local handle, distance = getNearestCarHandle(250)
print(handle, distance) -->> 4727, 119