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

madrasso

Потрачен
883
324
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Описание: Мигает окном один раз.
Lua:
local ffi = require('ffi')

ffi.cdef [[
    typedef int BOOL;
    typedef unsigned long HANDLE;
    typedef HANDLE HWND;
    typedef int bInvert;
 
    HWND GetActiveWindow(void);

    BOOL FlashWindow(HWND hWnd, BOOL bInvert);
]]

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

ffi.cdef [[
    typedef int BOOL;
    typedef unsigned long HANDLE;
    typedef HANDLE HWND;
    typedef int bInvert;
 
    HWND GetActiveWindow(void);

    BOOL FlashWindow(HWND hWnd, BOOL bInvert);
]]

function main()
    while not isSampfuncsLoaded() or not isSampLoaded() do wait(1000) end
    while not isSampAvailable() do wait(500) end
    window = ffi.C.GetActiveWindow()
    ffi.C.FlashWindow(window, true)
    wait(-1)
end
 
Последнее редактирование:

Azller Lollison

я узбек
Друг
1,342
2,266
Описание: получает точные координаты метки (нормальное определение Z координаты)
Lua:
function getTargetBlipCoordinatesFixed()
    local bool, x, y, z = getTargetBlipCoordinates(); if not bool then return false end
    requestCollision(x, y); loadScene(x, y, z)
    local bool, x, y, z = getTargetBlipCoordinates()
    return bool, x, y, z
end

Пример использования:

Lua:
function main()
    while not isSampAvailable() do wait(0) end
    sampAddChatMessage("Супер приватный телепорт для DIMON RP загружен", 1337228)
    sampRegisterChatCommand("superprivateteleportfordimonrp", function()
        if getTargetBlipCoordinatesFixed() then
            local _, x, y, z = getTargetBlipCoordinatesFixed()
            setCharCoordinates(PLAYER_PED, x, y, z)
        else
            sampAddChatMessage("Ув. Пользователь приватного телепорта для DIMON RP поставьте метку", 1337228)
        end
    end)
    wait(-1)
end
 

Musaigen

abobusnik
Проверенный
1,583
1,302
Описание: Рисует кнопку переключения с квадратом место галочки.
Lua:
function imgui.CheckBox(name, bool, str_id)

    local p = imgui.GetCursorScreenPos()
    local draw_list = imgui.GetWindowDrawList()

    local height = imgui.GetTextLineHeightWithSpacing() + (imgui.GetStyle().FramePadding.y / 2)
    local width = height

    local invisible_button = (str_id == nil) and name or str_id
    if imgui.InvisibleButton('##' ..invisible_button, imgui.ImVec2(width, height)) then
     bool.v = not bool.v
    end

    local col_bg
    if imgui.IsItemHovered() then
     col_bg = imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.FrameBgHovered])
    else
     col_bg = imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.FrameBg])
    end

    draw_list:AddRectFilled(p, imgui.ImVec2(p.x + width, p.y + height), col_bg, imgui.GetStyle().FrameRounding)

    draw_list:AddRectFilled(p, imgui.ImVec2(p.x + width, p.y + height), imgui.GetColorU32(bool.v and imgui.GetStyle().Colors[imgui.Col.ButtonActive] or imgui.GetStyle().Colors[imgui.Col.Button]), imgui.GetStyle().FrameRounding)


    imgui.SameLine(imgui.GetStyle().ItemSpacing.x + width + (imgui.GetStyle().FramePadding.x))
    imgui.AlignTextToFramePadding()
    imgui.Text(name)
end
Пример использования.
Lua:
imgui.CheckBox('Bad Position', imgui.ImBool(true), 'ImGui::ID');
imgui.CheckBox('Bad SeatId', imgui.ImBool(false));
Screenshot_17.png
 
Последнее редактирование:
  • Нравится
Реакции: MrYurkoo и r0ckwe11

AnWu

Guardian of Order
Всефорумный модератор
4,686
5,166
Описание: Проверяет есть ли указанный символ из массива в тексте.
Lua:
function checkSymbol(sumTable, checkText)
    for k, v in pairs(sumTable) do
        if checkText:find(v) then return true end
    end
    return false
