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

Vintik

Мечтатель
Проверенный
1,449
894
где ошибка? про кодировку забейте
Lua:
script_name('FamilyHelper v 1.0')
script_author('Tsunami_Nakamura')
script_description('FamilyHelper v 1.0')
script_version('1.0')

require "lib.moonloader"
local imgui = require 'imgui'
local key = require 'vkeys'

local main_window_state = imgui.ImBool(false)
function imgui.OnDrawFrame()
  if main_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(1000, 500), imgui.Cond.FirstUseEver)
    imgui.Begin('Family Helper by Nakamura', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    imgui.Text('Hello world')
    end
    imgui.End()
  end
end

function main()
  imgui.Process = true
end




function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(2000) end
    sampAddChatMessage('[FamHelper] ����� �������: Tsunami_Nakamura. ��������: Adam_Karleone [ARIZONA 10]', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ���� �������? �� - lcn.maks', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ��������� �������: /famh', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ������ �� ���������? ������ � ��', 0x00BFFF)
    sampRegisterChatCommand('famh', function() main_window_state.v = not main_window_state.v end)
    while true do
            wait(0)
            if main_window_state.v then
                imgui.ShowCursor = true
      imgui.Process = true
    else
      imgui.Process = false
    end
            imgui.Process = main_window_state.v
    end
end
Lua:
script_name('FamilyHelper v 1.0')
script_author('Tsunami_Nakamura')
script_description('FamilyHelper v 1.0')
script_version('1.0')

require 'lib.moonloader'
local imgui = require 'imgui'
local key = require 'vkeys'

local main_window_state = imgui.ImBool(false)

function imgui.OnDrawFrame()
  if main_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(1000, 500), imgui.Cond.FirstUseEver)
    imgui.Begin('Family Helper by Nakamura', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    imgui.Text('Hello world')
    imgui.End()
  end
end

function main()
  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(0) end
  imgui.Process = true
  sampAddChatMessage('[FamHelper] ����� �������: Tsunami_Nakamura. ��������: Adam_Karleone [ARIZONA 10]', 0x00BFFF)
  sampAddChatMessage('[FamHelper] ���� �������? �� - lcn.maks', 0x00BFFF)
  sampAddChatMessage('[FamHelper] ��������� �������: /famh', 0x00BFFF)
  sampAddChatMessage('[FamHelper] ������ �� ���������? ������ � ��', 0x00BFFF)
  sampRegisterChatCommand('famh', function() main_window_state.v = not main_window_state.v end)
  while true do
    wait(0)
    if main_window_state.v then
      imgui.ShowCursor = true
    else
      imgui.ShowCursor = false
    end
  end
end
1) Соблюдай табуляцию (чтобы код был читаемый)
2) Не может быть более 1 функции main()
Посмотри код, который я тебе переделал, там всё более просто и не запутано.
 

Kiberbuling

Новичок
20
1
бл, я чет сделал, тип в чате пишет там что скрипт загружен и тд, но кмд нет тип
Lua:
script_name('FamilyHelper v 1.0')
script_author('Tsunami_Nakamura')
script_description('FamilyHelper v 1.0')
script_version('1.0')

require "lib.moonloader"
local imgui = require 'imgui'
local key = require 'vkeys'


function main()
  imgui.Process = true
end


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(2000) end
    sampAddChatMessage('[FamHelper] ����� �������: Tsunami_Nakamura. ��������: Adam_Karleone [ARIZONA 10]', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ���� �������? �� - lcn.maks', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ��������� �������: /famh', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ������ �� ���������? ������ � ��', 0x00BFFF)
    sampRegisterChatCommand('famh', function() main_window_state.v = not main_window_state.v end)
    while true do
            wait(0)
            if main_window_state.v then
                imgui.ShowCursor = true
      imgui.Process = true
    else
      imgui.Process = false
    end
            imgui.Process = main_window_state.v
    end
end

local main_window_state = imgui.ImBool(false)
function imgui.OnDrawFrame()
  if main_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(1000, 500), imgui.Cond.FirstUseEver)
    imgui.Begin('Family Helper by Nakamura', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)

    if imgui.Button (u8"Основное меню", imgui.ImVec2(200,20)) then uu() menu[1] = true end
  end
