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

DZONE

Известный
187
199
Приветствую, работа с сампом, дана строка с текстом(их много видов):
[Gasha] У Nick_Name[74] случился сердечный приступ
[Gasha] Nick_Name[74] случился сердечный приступ
[Gasha] у Nick_Name[74] случился сердечный приступ

Каким образом мне вывести с данной строки именно id игрока и занести его в переменную.
Нужно чтобы оно автоматом при обнаружение данной строки выполняло определенные действия

sampSendChat(/'heal' .. id) -- Чисто к примеру
Lua:
function sampev.onServerMessage(color, text)
    if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
        local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
        sampSendChat("/heal "..hid)
    end
end
 
  • Нравится
Реакции: AvAll

whyega52

Eblang головного мозга
Модератор
2,838
2,783
Как сделать что-то типа ToggleButton в mimgui?
 

Rice.

Известный
Модератор
1,753
1,653
Как сделать что-то типа ToggleButton в mimgui?
 
  • Нравится
Реакции: whyega52

Gorskin

🖕
Проверенный
1,349
1,200
Есть хук
Lua:
do
    local org_addEventHandler = addEventHandler
    local hkPresentQueueu = {}
    function hkPresent(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)
        for i, f in ipairs(hkPresentQueueu) do
            f()
        end
        
        return hkPresent(pDevice, pSourceRect, pDestRect, hDestWindowOverride, pDirtyRegion)
    end
    local D3D9Device = vmt_hook.new(ffi.cast('intptr_t*', 0xC97C28)[0])
    hkPresent = D3D9Device.hookMethod('long(__stdcall*)(void*, void*, void*, void*, void*)', hkPresent, 17) 
    function addEventHandler(event, func)
        if event == "onD3DPresent" then
            table.insert(hkPresentQueueu, func)
        else
            return org_addEventHandler(event, func)
        end
    end
end

Как мне использовать метод IDirect3DDevice9Ex::SetMaximumFrameLatency в этом хуке?
 

Julimba

Участник
108
10
В чем проблема? Попросту не запускается.
Lua:
require "lib.moonloader"
local keys = require "vkeys"

local tag = {3CB371}[Лечилка]
local main_color = 0xFFFFFF

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailble() do wait(100) end
       
        sampAddChatMessage(tag .. " Скрипт успешно {008000}запущен", main_color)
        sampAddChatMessage(tag .. " Чтобы использовать скрипт нажмите {0066FF}NumPad3.{FFFFFF}. Удачи!", main_color)
   
    while true do
        wait(0)
        if isKeyJustPressed(99) then
    if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
        local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
        sampSendChat("/heal "..hid)
        end
     end          
end
 

chapo

tg/inst: @moujeek
Модератор
9,073
12,042
помогите пж копировать текст текстдравов в массив. у меня чота не работает, копирует nil, чо не так делаю?
Lua:
local array = {440,442,444,446,448,450,452,454,456,458}
local text = {}
for i = 1, #array do
    result = sampTextdrawIsExists(array[i])
    if result then
        sampTextdrawSetLetterSizeAndColor(array[i], 0, 0, -1)
        local 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 = sampTextdrawGetString(array[i])
        table.insert(text, {1 = 1, 2 = 2, 3 = 3, 4 = 4, 5 = 5, 6 = 6, 7 = 7, 8 = 8, 9 = 9, 10 = 10})
    end
end
1. это так не работает, sampTextdrawGetString возвращает только 1 значение
2. переменные не могут называться цифрами (вернее нельзя что бы цифра была первым символом в названии переменной)
3. еще много ошибок о которых мне лень писать
Lua:
local array = { 440,442,444,446,448,450,452,454,456,458 }
local text = {}
for index, id in ipairs(array) do
    if sampTextdrawIsExists(id) then
        sampTextdrawSetLetterSizeAndColor(id, 0, 0, -1)
        table.insert(text, sampTextdrawGetString(id))
    end
