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

g305noobo

Известный
Модератор
318
531
как эмулировать нажатие лкм по синхре?
Lua:
function samp_create_sync_data(sync_type, copy_from_player)
    local ffi = require 'ffi'
    local sampfuncs = require 'sampfuncs'
    -- from SAMP.Lua
    local raknet = require 'samp.raknet'
    require 'samp.synchronization'

    copy_from_player = copy_from_player or true
    local sync_traits = {
        player = {'PlayerSyncData', raknet.PACKET.PLAYER_SYNC, sampStorePlayerOnfootData},
        vehicle = {'VehicleSyncData', raknet.PACKET.VEHICLE_SYNC, sampStorePlayerIncarData},
        passenger = {'PassengerSyncData', raknet.PACKET.PASSENGER_SYNC, sampStorePlayerPassengerData},
        aim = {'AimSyncData', raknet.PACKET.AIM_SYNC, sampStorePlayerAimData},
        trailer = {'TrailerSyncData', raknet.PACKET.TRAILER_SYNC, sampStorePlayerTrailerData},
        unoccupied = {'UnoccupiedSyncData', raknet.PACKET.UNOCCUPIED_SYNC, nil},
        bullet = {'BulletSyncData', raknet.PACKET.BULLET_SYNC, nil},
        spectator = {'SpectatorSyncData', raknet.PACKET.SPECTATOR_SYNC, nil}
    }
    local sync_info = sync_traits[sync_type]
    local data_type = 'struct ' .. sync_info[1]
    local data = ffi.new(data_type, {})
    local raw_data_ptr = tonumber(ffi.cast('uintptr_t', ffi.new(data_type .. '*', data)))
    -- copy player's sync data to the allocated memory
    if copy_from_player then
        local copy_func = sync_info[3]
        if copy_func then
            local _, player_id
            if copy_from_player == true then
                _, player_id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            else
                player_id = tonumber(copy_from_player)
            end
            copy_func(player_id, raw_data_ptr)
        end
    end
    -- function to send packet
    local func_send = function()
        local bs = raknetNewBitStream()
        raknetBitStreamWriteInt8(bs, sync_info[2])
        raknetBitStreamWriteBuffer(bs, raw_data_ptr, ffi.sizeof(data))
        raknetSendBitStreamEx(bs, sampfuncs.HIGH_PRIORITY, sampfuncs.UNRELIABLE_SEQUENCED, 1)
        raknetDeleteBitStream(bs)
    end
    -- metatable to access sync data and 'send' function
    local mt = {
        __index = function(t, index)
            return data[index]
        end,
        __newindex = function(t, index, value)
            data[index] = value
        end
    }
    return setmetatable({send = func_send}, mt)
end

function send_lmb()
    local data = samp_create_sync_data('player')
    data.keysData = data.keysData + 4
    data.send()
end

для других кнопок тут data.keysData = data.keysData + 4 можешь заменить на что-то отсюда
Код:
Y = gunid + 64
F =keydata + 16
H = gunid + 192
C = keydata + 2
N = gunid + 128
LMB = keydata + 4
RMB = keydata + 128
TAB = keydata + 1
SPRINT = keydata +8
ALT = keydata + 1024
JUMP = keydata + 32
 

uvie

Известный
273
54
Lua:
local sampev = require 'lib.samp.events'

require 'lib.moonloader'

local act = false

function main()
    while not isSampAvailable() do
        wait(0)
    end
    sampRegisterChatCommand('vaz', function()
        act = not act
        sampAddChatMessage(act and '{e53939}RLS.LT AUTO VAZIUOJU {ffffff}IJUNGTA' or '{e53939}RLS.LT AUTO VAZIUOJU {ffffff}ISJUNGTA', -1)

    end)

    while true do
        wait(0)

    end
end

local laukimas = 1000

function sampev.onServerMessage(color, text)
    if act and text:find('Gavome iškvietimą nuo .+%[%d+%], žaidėjas pažymėtas auksine spalva%. Naudok /vaziuoju%.') then
        lua_thread.create(function()
            wait(1000)
            sampSendChat('/vaziuoju')
        end)
    end
end