end
 

[SA ARZ]

Известный
390
8
Посмотреть вложение 88405

Где Доступен - выбирал и принимал квест
Появится надпись что нужно завершить квест то выбрал пункт - Можно завершить
help и когда выбрал Доступен, в другом окне нажала 1 кнопку, после ещё раз эту панель открыл и выбрал следующий квест и так все
 

kizn

О КУ)))
Всефорумный модератор
2,405
2,054
бл, я чет сделал, тип в чате пишет там что скрипт загружен и тд, но кмд нет тип
Lua:
script_name('FamilyHelper v 1.0')
script_author('Tsunami_Nakamura')
script_description('FamilyHelper v 1.0')
script_version('1.0')

require "lib.moonloader"
local imgui = require 'imgui'
local key = require 'vkeys'


function main()
  imgui.Process = true
end


function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(2000) end
    sampAddChatMessage('[FamHelper] ����� �������: Tsunami_Nakamura. ��������: Adam_Karleone [ARIZONA 10]', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ���� �������? �� - lcn.maks', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ��������� �������: /famh', 0x00BFFF)
    sampAddChatMessage('[FamHelper] ������ �� ���������? ������ � ��', 0x00BFFF)
    sampRegisterChatCommand('famh', function() main_window_state.v = not main_window_state.v end)
    while true do
            wait(0)
            if main_window_state.v then
                imgui.ShowCursor = true
      imgui.Process = true
    else
      imgui.Process = false
    end
            imgui.Process = main_window_state.v
    end
end

local main_window_state = imgui.ImBool(false)
function imgui.OnDrawFrame()
  if main_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(1000, 500), imgui.Cond.FirstUseEver)
    imgui.Begin('Family Helper by Nakamura', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)

    if imgui.Button (u8"Основное меню", imgui.ImVec2(200,20)) then uu() menu[1] = true end
  end
end
где imgui.end()
 

HpP

Известный
368
117
Как получить высоту и ширину mimgui окна и записать их в переменную?
 

kuzheren

Известный
484
444
Как сделать какое-то действие если игрок отключился? (Server closed the connection)
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,762
11,195
Как использовать:
https://www.blast.hk/threads/13380/page-16#post-650507 ?
Код:
[ML] (error) chams.lua: ...AMP only asi loader\GTA San Andreas\moonloader\chams.lua:133: attempt to call global 'GetTextureStageState' (a nil value)
stack traceback:
    ...AMP only asi loader\GTA San Andreas\moonloader\chams.lua:133: in main chunk
[ML] (error) chams.lua: Script died due to an error. (115B1EC4)
 

wulfandr

Известный
637
260
Как использовать:
https://www.blast.hk/threads/13380/page-16#post-650507 ?
Код:
[ML] (error) chams.lua: ...AMP only asi loader\GTA San Andreas\moonloader\chams.lua:133: attempt to call global 'GetTextureStageState' (a nil value)
stack traceback:
    ...AMP only asi loader\GTA San Andreas\moonloader\chams.lua:133: in main chunk
[ML] (error) chams.lua: Script died due to an error. (115B1EC4)
так и используй как в примере. но удали с GetTextureStageState который вне функции находится. после ffi, он криво написал
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,762
11,195
так и используй как в примере. но удали с GetTextureStageState который вне функции находится. после ffi, он криво написал
так у меня вообще сам не запускается (крашится после выбора разрешения)
Lua:
--local inicfg = require 'inicfg'

