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

monolith04

Известный
69
6
что я не так написал?
script:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local settings_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)

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

  sampRegisterChatCommand("tester", cmd_tester)

  imgui.Process = false

end

while true do
    wait(0)

function cmd_imgui(arg)
    settings_window_state.v = not settings_window_state.v
    imgui.Process = settings_window_state.v
end
function imgui.OnDrawFrame()
  if settings_window_state.v then
        imgui.Begin("Меню", settings_window_state, 70)
        if imgui.Button("Test") then
            example_window_state.v = not example_window_state.v
        end
        imgui.End()
  end
    if example_window_state.v then
        imgui.Begin("Меню1", example_window_state)
        imgui.Text("Test")
        imgui.End()
    end
end
Ты забыл закрыть цикл на 23 строке.
Lua:
while true do
    wait(0)
end
 
  • Bug
Реакции: Next.. и F0RQU1N and

CaJlaT

Овощ
Модератор
2,807
2,609
Без цикла не уедешь, ты смотрел основы?
Не всегда он нужен. Если в скрипте есть хотя бы один хук, то цикл не нужен
Lua:
function main()
    sampRegisterChatCommand('zdarova', function() sampAddChatMessage('Ну привет', -1) end)
end
local samp = require 'samp.events'
function samp.onSendChat(text)
    if text:find('123') then
        sampAddChatMessage('321', -1)
    end
end

1629095744625.png

Также, этот цикл можно заменить простой задержкой на -1 мс, которая отправит скрипт в бесконечное ожидание
Lua:
function main()
    sampRegisterChatCommand('zdarova', function() sampAddChatMessage('Ну привет', 0xFF0000) end)
    wait(-1)
end
1629095869789.png
 

abnomegd

Активный
335
35
script:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local settings_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)

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

  sampRegisterChatCommand("tester", cmd_tester)

  imgui.Process = false

end

    while true do
        wait(0)

function cmd_tester(arg)
    settings_window_state.v = not settings_window_state.v
    imgui.Process = settings_window_state.v
end
function imgui.OnDrawFrame()
  if settings_window_state.v then
        imgui.Begin("Меню", settings_window_state, 70)
        if imgui.Button("Test") then
            example_window_state.v = not example_window_state.v
        end
        imgui.End()
  end
    if example_window_state.v then
        imgui.Begin("Меню1", example_window_state)
        imgui.Text("Test")
        imgui.End()
    end
end
 

Вложения

  • moonloader.log
    51.8 KB · Просмотры: 2

Gorskin

{Reverse Developer} ✓
Проверенный
1,251
1,054
script:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local settings_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)

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

  sampRegisterChatCommand("tester", cmd_tester)

  imgui.Process = false

end

    while true do
        wait(0)

function cmd_tester(arg)
    settings_window_state.v = not settings_window_state.v
    imgui.Process = settings_window_state.v
end
function imgui.OnDrawFrame()
  if settings_window_state.v then
        imgui.Begin("Меню", settings_window_state, 70)
        if imgui.Button("Test") then
            example_window_state.v = not example_window_state.v
        end
        imgui.End()
  end
    if example_window_state.v then
        imgui.Begin("Меню1", example_window_state)
        imgui.Text("Test")
        imgui.End()
    end
end
учи луа:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local sw, sh = getScreenResolution() -- узнаем размер экрана

local settings_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)

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

    sampRegisterChatCommand("tester", cmd_tester)

    imgui.Process = false

    while true do
        wait(0)
        
    end

end

function cmd_tester()
    settings_window_state.v = not settings_window_state.v
    imgui.Process = settings_window_state.v or example_window_state.v
end

function imgui.OnDrawFrame()
    if not settings_window_state.v then
        imgui.Process = false
    end -- если окно не активно то и процесс тоже будет не активен. После закрытия окна мышь пропадет.
    if settings_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver) -- устанавливаем размер окна
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- позиция окна
        imgui.Begin(u8"Меню", settings_window_state)
            if imgui.Button(u8"Test") then
                example_window_state.v = not example_window_state.v
            end
        imgui.End()
    end
    if example_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 5), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8"Меню1", example_window_state)
            imgui.Text(u8"Test")

        imgui.End()
    end
end
 
  • Нравится
Реакции: abnomegd

abnomegd

Активный
335
35
учи луа:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local sw, sh = getScreenResolution() -- узнаем размер экрана

