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

percheklii

Известный
727
267
как сделать сраный checkbox, 2 часа сижу себе ломаю голову, это пиздец(соре за мат) p.s полный 0 в imgui =)

Код:
типа надо для этой функции сделать

ini.time.on - путь к true/false

if time.v then
time = sampTextdrawGetString(0)
hour, minute = time:match("~w~(%d+)~y~:~w~(%d+)")
local text = string.format("%s:%s", hour, minute)
renderFontDrawText(font, text, ini.time.x, ini.time.y, -1)
end
 

Julimba

Участник
108
10
cc1 = {'12', '13', '14', '15'},
cc2 = {'(%d*)', '(%.*)}',
[ML] (error) verytest.lua: ...ser\Desktop\maxshrinkedByKichiro\moonloader\verytest.lua:43: bad argument #1 to 'find' (string expected, got table)
stack traceback:
[C]: in function 'find'
...ser\Desktop\maxshrinkedByKichiro\moonloader\verytest.lua:43: in function 'callback'
...maxshrinkedByKichiro\moonloader\lib\samp\events\core.lua:79: in function <...maxshrinkedByKichiro\moonloader\lib\samp\events\core.lua:53>
[ML] (error) verytest.lua: Script died due to an error. (01D68364)
 

Anti...

Участник
243
19
Как сделать уведомления в группу ВК через игру? Написал "/cmd hello" и это "hello" отправилось в группу ВК

как сделать сраный checkbox, 2 часа сижу себе ломаю голову, это пиздец(соре за мат) p.s полный 0 в imgui =)

Код:
типа надо для этой функции сделать

ini.time.on - путь к true/false

if time.v then
time = sampTextdrawGetString(0)
hour, minute = time:match("~w~(%d+)~y~:~w~(%d+)")
local text = string.format("%s:%s", hour, minute)
renderFontDrawText(font, text, ini.time.x, ini.time.y, -1)
end
Код:
--function imgui.onDrawFrame
checkbox = imgui.ImBool(false)

imgui.Checkbox(u8 'Checkbox', checkbox) then
 

percheklii

Известный
727
267
Как сделать уведомления в группу ВК через игру? Написал "/cmd hello" и это "hello" отправилось в группу ВК


Код:
--function imgui.onDrawFrame
checkbox = imgui.ImBool(false)

imgui.Checkbox(u8 'Checkbox', checkbox) then
та я делал так, вылазит ошибка
stack index 2, expected userdata, received boolean: value is not a valid userdata (bad argument into 'bool(const char*, ImValue<bool>*)')
 

percheklii

Известный
727
267
Код:
local fa = require 'fAwesome5'
local imgui = require("imgui")
local inicfg = require("inicfg")
local encoding = require ("encoding")
encoding.default = ("CP1251")
local u8 = encoding.UTF8


local path = getWorkingDirectory() .. "\\config\\Hud.ini"
local ini = inicfg.load({
    time = {
        on = true,
        x = 0,
        y = 0
      }
}, path)

local fa_font = nil
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })
function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig()
        font_config.MergeMode = true
        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 13.0, font_config, fa_glyph_ranges)
    end
end

local main_window_state = imgui.ImBool(false)

local menu = {
   true,
   false,
   false,
   false,
   false
}

function main()
    while not isSampAvailable() do wait(100) end
    
    local font = renderCreateFont(Arial, 10, 13)
    
    sampAddChatMessage('Скрипт успешно загружен. | Меню: F2 |', -1)

    while true do
        wait(0)   
        if isKeyJustPressed(113) then
            main_window_state.v  = not main_window_state.v
        end
        imgui.Process = main_window_state.v
        
        time = sampTextdrawGetString(0)
        hour, minute = time:match("~w~(%d+)~y~:~w~(%d+)")
        local text = string.format("%s:%s", hour, minute)
        renderFontDrawText(font, text, ini.time.x, ini.time.y, -1)
    end
end