[23:30:41] [R] [Dispečerinė]: {def01f}Gavome iškvietimą nuo Samperis_Dry[49], žaidėjas pažymėtas auksine spalva. Naudok /vaziuoju.

command script work's but script doesnt type /vaziuoju auto
 

Enlizmee

Активный
497
103
Lua:
function samp_create_sync_data(sync_type, copy_from_player)
    local ffi = require 'ffi'
    local sampfuncs = require 'sampfuncs'
    -- from SAMP.Lua
    local raknet = require 'samp.raknet'
    require 'samp.synchronization'

    copy_from_player = copy_from_player or true
    local sync_traits = {
        player = {'PlayerSyncData', raknet.PACKET.PLAYER_SYNC, sampStorePlayerOnfootData},
        vehicle = {'VehicleSyncData', raknet.PACKET.VEHICLE_SYNC, sampStorePlayerIncarData},
        passenger = {'PassengerSyncData', raknet.PACKET.PASSENGER_SYNC, sampStorePlayerPassengerData},
        aim = {'AimSyncData', raknet.PACKET.AIM_SYNC, sampStorePlayerAimData},
        trailer = {'TrailerSyncData', raknet.PACKET.TRAILER_SYNC, sampStorePlayerTrailerData},
        unoccupied = {'UnoccupiedSyncData', raknet.PACKET.UNOCCUPIED_SYNC, nil},
        bullet = {'BulletSyncData', raknet.PACKET.BULLET_SYNC, nil},
        spectator = {'SpectatorSyncData', raknet.PACKET.SPECTATOR_SYNC, nil}
    }
    local sync_info = sync_traits[sync_type]
    local data_type = 'struct ' .. sync_info[1]
    local data = ffi.new(data_type, {})
    local raw_data_ptr = tonumber(ffi.cast('uintptr_t', ffi.new(data_type .. '*', data)))
    -- copy player's sync data to the allocated memory
    if copy_from_player then
        local copy_func = sync_info[3]
        if copy_func then
            local _, player_id
            if copy_from_player == true then
                _, player_id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            else
                player_id = tonumber(copy_from_player)
            end
            copy_func(player_id, raw_data_ptr)
        end
    end
    -- function to send packet
    local func_send = function()
        local bs = raknetNewBitStream()
        raknetBitStreamWriteInt8(bs, sync_info[2])
        raknetBitStreamWriteBuffer(bs, raw_data_ptr, ffi.sizeof(data))
        raknetSendBitStreamEx(bs, sampfuncs.HIGH_PRIORITY, sampfuncs.UNRELIABLE_SEQUENCED, 1)
        raknetDeleteBitStream(bs)
    end
    -- metatable to access sync data and 'send' function
    local mt = {
        __index = function(t, index)
            return data[index]
        end,
        __newindex = function(t, index, value)
            data[index] = value
        end
    }
    return setmetatable({send = func_send}, mt)
end

function send_lmb()
    local data = samp_create_sync_data('player')
    data.keysData = data.keysData + 4
    data.send()
end

для других кнопок тут data.keysData = data.keysData + 4 можешь заменить на что-то отсюда
Код:
Y = gunid + 64
F =keydata + 16
H = gunid + 192
C = keydata + 2
N = gunid + 128
LMB = keydata + 4
RMB = keydata + 128
TAB = keydata + 1
SPRINT = keydata +8
ALT = keydata + 1024
JUMP = keydata + 32
можно как-то синхру гранат отправить?
 

Jefferson.!2.

Новичок
22
1
Этот код отключает выбор класса, но как отключить курсор?

Lua:
local memory = require('memory')
local samp = getModuleHandle("samp.dll")
local bEnable = true;
function enableClassSelection(bValue)
    local pClassSelection = memory.getuint32(samp + 0x21A18C, true)
    memory.setint8(pClassSelection + 0x13, bValue, true)
end
function main()
    while not isSampAvailable() do wait(0) end
    while true do
        wait(0)
        if wasKeyPressed(49) then
            bEnable = not bEnable
            enableClassSelection(bEnable and 1 or 0)
        end
    end
end
sampToggleCursor(bool show) Не сработало, мышь всегда возвращается в центр экрана.
showCursor(bool show, [bool lockControls=false]) Не дало никакого эффекта.