local ffi = require("ffi")
ffi.cdef([[
    typedef unsigned long DWORD;

    struct d3ddeviceVTBL {
        void *QueryInterface;
        void *AddRef;
        void *Release;
        void *TestCooperativeLevel;
        void *GetAvailableTextureMem;
        void *EvictManagedResources;
        void *GetDirect3D;
        void *GetDeviceCaps;
        void *GetDisplayMode;
        void *GetCreationParameters;
        void *SetCursorProperties;
        void *SetCursorPosition;
        void *ShowCursor;
        void *CreateAdditionalSwapChain;
        void *GetSwapChain;
        void *GetNumberOfSwapChains;
        void *Reset;
        void *Present;
        void *GetBackBuffer;
        void *GetRasterStatus;
        void *SetDialogBoxMode;
        void *SetGammaRamp;
        void *GetGammaRamp;
        void *CreateTexture;
        void *CreateVolumeTexture;
        void *CreateCubeTexture;
        void *CreateVertexBuffer;
        void *CreateIndexBuffer;
        void *CreateRenderTarget;
        void *CreateDepthStencilSurface;
        void *UpdateSurface;
        void *UpdateTexture;
        void *GetRenderTargetData;
        void *GetFrontBufferData;
        void *StretchRect;
        void *ColorFill;
        void *CreateOffscreenPlainSurface;
        void *SetRenderTarget;
        void *GetRenderTarget;
        void *SetDepthStencilSurface;
        void *GetDepthStencilSurface;
        void *BeginScene;
        void *EndScene;
        void *Clear;
        void *SetTransform;
        void *GetTransform;
        void *MultiplyTransform;
        void *SetViewport;
        void *GetViewport;
        void *SetMaterial;
        void *GetMaterial;
        void *SetLight;
        void *GetLight;
        void *LightEnable;
        void *GetLightEnable;
        void *SetClipPlane;
        void *GetClipPlane;
        void *SetRenderState;
        void *GetRenderState;
        void *CreateStateBlock;
        void *BeginStateBlock;
        void *EndStateBlock;
        void *SetClipStatus;
        void *GetClipStatus;
        void *GetTexture;
        void *SetTexture;
        void *GetTextureStageState;
        void *SetTextureStageState;
        void *GetSamplerState;
        void *SetSamplerState;
        void *ValidateDevice;
        void *SetPaletteEntries;
        void *GetPaletteEntries;
        void *SetCurrentTexturePalette;
        void *GetCurrentTexturePalette;
        void *SetScissorRect;
        void *GetScissorRect;
        void *SetSoftwareVertexProcessing;
        void *GetSoftwareVertexProcessing;
        void *SetNPatchMode;
        void *GetNPatchMode;
        void *DrawPrimitive;
        void* DrawIndexedPrimitive;
        void *DrawPrimitiveUP;
        void *DrawIndexedPrimitiveUP;
        void *ProcessVertices;
        void *CreateVertexDeclaration;
        void *SetVertexDeclaration;
        void *GetVertexDeclaration;
        void *SetFVF;
        void *GetFVF;
        void *CreateVertexShader;
        void *SetVertexShader;
        void *GetVertexShader;
        void *SetVertexShaderConstantF;
        void *GetVertexShaderConstantF;
        void *SetVertexShaderConstantI;
        void *GetVertexShaderConstantI;
        void *SetVertexShaderConstantB;
        void *GetVertexShaderConstantB;
        void *SetStreamSource;
        void *GetStreamSource;
        void *SetStreamSourceFreq;
        void *GetStreamSourceFreq;
        void *SetIndices;
        void *GetIndices;
        void *CreatePixelShader;
        void *SetPixelShader;
        void *GetPixelShader;
        void *SetPixelShaderConstantF;
        void *GetPixelShaderConstantF;
        void *SetPixelShaderConstantI;
        void *GetPixelShaderConstantI;
        void *SetPixelShaderConstantB;
        void *GetPixelShaderConstantB;
        void *DrawRectPatch;
        void *DrawTriPatch;
        void *DeletePatch;
    };

    struct d3ddevice {
        struct d3ddeviceVTBL** vtbl;
    };
]])



ffi.cast("void(__thiscall*)(void*)", 0x59F180)(ffi.cast("void*", pPed)) -- pPed - указатель на педа

function main()
    AddPlayerToChamsQuery(PLAYER_PED, 0xFFAABB00)
    wait(-1)
end

local ChamsQuery = {
}

function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

function RemoveFromChamsQuery(handle)
    ChamsQuery.remove(handle)
end