end
Пример использования:
Lua:
local rusSym = { "а", "б", "в", "г", "д", "е", "ё", "ж", "з", "и", "й", "к", "л", "м", "н", "о", "п", "р", "с", "т", "у", "ф", "х", "ц", "ч", "ш", "щ", "ъ", "ы", "ь", "э", "ю", "я",
"А", "Б", "В", "Г", "Д", "Е", "Ё", "Ж", "З", "И", "Й", "К", "Л", "М", "Н", "О", "П", "Р", "С", "Т", "У", "Ф", "Х", "Ц", "Ч", "Ш", "Щ", "Ъ", "Ы", "Ь", "Э", "Ю", "Я" }
local text = "Привет"
if checkSymbol(rusSym, text) then
 print("В данном тексте есть русские символы!")
else
 print("В данном тексте нету русских символов")
end
Я чего-то не понимаю? Нахуя это нужно?
Lua:
print("Russian fucking symbol: ", ("Привет"):find("[А-Яа-я]+"))

Описание: Рисует кнопку переключения с квадратом место галочки.
Lua:
function imgui.CheckBox(name, bool, str_id)

    local p = imgui.GetCursorScreenPos()
    local draw_list = imgui.GetWindowDrawList()

    local height = imgui.GetTextLineHeightWithSpacing() + (imgui.GetStyle().FramePadding.y / 2)
    local width = height

    local invisible_button = (str_id == nil) and name or str_id
    if imgui.InvisibleButton('##' ..invisible_button, imgui.ImVec2(width, height)) then
     bool.v = not bool.v
    end

    local col_bg
    if imgui.IsItemHovered() then
     col_bg = imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.FrameBgHovered])
    else
     col_bg = imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.FrameBg])
    end

    draw_list:AddRectFilled(p, imgui.ImVec2(p.x + width, p.y + height), col_bg, imgui.GetStyle().FrameRounding)

    draw_list:AddRectFilled(p, imgui.ImVec2(p.x + width, p.y + height), imgui.GetColorU32(bool.v and imgui.GetStyle().Colors[imgui.Col.ButtonActive] or imgui.GetStyle().Colors[imgui.Col.Button]), imgui.GetStyle().FrameRounding)


    imgui.SameLine(imgui.GetStyle().ItemSpacing.x + width + (imgui.GetStyle().FramePadding.x))
    imgui.AlignTextToFramePadding()
    imgui.Text(name)
end
Пример использования.
Lua:
imgui.CheckBox('Bad Position', imgui.ImBool(true), 'ImGui::ID');
imgui.CheckBox('Bad SeatId', imgui.ImBool(false));
Посмотреть вложение 22328
отвратительно реализовано. И зачем нужен str_id? Ведь для разделения по ID умный имгуи давно придумал обрезать всё после ## в имени.
Я долго думал чем отличаются два чекбокса. Так ты просто квадрату цвет меняешь. Лучшим и понятным решением будет добавить квадрат в квадрат и подвергнуть его правилу фреймроунда. Тогда можно будет закруглить квадрат, что даст аж целый новый чекбокс. Два в одном так сказать.
Lua:
  local invisible_button = (str_id == nil) and name or str_id
>>
  local invisible_button = str_id or name
 

astynk

Известный
Проверенный
742
530
Возвращает ID ближайшего игрока, -1 если в зоне стрима никого нет.

Lua:
function getClosestPlayerId()
    local minDist = 9999
    local closestId = -1
    local x, y, z = getCharCoordinates(PLAYER_PED)
    for i = 0, 999 do
        local streamed, pedID = sampGetCharHandleBySampPlayerId(i)
        if streamed then
            local xi, yi, zi = getCharCoordinates(pedID)
            local dist = math.sqrt( (xi - x) ^ 2 + (yi - y) ^ 2 + (zi - z) ^ 2 )
            if dist < minDist then
                minDist = dist
                closestId = i
            end
        end
    end
    return closestId
end
 
Последнее редактирование модератором:

drags

Известный
Проверенный
155
207
Узнаем что за проц стоит у юзера

Lua:
local ffi = require("ffi")
local qwords = ffi.typeof("uint64_t[?]")
local dwords = ffi.typeof("uint32_t *")
local cpuid_EAX_EDX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x5B\xC3")
local cpuid_EBX_ECX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x91\x92\x93\x5B\xC3")

local function cpuid(n)
   local arr = ffi.cast(dwords, qwords(2, cpuid_EAX_EDX(n), cpuid_EBX_ECX(n)))
   return ffi.string(arr, 4), ffi.string(arr + 2, 4), ffi.string(arr + 3, 4), ffi.string(arr + 1, 4)
end