263511
 

copypaste_scripter

Известный
1,322
262
я глупи гавнокодер, как сделать чтобы текст оставался на экране. с этим скриптом текст появляется раз в секунду на пару милисекунд и прятается. и еще как сделать чтобы отсчет щел с 120 к 0

Lua:
require "lib.moonloader"
local sampev = require "lib.samp.events"
local font_flag = require('moonloader').font_flag
local my_font = renderCreateFont('JetBrains Mono Medium', 34, font_flag.BOLD + font_flag.BORDER)
local oX = 700--/1.4
local oY = 700--/1.4
local cd = false

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

    sampAddChatMessage("myflood", -1)
    
    sampRegisterChatCommand("wd", function()
        lua_thread.create(function()
            sampSendChat("aoaoao")
            wait(500)
            cd = true
        end)
    end)


    while true do
        wait(0)
        if cd == true then
            for i = 1, 120 do
                local timertext = i
                wait(1000)
                renderFontDrawText(my_font, timertext, oX - (renderGetFontDrawTextLength(my_font, timertext))/2, oY, 0xFFFFFFFF)
            end
            cd = false
        end
    end
end
 
  • Ха-ха
Реакции: Andrinall

kriksson

Новичок
11
6
я глупи гавнокодер, как сделать чтобы текст оставался на экране. с этим скриптом текст появляется раз в секунду на пару милисекунд и прятается. и еще как сделать чтобы отсчет щел с 120 к 0

Lua:
require "lib.moonloader"
local sampev = require "lib.samp.events"
local font_flag = require('moonloader').font_flag
local my_font = renderCreateFont('JetBrains Mono Medium', 34, font_flag.BOLD + font_flag.BORDER)
local oX = 700--/1.4
local oY = 700--/1.4
local cd = false

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

    sampAddChatMessage("myflood", -1)
   
    sampRegisterChatCommand("wd", function()
        lua_thread.create(function()
            sampSendChat("aoaoao")
            wait(500)
            cd = true
        end)
    end)


    while true do
        wait(0)
        if cd == true then
            for i = 1, 120 do
                local timertext = i
                wait(1000)
                renderFontDrawText(my_font, timertext, oX - (renderGetFontDrawTextLength(my_font, timertext))/2, oY, 0xFFFFFFFF)
            end
            cd = false
        end
    end
end
vahue:
require "lib.moonloader"
local sampev = require "lib.samp.events"
local font_flag = require('moonloader').font_flag
local my_font = renderCreateFont('JetBrains Mono Medium', 34, font_flag.BOLD + font_flag.BORDER)
local oX, oY = 700, 700
local cd, timertext = false, 0

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

    sampAddChatMessage("myflood", -1)
    
    sampRegisterChatCommand("wd", function()
        if not cd then
            lua_thread.create(function()
                sampSendChat("aoaoao")
                cd = true
                for i = 120, 0, -1 do
                    timertext = i
                    wait(1000)
                end
                cd = false
            end)
        end
    end)

    while true do
        wait(0)
        if cd then
            renderFontDrawText(my_font, tostring(timertext), oX - (renderGetFontDrawTextLength(my_font, tostring(timertext)))/2, oY, 0xFFFFFFFF)
        end
    end
end
 
  • Нравится
Реакции: copypaste_scripter

meowprd

Тот самый Котовский
Проверенный
1,302
731
я глупи гавнокодер, как сделать чтобы текст оставался на экране. с этим скриптом текст появляется раз в секунду на пару милисекунд и прятается. и еще как сделать чтобы отсчет щел с 120 к 0

Lua:
require "lib.moonloader"
local sampev = require "lib.samp.events"
local font_flag = require('moonloader').font_flag
local my_font = renderCreateFont('JetBrains Mono Medium', 34, font_flag.BOLD + font_flag.BORDER)
local oX = 700--/1.4
local oY = 700--/1.4
local cd = false

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

    sampAddChatMessage("myflood", -1)
  
    sampRegisterChatCommand("wd", function()
        lua_thread.create(function()
            sampSendChat("aoaoao")
            wait(500)
            cd = true
        end)
    end)


    while true do
        wait(0)
        if cd == true then
            for i = 1, 120 do
                local timertext = i
                wait(1000)
                renderFontDrawText(my_font, timertext, oX - (renderGetFontDrawTextLength(my_font, timertext))/2, oY, 0xFFFFFFFF)
            end
            cd = false
        end
    end