function onD3DPresent()
    local pDevice = ffi.cast("struct d3ddevice*", 0xC97C28)
    local SetTextureStageState =  ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned long)", pDevice.vtbl[0].SetTextureStageState)
    local GetTextureStageState =  ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned int*)", pDevice.vtbl[0].GetTextureStageState)

    local dwConstant = ffi.new("unsigned int[1]")
    local dwARG0 = ffi.new("unsigned int[1]")
    local dwARG1 = ffi.new("unsigned int[1]")
    local dwARG2 = ffi.new("unsigned int[1]")
    for key, color in pairs(ChamsQuery) do
        local pPed = getCharPointer(key)
        if pPed ~= 0 then
            GetTextureStageState(pDevice, 0, 32, dwConstant)
            GetTextureStageState(pDevice, 0, 26, dwARG0)
            GetTextureStageState(pDevice, 0, 2,  dwARG1)
            GetTextureStageState(pDevice, 0, 3,  dwARG2)
            SetTextureStageState(pDevice, 0, 32, color)
            SetTextureStageState(pDevice, 0, 26, 6)
            SetTextureStageState(pDevice, 0, 2,  6)
            SetTextureStageState(pDevice, 0, 3,  6)
        
            ffi.cast("void(__thiscall*)(void*)", 0x59F180)(ffi.cast("void*", pPed))
        
            SetTextureStageState(pDevice, 0, 32, dwConstant[0])
            SetTextureStageState(pDevice, 0, 26, dwARG0[0])
            SetTextureStageState(pDevice, 0, 2,  dwARG1[0])
            SetTextureStageState(pDevice, 0, 3,  dwARG2[0])
        end
    end
end
 

wulfandr

Известный
637
260
так у меня вообще сам не запускается (крашится после выбора разрешения)
Lua:
--local inicfg = require 'inicfg'

local ffi = require("ffi")
ffi.cdef([[
    typedef unsigned long DWORD;

    struct d3ddeviceVTBL {
        void *QueryInterface;
        void *AddRef;
        void *Release;
        void *TestCooperativeLevel;
        void *GetAvailableTextureMem;
        void *EvictManagedResources;
        void *GetDirect3D;
        void *GetDeviceCaps;
        void *GetDisplayMode;
        void *GetCreationParameters;
        void *SetCursorProperties;
        void *SetCursorPosition;
        void *ShowCursor;
        void *CreateAdditionalSwapChain;
        void *GetSwapChain;
        void *GetNumberOfSwapChains;
        void *Reset;
        void *Present;
        void *GetBackBuffer;
        void *GetRasterStatus;
        void *SetDialogBoxMode;
        void *SetGammaRamp;
        void *GetGammaRamp;
        void *CreateTexture;
        void *CreateVolumeTexture;
        void *CreateCubeTexture;
        void *CreateVertexBuffer;
        void *CreateIndexBuffer;
        void *CreateRenderTarget;
        void *CreateDepthStencilSurface;
        void *UpdateSurface;
        void *UpdateTexture;
        void *GetRenderTargetData;
        void *GetFrontBufferData;
        void *StretchRect;
        void *ColorFill;
        void *CreateOffscreenPlainSurface;
        void *SetRenderTarget;
        void *GetRenderTarget;
        void *SetDepthStencilSurface;
        void *GetDepthStencilSurface;
        void *BeginScene;
        void *EndScene;
        void *Clear;
        void *SetTransform;
        void *GetTransform;
        void *MultiplyTransform;
        void *SetViewport;
        void *GetViewport;
        void *SetMaterial;
        void *GetMaterial;
        void *SetLight;
        void *GetLight;
        void *LightEnable;
        void *GetLightEnable;
        void *SetClipPlane;
        void *GetClipPlane;
        void *SetRenderState;
        void *GetRenderState;
        void *CreateStateBlock;
        void *BeginStateBlock;
        void *EndStateBlock;
        void *SetClipStatus;
        void *GetClipStatus;
        void *GetTexture;
        void *SetTexture;
        void *GetTextureStageState;
        void *SetTextureStageState;
        void *GetSamplerState;
        void *SetSamplerState;
        void *ValidateDevice;
        void *SetPaletteEntries;
        void *GetPaletteEntries;
        void *SetCurrentTexturePalette;
        void *GetCurrentTexturePalette;
        void *SetScissorRect;
        void *GetScissorRect;
        void *SetSoftwareVertexProcessing;
        void *GetSoftwareVertexProcessing;
        void *SetNPatchMode;
        void *GetNPatchMode;
        void *DrawPrimitive;
        void* DrawIndexedPrimitive;
        void *DrawPrimitiveUP;
        void *DrawIndexedPrimitiveUP;
        void *ProcessVertices;
        void *CreateVertexDeclaration;
        void *SetVertexDeclaration;
        void *GetVertexDeclaration;
        void *SetFVF;
        void *GetFVF;
        void *CreateVertexShader;
        void *SetVertexShader;
        void *GetVertexShader;
        void *SetVertexShaderConstantF;
        void *GetVertexShaderConstantF;
        void *SetVertexShaderConstantI;
        void *GetVertexShaderConstantI;
        void *SetVertexShaderConstantB;
        void *GetVertexShaderConstantB;
        void *SetStreamSource;
        void *GetStreamSource;
        void *SetStreamSourceFreq;
        void *GetStreamSourceFreq;
        void *SetIndices;
        void *GetIndices;
        void *CreatePixelShader;
        void *SetPixelShader;
        void *GetPixelShader;
        void *SetPixelShaderConstantF;
        void *GetPixelShaderConstantF;
        void *SetPixelShaderConstantI;
        void *GetPixelShaderConstantI;
        void *SetPixelShaderConstantB;
        void *GetPixelShaderConstantB;
        void *DrawRectPatch;
        void *DrawTriPatch;
        void *DeletePatch;
    };

    struct d3ddevice {
        struct d3ddeviceVTBL** vtbl;
    };
]])



