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

F0RQU1N and

Известный
1,305
497
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("bla bla", -1)
      sampRegisterChatCommand("debind", debind)
      sampRegisterChatCommand("mkabind", mka)
      sampRegisterChatCommand("ribind", ribind)
end

function mka(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x32) then
            sampSendChat('/m4 100')
        end
    end
end

function debind(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x31) then
            sampSendChat('/de 50')
        end
    end
end

function ribind()
    while true do
        wait(0)
        if isKeyJustPressed(0x33) then
            sampSendChat('/ri 20')
        end
    end
end

почему не работает
 

_razor

t.me/sssecretway | ТГК: t.me/razor_code
Всефорумный модератор
1,953
3,231
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("bla bla", -1)
      sampRegisterChatCommand("debind", debind)
      sampRegisterChatCommand("mkabind", mka)
      sampRegisterChatCommand("ribind", ribind)
end

function mka(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x32) then
            sampSendChat('/m4 100')
        end
    end
end

function debind(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x31) then
            sampSendChat('/de 50')
        end
    end
end

function ribind()
    while true do
        wait(0)
        if isKeyJustPressed(0x33) then
            sampSendChat('/ri 20')
        end
    end
end

почему не работает
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("bla bla", -1)
      sampRegisterChatCommand("debind", debind)
      sampRegisterChatCommand("mkabind", mka)
      sampRegisterChatCommand("ribind", ribind)
      wait(-1)
end

function mka(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x32) then
            sampSendChat('/m4 100')
        end
    end
end

function debind(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x31) then
            sampSendChat('/de 50')
        end
    end
end

function ribind()
    while true do
        wait(0)
        if isKeyJustPressed(0x33) then
            sampSendChat('/ri 20')
        end
    end
end
 

Izvinisb

Известный
Проверенный
963
601
Lua:
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("bla bla", -1)
      sampRegisterChatCommand("debind", debind)
      sampRegisterChatCommand("mkabind", mka)
      sampRegisterChatCommand("ribind", ribind)
      wait(-1)
end

function mka(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x32) then
            sampSendChat('/m4 100')
        end
    end
end

function debind(arg)
    while true do
        wait(0)
        if isKeyJustPressed(0x31) then
            sampSendChat('/de 50')
        end
    end
end

function ribind()
    while true do
        wait(0)
        if isKeyJustPressed(0x33) then
            sampSendChat('/ri 20')
        end
    end
end
Поток не нужен?
 
  • Bug
Реакции: _razor

MR_Lua

Участник
41
0
Как правильно сделать, чтобы при нажатии на кнопку отыгрывалось РП действие?

Lua:
imgui.Text(u8'Все отыгровки разделены по пунктам, для каждого действия.')
if imgui.CollapsingHeader(u8'Отыгровки для похищений') then
    imgui.Button(u8'Надеть мешок на голову')
end
 

Dmitriy Makarov

25.05.2021
Проверенный
2,508
1,136
Как правильно сделать, чтобы при нажатии на кнопку отыгрывалось РП действие?

Lua:
imgui.Text(u8'Все отыгровки разделены по пунктам, для каждого действия.')
if imgui.CollapsingHeader(u8'Отыгровки для похищений') then
    imgui.Button(u8'Надеть мешок на голову')
end
Lua:
if imgui.Button(u8'Надеть мешок на голову') then
    -- RP
end
 

Chiba

Известный
25
1
Возможно ли не прорисовывать NameTag какого-либо персонажа? По ID или по нику, например.
 

F0RQU1N and

Известный
1,305
497
как сделать чтобы когда ты в тачке по нажатию клавиш ты вставал в афк у других и не мог двигатся?
 

Pashyka

Участник
220
17
Здравствуйте, у меня есть многострочное поле
Lua:
imgui.InputTextMultiline("", sobes)
Загружаю поле так
Lua:
local sobes = imgui.ImBuffer(mainIni.config.sobes:gsub("&", "\n"), 1024)
Сохраняю так
Lua:
mainIni.config.sobes = sobes.v:gsub("\n", "&")

Так вот, мне нужно, чтобы все строчки отправлялись с интервалом указанным в самой же строчке. к примеру строка
Привет
Как дела
Что делаешь?

отправлялась в 3 сообщения

Пробую отправлять по команде, не получается...

Lua:
function cmd_easy(arg)
    lua_thread.create(function()
        local strings = split(sobes, '\n', false)
        for i,g in ipairs(strings) do
            sampSendChat("/c " .. g)
            wait(6000)
        end
    end)
end
 

yarsuetolog

Участник
67
7
Нужно при открытии имгуи окна убирать курсор и отключать возможность какие-либо действия в нем мышкой, поможете?
 

lorgon

Известный
656
272
не очень в тему (%w+_?%w+), оно ищет так-то РП ник, а вдруг таксист с нрп ником?)

Lua:
if YourWindow.v then
    imgui.ShowCursor = false
end
Можно такую регулировку сделать:
local id, msg = message:match('%[Такси%].*%[(%d+)%]:(.*)')
Как сделать вертикальную линию в имгуи?
В полезных сниппетах была
Lua:
function imgui.VerticalSeparator()
    local p = imgui.GetCursorScreenPos()
    imgui.GetWindowDrawList():AddLine(imgui.ImVec2(p.x, p.y), imgui.ImVec2(p.x, p.y + imgui.GetContentRegionMax().y), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.Separator]))
end
 

trefa

3d print
Всефорумный модератор
2,121
1,288
Почему не работает?
Lua:
time = os.clock()
       
        if active_report then
            if not isKeyJustPressed(VK_K) then
                if time == "1" then
                    printStyledString('Forma wait 10', 1000, 4)
                end
                if time == "2" then
                    printStyledString('Forma wait 9', 1000, 4)
                end
                if time == "3" then
                    printStyledString('Forma wait 8', 1000, 4)
                end
                if time == "4" then
                    printStyledString('Forma wait 7', 1000, 4)
                end
                if time == "5" then
                    printStyledString('Forma wait 6', 1000, 4)
                end
                if time == "6" then
                    printStyledString('Forma wait 5', 1000, 4)
                end
                if time == "7" then
                    printStyledString('Forma wait 4', 1000, 4)
                end
                if time == "8" then                                      
                    printStyledString('Forma wait 3', 1000, 4)
                end
                if time == "9" then
                    printStyledString('Forma wait 2', 1000, 4)
                end
                if time == "10" then
                    printStyledString('Forma wait 1', 1000, 4)
                end
                if time == "11" then
                    printStyledString('The form is automatically skipped', 1000, 4)
                    active_report = false
                end
            elseif isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() then
                sampSendChat("/"..cmd.." "..other.." || "..admin_nick)
                active_report = false
            end
        end
Потому что time = number но time ~= string