local s1 = ""
for n = 0x80000002, 0x80000004 do
   local eax, ebx, ecx, edx = cpuid(n)
   s1 = s1..eax..ebx..ecx..edx
end
s1 = s1:gsub("^%s+", ""):gsub("%z+$", "")

local eax, ebx, ecx, edx = cpuid(0)
local s2 = ebx..edx..ecx
s2 = s2:gsub("^%s+", ""):gsub("%z+$", "")

---Результат
print(s1.." "..s2)  -- Intel(R) Core(TM) i3-7100U CPU @ 2.40GHz GenuineIntel
 

#Northn

Police Helper «Reborn» — уже ШЕСТЬ лет!
Всефорумный модератор
2,634
2,483
Описание: Выводит на экран сообщение функцией MessageBoxA. Вырезано с исходного кода LuaRocks. Последним параметром можно выдавать как нулёвое значение, так же и 0x10 - 0x40. Каждый раз картинка слева будет меняться.
Lua:
--В начало скрипта.
local ffi = require 'ffi'

--Глубоко в скрипте.
function ShowMessage(text, title, style)
    ffi.cdef [[
        int MessageBoxA(
            void* hWnd,
            const char* lpText,
            const char* lpCaption,
            unsigned int uType
        );
    ]]
    local hwnd = ffi.cast('void*', readMemory(0x00C8CF88, 4, false))
    ffi.C.MessageBoxA(hwnd, text,  title, style and (style + 0x50000) or 0x50000)
end
Пример использования:
Lua:
ShowMessage('Демонстрация этой крутой штуковины.', 'Заголовок', 0x10)

upload_2019-1-11_16-14-35.png
 

Akionka

akionka.lua
Проверенный
742
500
Описание: Обрезает пробелы по краям строки (triming)
Lua:
function trim(s)
    return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
