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

malis

Участник
41
4
Так, как там в имгуи курсор оффать?

UPD: Как еще выводить ID диалога рядом с названием его?
UPD: Код как ограничитель фпс снять ( память вроде, не ебу )
 
Последнее редактирование:

gfgfds2423

Участник
73
18
Lua:
script_name('first script for lingberg')
script_author('_tsukanov_')
script_description('activation /lingberg')

require "lib.moonloader"

local tag = '[my first script]:'

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

    sampAddChatMessage("for lingberg!", 0x7300FF)

    while true do
        wait(0)
    end
end
ошибка в isSampFuncsLoaded() надо писать isSampfuncsLoaded()
и цвет надо писать начиная с 0x


Пробуй!
 
Последнее редактирование:

Domino

Участник
326
15
Lua:
script_name('Moon ImGui Example')
script_author('FYP')
script_description('Demonstrates Moon ImGui features')

local key = require 'vkeys'
local imgui = require 'imgui'
local encoding = require 'encoding'
local pie = require 'imgui_piemenu'
encoding.default = 'CP1251'
u8 = encoding.UTF8

function apply_custom_style()
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0
    -- style.Alpha =
    -- style.WindowPadding =
    -- style.WindowMinSize =
    -- style.FramePadding =
    -- style.ItemInnerSpacing =
    -- style.TouchExtraPadding =
    -- style.IndentSpacing =
    -- style.ColumnsMinSpacing = ?
    -- style.ButtonTextAlign =
    -- style.DisplayWindowPadding =
    -- style.DisplaySafeAreaPadding =
    -- style.AntiAliasedLines =
    -- style.AntiAliasedShapes =
    -- style.CurveTessellationTol =

    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.FrameBg]                = ImVec4(0.16, 0.29, 0.48, 0.54)
    colors[clr.FrameBgHovered]         = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.FrameBgActive]          = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.TitleBg]                = ImVec4(0.04, 0.04, 0.04, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.16, 0.29, 0.48, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.MenuBarBg]              = ImVec4(0.14, 0.14, 0.14, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]          = ImVec4(0.31, 0.31, 0.31, 1.00)
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.CheckMark]              = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.24, 0.52, 0.88, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.Button]                 = ImVec4(0.26, 0.59, 0.98, 0.40)
    colors[clr.ButtonHovered]          = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.06, 0.53, 0.98, 1.00)
    colors[clr.Header]                 = ImVec4(0.26, 0.59, 0.98, 0.31)
    colors[clr.HeaderHovered]          = ImVec4(0.26, 0.59, 0.98, 0.80)
    colors[clr.HeaderActive]           = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.26, 0.59, 0.98, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.26, 0.59, 0.98, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.26, 0.59, 0.98, 0.95)
    colors[clr.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    colors[clr.CloseButtonHovered]     = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]      = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.26, 0.59, 0.98, 0.35)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
apply_custom_style()

do