end
Данный код будет более корректный и не будет зависеть от кадров и/или фризов игры, если сравнивать с ответом выше (использование цикла в отдельном потоке)
Не проверял, написано на коленке
Lua:
require "lib.moonloader"
local sampev = require "lib.samp.events"
local font_flag = require('moonloader').font_flag
local my_font = renderCreateFont('JetBrains Mono Medium', 34, font_flag.BOLD + font_flag.BORDER)
local oX = 700--/1.4
local oY = 700--/1.4
-- local cd = false
local renderTimer = os.clock()

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

    sampAddChatMessage("myflood", -1)
   
    sampRegisterChatCommand("wd", function()
        lua_thread.create(function()
            sampSendChat("aoaoao")
            wait(500)
            renderTimer = os.clock() + 120
        end)
    end)


    while true do
        wait(0)

        if renderTimer > os.clock() then
            local s = tostring((renderTimer - os.clock()) > 0 and math.floor(renderTimer - os.clock()) or 0)
            renderFontDrawText(my_font, s, oX - (renderGetFontDrawTextLength(my_font, s))/2, oY, 0xFFFFFFFF)
        end
    end
end
 

Enlizmee

Активный
497
103

как отправить самому себе урон?
 
Последнее редактирование:

Enlizmee

Активный
497
103
как можно по синхре отправить гранаты и чтобы прошел урон от нее? Примерный код
 

chromiusj

Стань той переменой, которую хочешь увидеть в мире
Модератор
5,732
4,032
как можно по синхре отправить гранаты и чтобы прошел урон от нее? Примерный код
тебе нужно в синхре оружие менять и кейсдату
примеры
 
  • Нравится
Реакции: Enlizmee

Enlizmee

Активный
497
103
тебе нужно в синхре оружие менять и кейсдату
примеры
А если в руке граната будет?
 

.Oinoas

Новичок
6
0
error occur the same or a different one?
After turning on,if get an error surfingVehicle ID,an error will be reported

error:
[19:36:14.135761] (error)    test.lua: F:\GTA San Andreas\moonloader\test.lua:592: attempt to compare nil with number
stack traceback:
    F:\GTA San Andreas\moonloader\test.lua:592: in function 'callback'
    ...\GTA San Andreas\moonloader\lib\samp\events\core.lua:77: in function 'process_event'
    ...\GTA San Andreas\moonloader\lib\samp\events\core.lua:100: in function 'process_packet'
    ...\GTA San Andreas\moonloader\lib\samp\events\core.lua:131: in function <...\GTA San Andreas\moonloader\lib\samp\events\core.lua:130>
 

meowprd

Тот самый Котовский
Проверенный
1,302
731
After turning on,if get an error surfingVehicle ID,an error will be reported

error:
[19:36:14.135761] (error)    test.lua: F:\GTA San Andreas\moonloader\test.lua:592: attempt to compare nil with number
stack traceback:
    F:\GTA San Andreas\moonloader\test.lua:592: in function 'callback'
    ...\GTA San Andreas\moonloader\lib\samp\events\core.lua:77: in function 'process_event'
    ...\GTA San Andreas\moonloader\lib\samp\events\core.lua:100: in function 'process_packet'
    ...\GTA San Andreas\moonloader\lib\samp\events\core.lua:131: in function <...\GTA San Andreas\moonloader\lib\samp\events\core.lua:130>
Sorry for the confusion, it's my mistake. According to the documentation surfingVehicle ID may not exist (== nil)
Lua:
function event.onPlayerSync(id, data)
    if state and (data.surfingVehicleId and data.surfingVehicleId or 0) >= 2000 then
        sampAddChatMessage(string.format("Wrong SurfingVehicle ID[%d]", tonumber(data.surfingVehicleId)), -1)
    end
end
U can try corrected code, it should work
 
  • Нравится
Реакции: .Oinoas