function imgui.OnDrawFrame()
    local sw, sh = getScreenResolution()
    imgui.SetNextWindowSize(imgui.ImVec2(570, 350))
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(fa.ICON_FA_DESKTOP .. "  her", window, imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.NoCollapse)
        imgui.BeginChild('##left', imgui.ImVec2(150, 300), true)
        if imgui.Button(fa.ICON_FA_CLOCK .. u8(' Профиль'), imgui.ImVec2(-1, 20)) then
            menu = 1
        end
        if imgui.Button(u8('Время'), imgui.ImVec2(-1, 20)) then
            menu = 2
        end
        if imgui.Button(u8('Дата'), imgui.ImVec2(-1, 20)) then
            menu = 3
        end
        if imgui.Button(u8('Уровень'), imgui.ImVec2(-1, 20)) then
            menu = 4
        end
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginChild('##right', imgui.ImVec2(400, 300), true)
        if menu == 1 then   
        if imgui.Button(u8"Позиция", imgui.ImVec2(150, 25)) then
                main_window_state.v = false
                lua_thread.create(function ()
                    while not isKeyJustPressed(0x01) do wait(0)
                        sampSetCursorMode(4)
                        local posX, posY = getCursorPos()
                        ini.time.x = posX
                        ini.time.y = posY
                    end
                    main_window_state.v = true
                    sampSetCursorMode(0)
                    inicfg.save(ini, path)
                end)
            end
        end
        if menu == 2 then
        end
        if menu == 3 then
        end
        if menu == 4 then
        end
        imgui.EndChild()
    imgui.End()
end
 

accord-

Потрачен
437
79
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Как сделать уведомления в группу ВК через игру? Написал "/cmd hello" и это "hello" отправилось в группу ВК


Код:
--function imgui.onDrawFrame
checkbox = imgui.ImBool(false)

imgui.Checkbox(u8 'Checkbox', checkbox) then
Код:
if imgui.Checkbox('xyeta', bool) then

end

Функиция "nameTagOff" не отключает ники, что не так?
Lua:
-----В функции WH
                 if wallhack.v then
                    nameTagOn()
                else
                    nameTagOff()
                end
-----
function nameTagOn()
    local pStSet = sampGetServerSettingsPtr();
    NTdist = mem.getfloat(pStSet + 39)
    NTwalls = mem.getint8(pStSet + 47)
    NTshow = mem.getint8(pStSet + 56)
    mem.setfloat(pStSet + 39, 1488.0)
    mem.setint8(pStSet + 47, 0)
    mem.setint8(pStSet + 56, 1)
end

function nameTagOff()
    local pStSet = sampGetServerSettingsPtr();
    mem.setfloat(pStSet + 39, NTdist)
    mem.setint8(pStSet + 47, NTwalls)
    mem.setint8(pStSet + 56, NTshow)
end

1675965029871.png
 

Вложения

  • 1675965026354.png
    1675965026354.png
    25.4 KB · Просмотры: 8
Последнее редактирование:

Leatington

Известный
258
71
Как нативно определить адрес сервера, к которому подключён персонаж? Без сторонних библиотек и без SampFuncs.
 

qdIbp

Автор темы
Проверенный
1,386
1,141
[ML] (error) verytest.lua: ...ser\Desktop\maxshrinkedByKichiro\moonloader\verytest.lua:43: bad argument #1 to 'find' (string expected, got table)
stack traceback:
[C]: in function 'find'
...ser\Desktop\maxshrinkedByKichiro\moonloader\verytest.lua:43: in function 'callback'
...maxshrinkedByKichiro\moonloader\lib\samp\events\core.lua:79: in function <...maxshrinkedByKichiro\moonloader\lib\samp\events\core.lua:53>
[ML] (error) verytest.lua: Script died due to an error. (01D68364)
И как ты делал?
 
D

deleted-user-422095

Гость
Как нативно определить адрес сервера, к которому подключён персонаж? Без сторонних библиотек и без SampFuncs.
 

aidzava

Новичок
20
0
всем привет, такая проблема, мне нужно хукануть цветную строку с таймстампом Посмотреть вложение 189348, и вывести ее например в чат, с таким же цветом, но когда я это делаю, у меня вообще другой цвет выводит. Посмотреть вложение 189349 c другими же строками все норм работает, только вип чат так выводит
код вот
qwe:
function se.onServerMessage(col, msg)
text = msg
local tagg, player, id, text = msg:match('^%[(.+)%] %{......%}(.+)%[(%d+)%]: (.+)')
if tagg == 'VIP' or tagg == 'PREMIUM' or tagg == 'FOREVER' then
    if work then
        sampAddChatMessage(msg, col)
    end
end
 
  • Злость
Реакции: qdIbp

D3vel0per

Участник
61
34
Как сделать, чтобы при нажатие кнопки в imgui окне, добавлялась строчка с иптутом текста
 

Rice.

https://t.me/riceoff
Модератор
1,689
1,430
Как сделать, чтобы при нажатие кнопки в imgui окне, добавлялась строчка с иптутом текста
Lua:
-->> Таблица инпутов
local inputs = {
    imgui.ImBuffer(256)
}