end
-- а лучше вообще так:
local Textdraw = {
    [440] = 'none',
    [442] = 'none',
    [444] = 'none',
    [446] = 'none',
    [448] = 'none',
    [450] = 'none',
    [452] = 'none',
    [454] = 'none',
    [456] = 'none',
    [458] = 'none'
}
for id, text in pairs(Textdraw) do
    if sampTextdrawIsExists(id) then
        sampTextdrawSetLetterSizeAndColor(id, 0, 0, -1)
        Textdraw[id] = sampTextdrawGetString(id)
    end
end
 

chapo

tg/inst: @moujeek
Модератор
9,073
12,042
В чем проблема? Попросту не запускается.
Lua:
require "lib.moonloader"
local keys = require "vkeys"

local tag = {3CB371}[Лечилка]
local main_color = 0xFFFFFF

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailble() do wait(100) end
      
        sampAddChatMessage(tag .. " Скрипт успешно {008000}запущен", main_color)
        sampAddChatMessage(tag .. " Чтобы использовать скрипт нажмите {0066FF}NumPad3.{FFFFFF}. Удачи!", main_color)
  
    while true do
        wait(0)
        if isKeyJustPressed(99) then
    if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
        local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
        sampSendChat("/heal "..hid)
        end
     end         
end
этот текст должен быть в кавычках
1664726905575.png
 

AugustTN

Известный
1,363
472
В чем проблема? Попросту не запускается.
Lua:
require "lib.moonloader"
local keys = require "vkeys"

local tag = {3CB371}[Лечилка]
local main_color = 0xFFFFFF

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailble() do wait(100) end
     
        sampAddChatMessage(tag .. " Скрипт успешно {008000}запущен", main_color)
        sampAddChatMessage(tag .. " Чтобы использовать скрипт нажмите {0066FF}NumPad3.{FFFFFF}. Удачи!", main_color)
 
    while true do
        wait(0)
        if isKeyJustPressed(99) then
    if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
        local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
        sampSendChat("/heal "..hid)
        end
     end        
end
Lua:
require "lib.moonloader"
local keys = require "vkeys"
local sampev = require 'samp.events'
local tag = "{3CB371}[Лечилка]"
local main_color = 0xFFFFFF

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailble() do wait(100) end
        
        sampAddChatMessage(tag .. " Скрипт успешно {008000}запущен", main_color)
        sampAddChatMessage(tag .. " Чтобы использовать скрипт нажмите {0066FF}NumPad3.{FFFFFF}. Удачи!", main_color)
    
    while true do
        wait(-1)
end
function sampev.onServerMessage(clr,text)
    if isKeyJustPressed(99) then
        if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
            local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
            sampSendChat("/heal "..hid)
        end
    end
end
Попробуй
 

AugustTN

Известный
1,363
472
Исправил, так же не запускается.
Lua:
require "lib.moonloader"
local keys = require "vkeys"
local sampev = require 'samp.events'
local tag = "{3CB371}[Лечилка]"
local main_color = 0xFFFFFF

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailble() do wait(100) end
       
        sampAddChatMessage(tag .. " Скрипт успешно {008000}запущен", main_color)
        sampAddChatMessage(tag .. " Чтобы использовать скрипт нажмите {0066FF}NumPad3.{FFFFFF}. Удачи!", main_color)
   
    while true do
        wait(-1)
end
function sampev.onServerMessage(clr,text)
    if isKeyJustPressed(99) then
        if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
            local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
            sampSendChat("/heal "..hid)
        end
    end
end
Попробуй
 

whyega52

