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

tsunamiqq

Участник
429
16
Lua:
local imgui = require("mimgui")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool()
local checkbox = imgui.new.bool()

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sx / 2, sy /2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("Test", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(500, 500), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
Спасибо, но нужно еще сделать сохранение в конфиг
 

percheklii

Известный
744
279
Спасибо, но нужно еще сделать сохранение в конфиг
Lua:
local imgui = require("mimgui")
local inicfg = require("inicfg")

local ini = inicfg.load({
    set = {
        on = false
    }
}, "test.ini")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool(ini.set.on)
local checkbox = imgui.new.bool(ini.set.on)

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sx / 2, sy /2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("Test", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
        ini.set.on = secondWindow[0]
        inicfg.save(ini, "test.ini")
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(500, 500), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
 
  • Нравится
Реакции: tsunamiqq

Kaktyc007

Известный
166
11
Написал самый простой скрипт при нахождении слова Хуй, проигрывается звук, но из часа слово Хуй удаляется. Как не удалять слово, которое я ищу?


хуй:
local sampev = require "lib.samp.events"
function sampev.onServerMessage(color, text)
    if text:find("Хуй")  then
        addOneOffSound(0.0, 0.0, 0.0, 1138)
    end
end
 

percheklii

Известный
744
279
Написал самый простой скрипт при нахождении слова Хуй, проигрывается звук, но из часа слово Хуй удаляется. Как не удалять слово, которое я ищу?


хуй:
local sampev = require "lib.samp.events"
function sampev.onServerMessage(color, text)
    if text:find("Хуй")  then
        addOneOffSound(0.0, 0.0, 0.0, 1138)
    end
end
Lua:
local sampev = require "lib.samp.events"
function sampev.onServerMessage(color, text)
    if text:find("Хуй") then
        lua_thread.create(function()
            wait(1)
            addOneOffSound(0.0, 0.0, 0.0, 1138)
        end)
    end
end
 

tsunamiqq

Участник
429
16
Lua:
local imgui = require("mimgui")
local inicfg = require("inicfg")

local ini = inicfg.load({
    set = {
        on = false
    }
}, "test.ini")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool(ini.set.on)
local checkbox = imgui.new.bool(ini.set.on)

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sx / 2, sy /2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("Test", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
        ini.set.on = secondWindow[0]
        inicfg.save(ini, "test.ini")
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(500, 500), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
Спасибки, еще просьба одна, можешь сделать смену местоположение этого меню по кнопке, нажимаю, меняю, и к примеру по нажатию на пробел сохраняю в конфиг местоположение
 

percheklii

Известный
744
279
Спасибки, еще просьба одна, можешь сделать смену местоположение этого меню по кнопке, нажимаю, меняю, и к примеру по нажатию на пробел сохраняю в конфиг местоположение
Lua:
local imgui = require("mimgui")
local inicfg = require("inicfg")

local ini = inicfg.load({
    set = {
        on = false,
        x = 500,
        y = 500
    }
}, "test.ini")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool(ini.set.on)
local checkbox = imgui.new.bool(ini.set.on)

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sx / 2, sy /2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("FirstWindow", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
        ini.set.on = secondWindow[0]
        inicfg.save(ini, "test.ini")
    end

    if imgui.Button("Position", imgui.ImVec2(106, 20)) then
        lua_thread.create(function()
            while not isKeyJustPressed(1) do wait(0)
                sampSetCursorMode(4)
                ini.set.x, ini.set.y = getCursorPos()
                firstWindow[0] = false
            end
            firstWindow[0] = true
            sampSetCursorMode(0)
            inicfg.save(ini, "test.ini")
        end)
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(ini.set.x, ini.set.y), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("SecondWindow", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
 

tsunamiqq

Участник
429
16
Lua:
local imgui = require("mimgui")
local inicfg = require("inicfg")

local ini = inicfg.load({
    set = {
        on = false,
        x = 500,
        y = 500
    }
}, "test.ini")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool(ini.set.on)
local checkbox = imgui.new.bool(ini.set.on)

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sx / 2, sy /2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("FirstWindow", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
        ini.set.on = secondWindow[0]
        inicfg.save(ini, "test.ini")
    end

    if imgui.Button("Position", imgui.ImVec2(106, 20)) then
        lua_thread.create(function()
            while not isKeyJustPressed(1) do wait(0)
                sampSetCursorMode(4)
                ini.set.x, ini.set.y = getCursorPos()
                firstWindow[0] = false
            end
            firstWindow[0] = true
            sampSetCursorMode(0)
            inicfg.save(ini, "test.ini")
        end)
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(ini.set.x, ini.set.y), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("SecondWindow", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
Я имел ввиду, менять местоположение того окна, которое я включаю
 

percheklii

Известный
744
279
В этом не было проблемы, я так и сделал, но не работает
Весь прикол в том, что стоял imgui.Cond.FirstUseEver в imgui.SetNextWindowPos, которое как бы не хотело менять позицию окна в реальном времени, и возвращало его на изначальную позицию, а imgui.Cond.Always, будет всегда выполнять действие, не зависимо от изначально заданных координат для окна

Lua:
local imgui = require("mimgui")
local inicfg = require("inicfg")

local ini = inicfg.load({
    set = {
        on = false,
        x = 500,
        y = 500
    }
}, "test.ini")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool(ini.set.on)
local checkbox = imgui.new.bool(ini.set.on)

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(ini.set.x, ini.set.y), imgui.Cond.Always, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("FirstWindow", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
        ini.set.on = secondWindow[0]
        inicfg.save(ini, "test.ini")
    end

    if imgui.Button("Position", imgui.ImVec2(106, 20)) then
        sampAddChatMessage("Нажмите пробел, чтобы установить позицию окна.", 0xFFFFFF)
        lua_thread.create(function()
            while not isKeyJustPressed(32) do wait(0)
                sampToggleCursor(true)
                ini.set.x, ini.set.y = getCursorPos()
            end
            sampToggleCursor(false)
            inicfg.save(ini, "test.ini")
        end)
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(500, 500), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("SecondWindow", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
 
  • Нравится
Реакции: tsunamiqq

tsunamiqq

Участник
429
16
Весь прикол в том, что стоял imgui.Cond.FirstUseEver в imgui.SetNextWindowPos, которое как бы не хотело менять позицию окна в реальном времени, и возвращало его на изначальную позицию, а imgui.Cond.Always, будет всегда выполнять действие, не зависимо от изначально заданных координат для окна

Lua:
local imgui = require("mimgui")
local inicfg = require("inicfg")

local ini = inicfg.load({
    set = {
        on = false,
        x = 500,
        y = 500
    }
}, "test.ini")

local firstWindow, secondWindow = imgui.new.bool(), imgui.new.bool(ini.set.on)
local checkbox = imgui.new.bool(ini.set.on)

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

imgui.OnFrame(function() return firstWindow[0] end, function(player)
    local sx, sy = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(ini.set.x, ini.set.y), imgui.Cond.Always, imgui.ImVec2(0.5, 0.5))
    imgui.Begin("FirstWindow", firstWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.AlwaysAutoResize)
    if imgui.Checkbox("ON/OFF", checkbox) then
        secondWindow[0] = not secondWindow[0]
        ini.set.on = secondWindow[0]
        inicfg.save(ini, "test.ini")
    end

    if imgui.Button("Position", imgui.ImVec2(106, 20)) then
        sampAddChatMessage("Нажмите пробел, чтобы установить позицию окна.", 0xFFFFFF)
        lua_thread.create(function()
            while not isKeyJustPressed(32) do wait(0)
                sampToggleCursor(true)
                ini.set.x, ini.set.y = getCursorPos()
            end
            sampToggleCursor(false)
            inicfg.save(ini, "test.ini")
        end)
    end
    imgui.End()
end)

imgui.OnFrame(function() return secondWindow[0] end, function(player)
    player.HideCursor = true
    imgui.SetNextWindowPos(imgui.ImVec2(500, 500), imgui.Cond.Always, imgui.ImVec2(1, 1))
    imgui.SetNextWindowSize(imgui.ImVec2(130, 175), imgui.Cond.Always)
    imgui.Begin("SecondWindow", secondWindow, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoSavedSettings, imgui.WindowFlags.NoMove, imgui.WindowFlags.NoInputs)
    imgui.Text("Hello, world!")
    imgui.End()
end)

function main()
    repeat wait(0) until isSampAvailable()
    sampRegisterChatCommand("test", function()
        firstWindow[0] = not firstWindow[0]
    end)
    wait(-1)
end
В нужном мне окне, которое можно включить/выключить прописано "imgui.Cond.Always" но позицию так и не меняет