-->> Имгуи
if imgui.Button('Add Input') then
    table.insert(inputs, imgui.ImBuffer(256))
end

for k, v in ipairs(inputs) do
    imgui.InputText('Input ' .. k, v)
end

всем привет, такая проблема, мне нужно хукануть цветную строку с таймстампом Посмотреть вложение 189348, и вывести ее например в чат, с таким же цветом, но когда я это делаю, у меня вообще другой цвет выводит. Посмотреть вложение 189349 c другими же строками все норм работает, только вип чат так выводит
код вот
qwe:
function se.onServerMessage(col, msg)
text = msg
local tagg, player, id, text = msg:match('^%[(.+)%] %{......%}(.+)%[(%d+)%]: (.+)')
if tagg == 'VIP' or tagg == 'PREMIUM' or tagg == 'FOREVER' then
    if work then
        sampAddChatMessage(msg, col)
    end
end
Lua:
function se.onServerMessage(col, msg)
    text = msg
    local tagg, player, id, text = msg:match('^%[(.+)%] %{......%}(.+)%[(%d+)%]: (.+)')
    if tagg == 'VIP' or tagg == 'PREMIUM' or tagg == 'FOREVER' then
        if work then
            return{col, msg}
        end
    end
end

Код:
local fa = require 'fAwesome5'
local imgui = require("imgui")
local inicfg = require("inicfg")
local encoding = require ("encoding")
encoding.default = ("CP1251")
local u8 = encoding.UTF8


local path = getWorkingDirectory() .. "\\config\\Hud.ini"
local ini = inicfg.load({
    time = {
        on = true,
        x = 0,
        y = 0
      }
}, path)

local fa_font = nil
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })
function imgui.BeforeDrawFrame()
    if fa_font == nil then
        local font_config = imgui.ImFontConfig()
        font_config.MergeMode = true
        fa_font = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 13.0, font_config, fa_glyph_ranges)
    end
end

local main_window_state = imgui.ImBool(false)

local menu = {
   true,
   false,
   false,
   false,
   false
}

function main()
    while not isSampAvailable() do wait(100) end
   
    local font = renderCreateFont(Arial, 10, 13)
   
    sampAddChatMessage('Скрипт успешно загружен. | Меню: F2 |', -1)

    while true do
        wait(0)  
        if isKeyJustPressed(113) then
            main_window_state.v  = not main_window_state.v
        end
        imgui.Process = main_window_state.v
       
        time = sampTextdrawGetString(0)
        hour, minute = time:match("~w~(%d+)~y~:~w~(%d+)")
        local text = string.format("%s:%s", hour, minute)
        renderFontDrawText(font, text, ini.time.x, ini.time.y, -1)
    end
end

function imgui.OnDrawFrame()
    local sw, sh = getScreenResolution()
    imgui.SetNextWindowSize(imgui.ImVec2(570, 350))
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(fa.ICON_FA_DESKTOP .. "  her", window, imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.NoCollapse)
        imgui.BeginChild('##left', imgui.ImVec2(150, 300), true)
        if imgui.Button(fa.ICON_FA_CLOCK .. u8(' Профиль'), imgui.ImVec2(-1, 20)) then
            menu = 1
        end
        if imgui.Button(u8('Время'), imgui.ImVec2(-1, 20)) then
            menu = 2
        end
        if imgui.Button(u8('Дата'), imgui.ImVec2(-1, 20)) then
            menu = 3
        end
        if imgui.Button(u8('Уровень'), imgui.ImVec2(-1, 20)) then
            menu = 4
        end
        imgui.EndChild()
        imgui.SameLine()
        imgui.BeginChild('##right', imgui.ImVec2(400, 300), true)
        if menu == 1 then  
        if imgui.Button(u8"Позиция", imgui.ImVec2(150, 25)) then
                main_window_state.v = false
                lua_thread.create(function ()
                    while not isKeyJustPressed(0x01) do wait(0)
                        sampSetCursorMode(4)
                        local posX, posY = getCursorPos()
                        ini.time.x = posX
                        ini.time.y = posY
                    end
                    main_window_state.v = true
                    sampSetCursorMode(0)
                    inicfg.save(ini, path)
                end)
            end
        end
        if menu == 2 then
        end
        if menu == 3 then
        end
        if menu == 4 then
        end
        imgui.EndChild()
    imgui.End()
end
покажи код, в который ты уже добавил checkbox
 
Последнее редактирование:
  • Грустно
Реакции: qdIbp