ffi.cast("void(__thiscall*)(void*)", 0x59F180)(ffi.cast("void*", pPed)) -- pPed - указатель на педа

function main()
    AddPlayerToChamsQuery(PLAYER_PED, 0xFFAABB00)
    wait(-1)
end

local ChamsQuery = {
}

function AddPlayerToChamsQuery(handle, color)
    ChamsQuery[handle] = color
end

function RemoveFromChamsQuery(handle)
    ChamsQuery.remove(handle)
end

function onD3DPresent()
    local pDevice = ffi.cast("struct d3ddevice*", 0xC97C28)
    local SetTextureStageState =  ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned long)", pDevice.vtbl[0].SetTextureStageState)
    local GetTextureStageState =  ffi.cast("long(__stdcall*)(void*, unsigned long, unsigned long, unsigned int*)", pDevice.vtbl[0].GetTextureStageState)

    local dwConstant = ffi.new("unsigned int[1]")
    local dwARG0 = ffi.new("unsigned int[1]")
    local dwARG1 = ffi.new("unsigned int[1]")
    local dwARG2 = ffi.new("unsigned int[1]")
    for key, color in pairs(ChamsQuery) do
        local pPed = getCharPointer(key)
        if pPed ~= 0 then
            GetTextureStageState(pDevice, 0, 32, dwConstant)
            GetTextureStageState(pDevice, 0, 26, dwARG0)
            GetTextureStageState(pDevice, 0, 2,  dwARG1)
            GetTextureStageState(pDevice, 0, 3,  dwARG2)
            SetTextureStageState(pDevice, 0, 32, color)
            SetTextureStageState(pDevice, 0, 26, 6)
            SetTextureStageState(pDevice, 0, 2,  6)
            SetTextureStageState(pDevice, 0, 3,  6)
       
            ffi.cast("void(__thiscall*)(void*)", 0x59F180)(ffi.cast("void*", pPed))
       
            SetTextureStageState(pDevice, 0, 32, dwConstant[0])
            SetTextureStageState(pDevice, 0, 26, dwARG0[0])
            SetTextureStageState(pDevice, 0, 2,  dwARG1[0])
            SetTextureStageState(pDevice, 0, 3,  dwARG2[0])
        end
    end
end
ffi.cast("void(__thiscall*)(void*)", 0x59F180)(ffi.cast("void*", pPed)) -- pPed - указатель на педа

это тоже убери вне функции