local settings_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)

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

    sampRegisterChatCommand("tester", cmd_tester)

    imgui.Process = false

    while true do
        wait(0)
       
    end

end

function cmd_tester()
    settings_window_state.v = not settings_window_state.v
    imgui.Process = settings_window_state.v or example_window_state.v
end

function imgui.OnDrawFrame()
    if not settings_window_state.v then
        imgui.Process = false
    end -- если окно не активно то и процесс тоже будет не активен. После закрытия окна мышь пропадет.
    if settings_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver) -- устанавливаем размер окна
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- позиция окна
        imgui.Begin(u8"Меню", settings_window_state)
            if imgui.Button(u8"Test") then
                example_window_state.v = not example_window_state.v
            end
        imgui.End()
    end
    if example_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 5), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8"Меню1", example_window_state)
            imgui.Text(u8"Test")

        imgui.End()
    end
end
что-то не получилось
:
script:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)
local playerid = -1
local sw, sh = getScreenResolution() -- узнаем размер экрана

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function() main_window_state.v = not main_window_state.v end)
    imgui.Process = false
    -- Блок выполняется один раз после старта сампа
    while true do
        wait(0)
        imgui.Process = main_window_state.v
        -- Блок выполняющийся бесконечно (пока самп активен)
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
        if valid and doesCharExist(ped) then
            local result, id = sampGetPlayerIdByCharHandle(ped)
            if result and isKeyJustPressed(VK_X) then
                main_window_state.v = not main_window_state.v
                playerid = id
            end
        end
    end
end

function imgui.OnDrawFrame()
    if not main_window_state.v then
        imgui.Process = false
    end
    if main_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(300, 325), imgui.Cond.FirstUseEver) -- устанавливаем размер окна
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- позиция окна
        imgui.Begin(u8"Helper Menu", main_window_state)
        if imgui.Button(u8"История ников") then
            sampSendChat("/history "..sampGetPlayerNickname(tostring(playerid)))
        end

        if imgui.Button(u8"Добавить в записную книгу") then
             sampSendChat("/add "..tostring(playerid))
        end

        if imgui.Button(u8"Нажми") then
            example_window_state.v = not example_window_state.v
        end
        -- Если нужен NickName: sampGetPlayerNickname(tostring(playerid))
        -- Если нужен NickName без _ : sampGetPlayerNickname(tostring(playerid)):gsub('_', ' ')
        -- Если нужен ID: tostring(playerid)
    end
    imgui.End()
end
if example_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 5), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(u8"Меню1", example_window_state)
        imgui.Text(u8"Test")

    imgui.End()
end
 

Gorskin

{Reverse Developer} ✓
Проверенный
1,251
1,054
что-то не получилось
:
script:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)
local playerid = -1
local sw, sh = getScreenResolution() -- узнаем размер экрана

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function() main_window_state.v = not main_window_state.v end)
    imgui.Process = false
    -- Блок выполняется один раз после старта сампа
    while true do
        wait(0)
        imgui.Process = main_window_state.v
        -- Блок выполняющийся бесконечно (пока самп активен)
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
        if valid and doesCharExist(ped) then
            local result, id = sampGetPlayerIdByCharHandle(ped)
            if result and isKeyJustPressed(VK_X) then
                main_window_state.v = not main_window_state.v
                playerid = id
            end
        end
    end
end

function imgui.OnDrawFrame()
    if not main_window_state.v then
        imgui.Process = false
    end
    if main_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(300, 325), imgui.Cond.FirstUseEver) -- устанавливаем размер окна
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- позиция окна
        imgui.Begin(u8"Helper Menu", main_window_state)
        if imgui.Button(u8"История ников") then
            sampSendChat("/history "..sampGetPlayerNickname(tostring(playerid)))
        end

        if imgui.Button(u8"Добавить в записную книгу") then
             sampSendChat("/add "..tostring(playerid))
        end

        if imgui.Button(u8"Нажми") then
            example_window_state.v = not example_window_state.v
        end
        -- Если нужен NickName: sampGetPlayerNickname(tostring(playerid))
        -- Если нужен NickName без _ : sampGetPlayerNickname(tostring(playerid)):gsub('_', ' ')
        -- Если нужен ID: tostring(playerid)
    end
    imgui.End()
end
if example_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 5), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(u8"Меню1", example_window_state)
        imgui.Text(u8"Test")

    imgui.End()