show_main_window = imgui.ImBool(false)
local show_imgui_example = imgui.ImBool(false)
local slider_float = imgui.ImFloat(0.0)
local clear_color = imgui.ImVec4(0.45, 0.55, 0.60, 1.00)
local show_test_window = imgui.ImBool(false)
local show_another_window = imgui.ImBool(false)
local show_moon_imgui_tutorial = {imgui.ImBool(false), imgui.ImBool(false), imgui.ImBool(false)}
local moonimgui_text_buffer = imgui.ImBuffer('test', 256)
local sampgui_texture = nil
local cb_render_in_menu = imgui.ImBool(imgui.RenderInMenu)
local cb_lock_player = imgui.ImBool(imgui.LockPlayer)
local cb_show_cursor = imgui.ImBool(imgui.ShowCursor)
local font_changed = false
local glyph_ranges_cyrillic = nil
function imgui.OnDrawFrame()
    -- Main Window
    if show_main_window.v then
        local sw, sh = getScreenResolution()
        -- center
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(300, 300), imgui.Cond.FirstUseEver)
        imgui.Begin('Main Window', show_main_window)
        local btn_size = imgui.ImVec2(-0.1, 0)
  
  
        if imgui.Button(u8'Кружочек', btn_size) then
            imgui.OpenPopup('PieMenu')
        end
        if pie.BeginPiePopup('PieMenu', 1) then
            if pie.PieMenuItem('TestSub') then
                sampSendChat('Ау')
            end
            if pie.PieMenuItem('TestSub2') then
                sampSendChat('Ау')
                print("TestSub2")
            end
          
          
            if pie.BeginPieMenu(u8'Другое') then
                print("Другое")
                if pie.BeginPieMenu(u8'Еще другое') then
                    if pie.PieMenuItem('SubSub') then
                    sampSendChat('[ ')
                    end
                    if pie.PieMenuItem('SubSub2') then end
                pie.EndPieMenu()
                end
            pie.EndPieMenu()
            end
        pie.EndPiePopup()
        end
      
      
        if imgui.BeginPopupModal('Texture Loading Error', nil, imgui.WindowFlags.AlwaysAutoResize) then
            imgui.Text('Texture "sampgui.png" couldn\'t be loaded.')
            imgui.Separator()
            if imgui.Button('OK') then
                imgui.CloseCurrentPopup()
            end
            imgui.EndPopup()
        end
        if imgui.CollapsingHeader('Options') then
            if imgui.Checkbox('Render in menu', cb_render_in_menu) then
                imgui.RenderInMenu = cb_render_in_menu.v
            end
            if imgui.Checkbox('Lock player controls', cb_lock_player) then
                imgui.LockPlayer = cb_lock_player.v
            end
            if imgui.Checkbox('Show cursor', cb_show_cursor) then
                imgui.ShowCursor = cb_show_cursor.v
            end
        end
        imgui.End()
    end

    -- Moon ImGui tutorial
    if show_moon_imgui_tutorial[1].v then
        imgui.Begin('My window##w1')
        imgui.Text('Hello world')
        imgui.End()
    end

    if show_moon_imgui_tutorial[2].v then
        imgui.SetNextWindowSize(imgui.ImVec2(150, 200), imgui.Cond.FirstUseEver)
        imgui.Begin('My window##w2', show_moon_imgui_tutorial[2])
        imgui.Text('Hello world')
        if imgui.Button('Press me') then
            printStringNow('Button pressed!', 1000)
        end
        imgui.End()
    end

    if show_moon_imgui_tutorial[3].v then
        imgui.Begin(u8'Основное окно')
        if imgui.InputText(u8'Вводить текст сюда', moonimgui_text_buffer) then
            print('Введённый текст:', u8:decode(moonimgui_text_buffer.v))
        end
        imgui.Text(u8'Введённый текст: ' .. moonimgui_text_buffer.v)
        imgui.Text(u8(string.format('Текущая дата: %s', os.date())))
        imgui.End()
    end

    -- Standard ImGui example
    if show_imgui_example.v then
        imgui.Begin('ImGui example', show_imgui_example)
        imgui.Text('Hello, world!')
        imgui.SliderFloat('float', slider_float, 0.0, 1.0)
        imgui.ColorEdit3('clear color', clear_color)
        if imgui.Button('Test Window') then
            show_test_window.v = not show_test_window.v
        end
        if imgui.Button('Another Window') then
            show_another_window.v = not show_another_window.v
        end
        local framerate = imgui.GetIO().Framerate
        imgui.Text(string.format('Application average %.3f ms/frame (%.1f FPS)', 1000.0 / framerate, framerate))
        imgui.End()
    end

    if show_another_window.v then
        imgui.Begin('Another Window', show_another_window)
        imgui.Text('Hello from another window!')
        imgui.End()
    end

    if show_test_window.v then
        imgui.SetNextWindowPos(imgui.ImVec2(650, 20), imgui.Cond.FirstUseEver)
        imgui.ShowTestWindow(show_test_window)
    end
end

end

function main()
    while true do
        wait(0)
        if wasKeyPressed(key.VK_X) then
            show_main_window.v = not show_main_window.v
        end
        imgui.Process = show_main_window.v
    end
end
Что делать, если нажимаешь на Test SUB 1 и 2 , то не выводит в чат "АУ"
Это начиная с 121 строчки
 

dimazukanov

Участник
51
8
Lua:
script_name('first script for lingberg')
script_author('_tsukanov_')
script_description('activation /lingberg')

require "lib.moonloader"

local tag = '[my first script]:'

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

    sampAddChatMessage("for lingberg!", 0x7300FF)

    while true do
        wait(0)
    end
end
ошибка в isSampFuncsLoaded() надо писать isSampfuncsLoaded()
и цвет надо писать начиная с 0x


Пробуй!
ну всё равно не работает😭
 

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
ну всё равно не работает😭
это у тебя тогда проблемы с чем-то, возможно версия монлоадера старая, у меня все работает
38650
 

dimazukanov

Участник
51
8

ГОХА | GoxaShow

В АРМИИ С 12.12,ЗАКАЗЫ НЕ ДЕЛАЮ,ТУПЫЕ ВОПРОСЫ-НАХУ
Проверенный
1,870
1,872
Lua:
json = [[
{
    "nicks":
    {
        1:"Nick_Name",
        2:"Test_Name"
    }
}
]]

file = decodeJson(json)
local nick = file.nicks[1]
что делать, не работает
Lua:
function checkip()
    local result, response = pcall(request.get, "http://ip-api.com/json/")
    if result then
        response = decodeJson(response)
        if response["query"] ~= "800.555.35.35" then
            --..
        end
    end
end
крашит, помоги
 
Последнее редактирование:

S-Sirius

Известный
353
21
Можете кинуть код на диалога такого диалога в ImgUi для луа скрипта?(Писал скрипт где использую диалог типа 0, хочу менять на зидайн ImgUi)
38659
 

savvin

Известный
407
140

KCAS 700W

Новичок
20
4
Не знаю куда это писать, поэтому напишу сюда.
(Ракбот) Что из этого фейк афк ?
!aafk включить AntiAFK
!noafk включить NoAFK
 

KCAS 700W

Новичок
20
4
Lua:
function onSpawned(x, y, z)
    if (z > 17 and z < 18) and (z > 11 and z < 12) then
        printLog('Бот в больнице или на спавне. Эмулируем краш игры..')
        defCallAdd(1000, false, function() runCommand('!noafk') end)
        defCallAdd(13454, false, function() runCommand('!quit') end)
    end
end
Lua:
function onSpawned()
    spawnTime = clock()
end

Слепите в одну функцию , пожалуйста