Eblang головного мозга
Модератор
2,838
2,783
Почему пиздошит кар даже когда аирбрейк не включен, а когда включен, то кар улетает вверх
Lua:
        if AirBreak[0] then
            if isCharInAnyCar(PLAYER_PED) then
                local x, y, z = getCharCoordinates(PLAYER_PED)
                local x1, y1, z1 = getActiveCameraCoordinates()
                local head = math.rad(getHeadingFromVector2d(x-x1, y-y1))

                if isKeyDown(87) then
                    x = x-math.sin(-head+3.14)*air_speed_car[0]
                    y = y-math.cos(-head+3.14)*air_speed_car[0]
                elseif isKeyDown(83) then
                    x = x+math.sin(-head+3.14)*air_speed_car[0]
                    y = y+math.cos(-head+3.14)*air_speed_car[0]
                end
                
                if isKeyDown(65) then
                    local head = math.rad(math.deg(head)+90)
                    x = x-math.sin(-head+3.14)*air_speed_car[0]
                    y = y-math.cos(-head+3.14)*air_speed_car[0]
                elseif isKeyDown(68) then
                    local head = math.rad(math.deg(head)-90)
                    x = x-math.sin(-head+3.14)*air_speed_car[0]
                    y = y-math.cos(-head+3.14)*air_speed_car[0]
                end
                
                if isKeyDown(16) then
                    z = z-air_speed_car[0]
                elseif isKeyDown(32) then
                    z = z+air_speed_car[0]
                end

                setCarHeading(storeCarCharIsInNoSave(PLAYER_PED), math.deg(head))
                setCarCoordinates(storeCarCharIsInNoSave(PLAYER_PED), x, y, z)
            else
                local x, y, z = getCharCoordinates(PLAYER_PED)
                local x1, y1, z1 = getActiveCameraCoordinates()
                local head = math.rad(getHeadingFromVector2d(x-x1, y-y1))

                if isKeyDown(87) then
                    x = x-math.sin(-head+3.14)*air_speed_foot[0]
                    y = y-math.cos(-head+3.14)*air_speed_foot[0]
                elseif isKeyDown(83) then
                    x = x+math.sin(-head+3.14)*air_speed_foot[0]
                    y = y+math.cos(-head+3.14)*air_speed_foot[0]
                end
                
                if isKeyDown(65) then
                    local head = math.rad(math.deg(head)+90)
                    x = x-math.sin(-head+3.14)*air_speed_foot[0]
                    y = y-math.cos(-head+3.14)*air_speed_foot[0]
                elseif isKeyDown(68) then
                    local head = math.rad(math.deg(head)-90)
                    x = x-math.sin(-head+3.14)*air_speed_foot[0]
                    y = y-math.cos(-head+3.14)*air_speed_foot[0]
                end

                if isKeyDown(16) then
                    z = z-air_speed_foot[0]
                elseif isKeyDown(32) then
                    z = z+air_speed_foot[0]
                end
                
                setCharCollision(PLAYER_PED, false)
                setCharHeading(PLAYER_PED, math.deg(head))
                setCharCoordinates(PLAYER_PED, x, y, z-1)
            end
        end
        setCharCollision(PLAYER_PED, true)
    end
 

Julimba

Участник
108
10
Lua:
require "lib.moonloader"
local keys = require "vkeys"
local sampev = require 'samp.events'
local tag = "{3CB371}[Лечилка]"
local main_color = 0xFFFFFF

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailble() do wait(100) end
       
        sampAddChatMessage(tag .. " Скрипт успешно {008000}запущен", main_color)
        sampAddChatMessage(tag .. " Чтобы использовать скрипт нажмите {0066FF}NumPad3.{FFFFFF}. Удачи!", main_color)
   
    while true do
        wait(-1)
end
function sampev.onServerMessage(clr,text)
    if isKeyJustPressed(99) then
        if text:find("%[Gasha%] .* %w+_%w+%[.+%] случился .*") then
            local hid = text:match("%[Gasha%] .* %w+_%w+%[(.+)%] случился .*")
            sampSendChat("/heal "..hid)
        end
    end
end
Попробуй
Не работает, так же.