end
Lua:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)
local playerid = nil -- логично же ёпт :D
local sw, sh = getScreenResolution() -- узнаем размер экрана

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function() main_window_state.v = not main_window_state.v end)
    imgui.Process = false
    -- Блок выполняется один раз после старта сампа
    while true do
        wait(0)
        imgui.Process = main_window_state.v
        -- Блок выполняющийся бесконечно (пока самп активен)
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
        if valid and doesCharExist(ped) then
            local result, id = sampGetPlayerIdByCharHandle(ped)
            if result and isKeyJustPressed(VK_X) then
                main_window_state.v = not main_window_state.v
                playerid = id
            end
        end
    end
end

function imgui.OnDrawFrame()
    if not main_window_state.v then
        imgui.Process = false
    end
    if main_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(300, 325), imgui.Cond.FirstUseEver) -- устанавливаем размер окна
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- позиция окна
        imgui.Begin(u8"Helper Menu", main_window_state)
            if imgui.Button(u8"История ников") then
                if playerid ~= nil then -- если ид игрока не равен ничему то введет /history и ид. Без этой проверки крашнет игру
                    sampSendChat("/history "..sampGetPlayerNickname(tostring(playerid)))
                end
            end

            if imgui.Button(u8"Добавить в записную книгу") then
                if playerid ~= nil then
                    sampSendChat("/add "..tostring(playerid))
                end
            end

            if imgui.Button(u8"Нажми") then
                example_window_state.v = not example_window_state.v
            end
            -- Если нужен NickName: sampGetPlayerNickname(tostring(playerid))
            -- Если нужен NickName без _ : sampGetPlayerNickname(tostring(playerid)):gsub('_', ' ')
            -- Если нужен ID: tostring(playerid)
        imgui.End() -- правильно
    end
    -- imgui.End() -- не правильно
    if example_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 5), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin(u8"Меню1", example_window_state)
            imgui.Text(u8"Test")
    
        imgui.End()
    end
end
я за тебя что-ли должен писать скрипт?)
 
Последнее редактирование:
  • Нравится
Реакции: abnomegd

Next..

Известный
343
135
Lua:
require "lib.moonloader" -- подключение библиотеки
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local main_window_state = imgui.ImBool(false)
local example_window_state = imgui.ImBool(false)
local playerid = nil -- логично же ёпт :D
local sw, sh = getScreenResolution() -- узнаем размер экрана

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand("imgui", function() main_window_state.v = not main_window_state.v end)
    imgui.Process = false
    -- Блок выполняется один раз после старта сампа
    while true do
        wait(0)
        imgui.Process = main_window_state.v
        -- Блок выполняющийся бесконечно (пока самп активен)
        local valid, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
        if valid and doesCharExist(ped) then
            local result, id = sampGetPlayerIdByCharHandle(ped)
            if result and isKeyJustPressed(VK_X) then
                main_window_state.v = not main_window_state.v
                playerid = id
            end
        end
    end
end

function imgui.OnDrawFrame()
    if not main_window_state.v then
        imgui.Process = false
    end
    if main_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(300, 325), imgui.Cond.FirstUseEver) -- устанавливаем размер окна
        imgui.SetNextWindowPos(imgui.ImVec2((sw / 2), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) -- позиция окна
        imgui.Begin(u8"Helper Menu", main_window_state)
            if imgui.Button(u8"История ников") then
                if playerid ~= nil then -- если ид игрока не равен ничему то введет /history и ид. Без этой проверки крашнет игру
                    sampSendChat("/history "..sampGetPlayerNickname(tostring(playerid)))
                end
            end

            if imgui.Button(u8"Добавить в записную книгу") then
                if playerid ~= nil then
                    sampSendChat("/add "..tostring(playerid))
                end
            end

            if imgui.Button(u8"Нажми") then
                example_window_state.v = not example_window_state.v
            end
            -- Если нужен NickName: sampGetPlayerNickname(tostring(playerid))
            -- Если нужен NickName без _ : sampGetPlayerNickname(tostring(playerid)):gsub('_', ' ')
            -- Если нужен ID: tostring(playerid)
        imgui.End() -- правильно
    end
    -- imgui.End() -- не правильно
end
if example_window_state.v then
    imgui.SetNextWindowSize(imgui.ImVec2(100, 100), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((sw / 5), sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(u8"Меню1", example_window_state)
        imgui.Text(u8"Test")

    imgui.End()
end
я за тебя что-ли должен писать скрипт?)
63-70 вне функции