Пример использования:
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(0) end
    str = "  12312312     "
    print(#str)
    print(#trim(str))
end
output:
Код:
script.lua: 15
script.lua: 8
 

ШPEK

Известный
1,476
524
Описание: вставляет любые символы между цифрами в числе
Lua:
function setSymbolsBetweenNumbers(num, symbol)
  assert(type(num) == "number", "a not number value (1st argument)")
  assert(type(symbol) == "string", "a not string value (2nd argument)")
  return tostring(num):gsub("(%d)(%d)", "%1"..symbol.."%2"):gsub("(%d)(%d)", "%1"..symbol.."%2")
end
Пример использования:
Lua:
print(setSymbolsBetweenNumbers(19292, "-"))
 

FYP

Известный
Администратор
1,758
5,722
Описание: Функция для исправления кодировки текста на нужную для текстдравов
Lua:
function RusToGame(text)
    text = text:gsub('А', 'A')
    text = text:gsub('а', 'a')
    text = text:gsub('Б', 'Ђ')
    text = text:gsub('б', '—')
    text = text:gsub('В', '‹')
    text = text:gsub('в', 'ў')
    text = text:gsub('Г', '‚')
    text = text:gsub('г', '™')
    text = text:gsub('Д', 'ѓ')
    text = text:gsub('д', 'љ')
    text = text:gsub('Е', 'E')
    text = text:gsub('е', 'e')
    text = text:gsub('Ё', 'E')
    text = text:gsub('ё', 'e')
    text = text:gsub('Ж', '„')
    text = text:gsub('ж', '›')
    text = text:gsub('З', '€')
    text = text:gsub('з', 'џ')
    text = text:gsub('И', '…')
    text = text:gsub('и', 'њ')
    text = text:gsub('Й', '…')
    text = text:gsub('й', 'ќ')
    text = text:gsub('К', 'K')
    text = text:gsub('к', 'k')
    text = text:gsub('Л', '‡')
    text = text:gsub('л', 'ћ')
    text = text:gsub('М', 'M')
    text = text:gsub('м', 'Ї')
    text = text:gsub('Н', 'H')
    text = text:gsub('н', '®')
    text = text:gsub('О', 'O')
    text = text:gsub('о', 'o')
    text = text:gsub('П', 'Њ')
    text = text:gsub('п', 'Ј')
    text = text:gsub('Р', 'P')
    text = text:gsub('р', 'p')
    text = text:gsub('С', 'C')
    text = text:gsub('с', 'c')
    text = text:gsub('Т', 'Џ')
    text = text:gsub('т', '¦')
    text = text:gsub('У', 'Y')
    text = text:gsub('у', 'y')
    text = text:gsub('Ф', 'Ѓ')
    text = text:gsub('ф', '?')
    text = text:gsub('Х', 'X')
    text = text:gsub('х', 'x')
    text = text:gsub('Ц', '‰')
    text = text:gsub('ц', '$')
    text = text:gsub('Ч', 'Ќ')
    text = text:gsub('ч', '¤')
    text = text:gsub('Ш', 'Ћ')
    text = text:gsub('ш', 'Ґ')
    text = text:gsub('Щ', 'Љ')
    text = text:gsub('щ', 'Ў')
    text = text:gsub('Ь', '’')
    text = text:gsub('ь', '©')
    text = text:gsub('Ъ', '§')
    text = text:gsub('ъ', 'ђ')
    text = text:gsub('Ы', '‘')
    text = text:gsub('ы', 'Ё')
    text = text:gsub('Э', '“')
    text = text:gsub('э', 'Є')
    text = text:gsub('Ю', '”')
    text = text:gsub('ю', '«')
    text = text:gsub('Я', '•')
    text = text:gsub('я', '¬')
    return text
end
Пример использования:
Lua:
sampTextdrawCreate(282, RusToGame('й, б, ф, я'), 1337.0, 228.0)
Lua:
function RusToGame(text)
    local convtbl = {[230]=155,[231]=159,[247]=164,[234]=107,[250]=144,[251]=168,[254]=171,[253]=170,[255]=172,[224]=97,[240]=112,[241]=99,[226]=162,[228]=154,[225]=151,[227]=153,[248]=165,[243]=121,[184]=101,[235]=158,[238]=111,[245]=120,[233]=157,[242]=166,[239]=163,[244]=63,[237]=174,[229]=101,[246]=36,[236]=175,[232]=156,[249]=161,[252]=169,[215]=141,[202]=75,[204]=77,[220]=146,[221]=147,[222]=148,[192]=65,[193]=128,[209]=67,[194]=139,[195]=130,[197]=69,[206]=79,[213]=88,[168]=69,[223]=149,[207]=140,[203]=135,[201]=133,[199]=136,[196]=131,[208]=80,[200]=133,[198]=132,[210]=143,[211]=89,[216]=142,[212]=129,[214]=137,[205]=72,[217]=138,[218]=167,[219]=145}
    local result = {}
    for i = 1, #text do
        local c = text:byte(i)
        result[i] = string.char(convtbl[c] or c)
    end
    return table.concat(result)
end
советую всегда стараться делать сразу нормально или как минимум не выкладывать говнокод в качестве сниппета. твоя реализация очень неоптимизированная.
 

molimawka

Известный
Друг
443
648
Описание: Выход из полноэкранного режима
Lua:
function windowMode(w,h)
    local ffi = require('ffi')
    if ffi.arch == 'x64' then
        ffi.cdef'typedef unsigned __int64 UINT_PTR;'
        ffi.cdef'typedef __int64 LONG_PTR;'
    else
        ffi.cdef'typedef unsigned int UINT_PTR;'
        ffi.cdef'typedef long LONG_PTR;'
    end

    ffi.cdef [[
        typedef unsigned long HANDLE;
        typedef HANDLE HWND;
        typedef unsigned int uint;
        typedef LONG_PTR lresult;
        typedef LONG_PTR LPARAM;
        typedef UINT_PTR WPARAM;
        typedef struct _RECT {
          long left;
          long top;
          long right;
          long bottom;
        } RECT, *PRECT;
  
        HWND GetActiveWindow(void);
  
        bool SetWindowPos(
          HWND hWnd,
          HWND hWndInsertAfter,
          int  X,
          int  Y,
          int  cx,
          int  cy,
          uint uFlags
        );
  
        lresult SendMessageA(
          HWND   hWnd,
          uint   Msg,
          WPARAM wParam,
          LPARAM lParam
        );
  
        int GetSystemMetrics(
          int nIndex
        );
  
        bool GetWindowRect(
          HWND   hWnd,
          PRECT lpRect
        );
  
    ]]

    local szx = ffi.C.GetSystemMetrics(0);
    local szy = ffi.C.GetSystemMetrics(1);

    local rect = ffi.new('RECT', 0)
    ffi.C.GetWindowRect(ffi.C.GetActiveWindow(),rect);

    local cszx = rect.right - rect.left
    local cszy = rect.bottom - rect.top

    if szx == cszx and szy == cszy then

        ffi.C.SendMessageA(ffi.C.GetActiveWindow(), 0x0104, 0x00000012, 0x20380001);
        ffi.C.SendMessageA(ffi.C.GetActiveWindow(), 0x0104, 0x0000000D, 0x201C0001);  
        ffi.C.SendMessageA(ffi.C.GetActiveWindow(), 0x0106, 0x0000000D, 0x201C0001);
        ffi.C.SendMessageA(ffi.C.GetActiveWindow(), 0x0105, 0x0000000D, 0xE01C0001);
        ffi.C.SendMessageA(ffi.C.GetActiveWindow(), 0x0101, 0x00000012, 0xC0380001);

        ffi.C.SetWindowPos(ffi.C.GetActiveWindow(), -1, 1, 1, w,h,0x0200)
    end
end
Пример использования:
Lua:
function main()
    if not isSampLoaded() then return end
    while not isSampAvailable() do wait(0) end
    windowMode(640,480)
end
 
Последнее редактирование:

Pakulichev

Software Developer & System Administrator
Друг
1,789
2,132
Описание: Позволяет получить сторону света, в которую повёрнут персонаж.
Lua:
function direction()
    if sampIsLocalPlayerSpawned() then
        local angel = math.ceil(getCharHeading(PLAYER_PED))
        if angel then
            if (angel >= 0 and angel <= 30) or (angel <= 360 and angel >= 330) then
                return "Север"
            elseif (angel > 80 and angel < 100) then
                    return "Запад"
            elseif (angel > 260 and angel < 280) then
                    return "Восток"
            elseif (angel >= 170 and angel <= 190) then
                    return "Юг"
            elseif (angel >= 31 and angel <= 79) then
                    return "Северо-запад"
            elseif (angel >= 191 and angel <= 259) then
                    return "Юго-восток"
            elseif (angel >= 81 and angel <= 169) then
                    return "Юго-запад"
            elseif (angel >= 259 and angel <= 329) then
                    return "Северо-восток"
            else
                return angel
            end
        else
            return "Неизвестно"
        end
    else
        return "Неизвестно"
    end
end
Пример использования:
Lua:
print("Ваш персонаж смотрит на " .. direction())
 

#Northn

Police Helper «Reborn» — уже ШЕСТЬ лет!
Всефорумный модератор
2,634
2,483
Описание: Центрирование текста в окнах ImGui, а так же возможность перекрашивать текст RGB-вставками. Функцию смены цвета текста взял у @imring и изменил. В функции имеется встроенная смена кодировки, так что при вызове функции менять кодировку не нужно.
Lua:
local encoding = require 'encoding'
encoding.default = 'CP1251'
local u8 = encoding.UTF8

function imgui.CenterTextColoredRGB(text)
    local width = imgui.GetWindowWidth()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local ImVec4 = imgui.ImVec4

    local explode_argb = function(argb)
        local a = bit.band(bit.rshift(argb, 24), 0xFF)
        local r = bit.band(bit.rshift(argb, 16), 0xFF)
        local g = bit.band(bit.rshift(argb, 8), 0xFF)
        local b = bit.band(argb, 0xFF)
        return a, r, g, b
    end

    local getcolor = function(color)
        if color:sub(1, 6):upper() == 'SSSSSS' then
            local r, g, b = colors[1].x, colors[1].y, colors[1].z
            local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
            return ImVec4(r, g, b, a / 255)
        end
        local color = type(color) == 'string' and tonumber(color, 16) or color
        if type(color) ~= 'number' then return end
        local r, g, b, a = explode_argb(color)
        return imgui.ImColor(r, g, b, a):GetVec4()
    end

    local render_text = function(text_)
        for w in text_:gmatch('[^\r\n]+') do
            local textsize = w:gsub('{.-}', '')
            local text_width = imgui.CalcTextSize(u8(textsize))
            imgui.SetCursorPosX( width / 2 - text_width .x / 2 )
            local text, colors_, m = {}, {}, 1
            w = w:gsub('{(......)}', '{%1FF}')
            while w:find('{........}') do
                local n, k = w:find('{........}')
                local color = getcolor(w:sub(n + 1, k - 1))
                if color then
                    text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                    colors_[#colors_ + 1] = color
                    m = n
                end
                w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
            end
            if text[0] then
                for i = 0, #text do
                    imgui.TextColored(colors_[i] or colors[1], u8(text[i]))
                    imgui.SameLine(nil, 0)
                end
                imgui.NewLine()
            else
                imgui.Text(u8(w))
            end
        end
    end
    render_text(text)
end
Пример использования:
Lua:
imgui.CenterTextColoredRGB('Строка {ff0000}номер {SSSSSS}один\nДва\n{ff0000}И даже {0059B3}три!')

upload_2019-1-17_13-45-38.png
 

Вложения

  • upload_2019-1-17_13-44-39.png
    upload_2019-1-17_13-44-39.png
    1.2 KB · Просмотры: 465

molimawka

Известный
Друг
443
648
(Не знаю насколько полезно)
Описание: Inject dll
Lua:
function injectDll(dllName)
    local ffi = require('ffi')
    if ffi.arch == 'x64' then
        ffi.cdef'typedef __int64 INT_PTR;'
    else
        ffi.cdef'typedef int INT_PTR;'
    end
    ffi.cdef [[
        typedef unsigned long DWORD;
        typedef void *PVOID;
        typedef void *LPVOID;
        typedef PVOID HANDLE;
        typedef bool BOOL;
        typedef char CHAR;
        typedef size_t SIZE_T;
        typedef const CHAR *LPCSTR;
        typedef const void *LPCVOID;
        typedef HANDLE HINSTANCE;
        typedef HINSTANCE HMODULE;
        typedef DWORD *LPDWORD;
        typedef INT_PTR (* FARPROC)();
       
        typedef struct _SECURITY_ATTRIBUTES {
          DWORD  nLength;
          LPVOID lpSecurityDescriptor;
          BOOL   bInheritHandle;
        } SECURITY_ATTRIBUTES, *PSECURITY_ATTRIBUTES, *LPSECURITY_ATTRIBUTES;
       
        typedef DWORD (*LPTHREAD_START_ROUTINE) (
            LPVOID lpThreadParameter
        );
       
        DWORD GetCurrentProcessId();

        HANDLE OpenProcess(
          DWORD dwDesiredAccess,
          BOOL  bInheritHandle,
          DWORD dwProcessId
        );
        HMODULE GetModuleHandleA(
          LPCSTR lpModuleName
        );
        LPVOID GetProcAddress(
          HMODULE hModule,
          LPCSTR  lpProcName
        );
        FARPROC VirtualAllocEx(
          HANDLE hProcess,
          LPVOID lpAddress,
          SIZE_T dwSize,
          DWORD  flAllocationType,
          DWORD  flProtect
        );
        BOOL WriteProcessMemory(
          HANDLE  hProcess,
          LPVOID  lpBaseAddress,
          LPCVOID lpBuffer,
          SIZE_T  nSize,
          SIZE_T  *lpNumberOfBytesWritten
        );
        HANDLE CreateRemoteThread(
          HANDLE                 hProcess,
          LPSECURITY_ATTRIBUTES  lpThreadAttributes,
          SIZE_T                 dwStackSize,
          LPTHREAD_START_ROUTINE lpStartAddress,
          LPVOID                 lpParameter,
          DWORD                  dwCreationFlags,
          LPDWORD                lpThreadId
        );
        DWORD WaitForSingleObject(
          HANDLE hHandle,
          DWORD  dwMilliseconds
        );
        BOOL CloseHandle(
          HANDLE hObject
        );
       
       
    ]]
    local k32Lib = ffi.load("kernel32");
    local handle = ffi.C.OpenProcess(0x1F0FFF, false, ffi.C.GetCurrentProcessId())
    local LoadLibAddr = ffi.C.GetProcAddress(ffi.C.GetModuleHandleA('kernel32'),'LoadLibraryA')
    local baseAddr = ffi.C.VirtualAllocEx(handle, nil, string.len(dllName), 0x00001000 or 0x00002000, 0x04);
    ffi.C.WriteProcessMemory(handle, baseAddr, dllName, string.len(dllName), nil);
    LoadLibAddr = ffi.new('LPTHREAD_START_ROUTINE',LoadLibAddr)
    local remThread = ffi.C.CreateRemoteThread(handle, nil, 0, LoadLibAddr, baseAddr, 0, nil);
    ffi.C.WaitForSingleObject(remThread, 0xFFFFFFFF);
    ffi.C.CloseHandle(remThread)
    ffi.C.CloseHandle(handle)
end
Пример использования:
Lua:
injectDll('C:\\1.dll')