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

Smeruxa

smeruxa.ru
Проверенный
1,428
788
напиши ednPos = {GetBodyPartCoordinates(4, handle)}
Убери проверки, если работает - то ты неверно используешь RadioButton, я давным давно им пользовался, поэтому не могу точно утверждать, правильно ли ты используешь
Lua:
-- с

if buf_1.bone == 1 then
                ednPos = {GetBodyPartCoordinates(6, handle)}
            elseif buf_1.bone == 2 then
                ednPos = {GetBodyPartCoordinates(4, handle)}
            elseif buf_1.bone == 3 then
                ednPos = {GetBodyPartCoordinates(3, handle)}
            end
           
-- на

ednPos = {GetBodyPartCoordinates(4, handle)}
 
Последнее редактирование:

goodflex

Активный
280
58
X: ((ширина экрана - ширина окна) / 2) - window_size_x
Y: ((высота экрана - высота окна) / 2) - window_size_y
если нет 0.5 по кордам


напиши ednPos = {GetBodyPartCoordinates(4, handle)}
Убери проверки, если работает - то ты неверно используешь RadioButton, я давным давно им пользовался, поэтому не могу точно утверждать, правильно ли ты используешь
Lua:
-- с

if buf_1.bone == 1 then
                ednPos = {GetBodyPartCoordinates(6, handle)}
            elseif buf_1.bone == 2 then
                ednPos = {GetBodyPartCoordinates(4, handle)}
            elseif buf_1.bone == 3 then
                ednPos = {GetBodyPartCoordinates(3, handle)}
            end
           
-- на

ednPos = {GetBodyPartCoordinates(4, handle)}
-, .lua:1251: attempt to call global 'GetBodyPartCoordinates' (a nil value)
 

goodflex

Активный
280
58
Вырежи эту функцию из того откуда ты вырезал те функции
где я вырезал было
Lua:
            if aim.CheckBox.bone[0] == 0 then
                ednPos = {GetBodyPartCoordinates(6, handle)}
            elseif aim.CheckBox.bone[0] == 1 then
                ednPos = {GetBodyPartCoordinates(4, handle)}
            elseif aim.CheckBox.bone[0] == 2 then
                ednPos = {GetBodyPartCoordinates(3, handle)}
            end
            -- я лишь изменил aim.CheckBox.bone[0] на то как у меня стоит, тоесть buf_1.bone
 

Smeruxa

smeruxa.ru
Проверенный
1,428
788
где я вырезал было
Lua:
            if aim.CheckBox.bone[0] == 0 then
                ednPos = {GetBodyPartCoordinates(6, handle)}
            elseif aim.CheckBox.bone[0] == 1 then
                ednPos = {GetBodyPartCoordinates(4, handle)}
            elseif aim.CheckBox.bone[0] == 2 then
                ednPos = {GetBodyPartCoordinates(3, handle)}
            end
            -- я лишь изменил aim.CheckBox.bone[0] на то как у меня стоит, тоесть buf_1.bone
Функцию вырежи GetBodyPartCoordinates с того же скрипта, она должна быть, зачем ты дважды спрашиваешь, если тебе сказали что делать
 

goodflex

Активный
280
58
пишет 1261: attempt to index upvalue 'ednPos' (a nil value)
Функцию вырежи GetBodyPartCoordinates с того же скрипта, она должна быть, зачем ты дважды спрашиваешь, если тебе сказали что делать
Lua:
local ednPos

--

if one4.v then
         local sw, sh = getScreenResolution()
         imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.7))
         imgui.SetNextWindowSize(imgui.ImVec2(400,350), imgui.Cond.FirstUseEver)
         imgui.Begin(fa.ICON_FA_CROSSHAIRS.. u8" AIM", one4, imgui.WindowFlags.NoResize)
         imgui.Checkbox(fa.ICON_FA_CROSSHAIRS.. u8' Включить', buf_1.enableaim)
         imgui.SliderFloat(u8"Радиус", buf_1.fov, 1, 30)
         imgui.SliderFloat(u8"Плавность", buf_1.smooth, 1, 50)
         imgui.SliderFloat(u8"Дистанция", buf_1.maxdistAim, 30, 1000)
         imgui.Separator()
         imgui.Checkbox(u8"Проверка на здания", buf_1.checkBuild)
         imgui.Checkbox(u8"Проверка на машины", buf_1.checkVehicle)
         imgui.Checkbox(u8"Проверка на объекты", buf_1.checkObject)
         imgui.Separator()
         imgui.RadioButton(u8"Голова", buf_1.bone, 1)
         imgui.RadioButton(u8"Торс", buf_1.bone, 2)
         imgui.RadioButton(u8"Пах", buf_1.bone, 3)
         imgui.Separator()
         imgui.Checkbox(u8"Стрельба по своим", buf_1.team)
         imgui.End()
    end
    
--

function Aimbot()
    if buf_1.enableaim and isKeyDown(VK_RBUTTON) then
        local handle = GetNearestPed(buf_1.fov)
        if handle ~= -1 then
            local myPos = {getActiveCameraCoordinates()}
            if buf_1.bone == 1 then
                ednPos = 6, handle
            elseif buf_1.bone == 2 then
                ednPos = 4, handle
            elseif buf_1.bone == 3 then
                ednPos = 3, handle
            end
            if buf_1.team then
                if isLineOfSightClear(myPos[1], myPos[2], myPos[3], ednPos[1], ednPos[2], ednPos[3], buf_1.checkBuild, buf_1.checkVehicle, false, buf_1.checkObject, false) then
                    local vector = {myPos[1] - ednPos[1], myPos[2] - ednPos[2], myPos[3] - ednPos[3]}
                    if isWidescreenOnInOptions() then coefficentZ = 0.0778 else coefficentZ = 0.103 end
                    local angle = {(math.atan2(vector[2], vector[1]) + 0.04253), (math.atan2((math.sqrt((math.pow(vector[1], 2) + math.pow(vector[2], 2)))), vector[3]) - math.pi / 2 - coefficentZ)}
                    local view = {fix(representIntAsFloat(readMemory(0xB6F258, 4, false))), fix(representIntAsFloat(readMemory(0xB6F248, 4, false)))}
                    local difference = {angle[1] - view[1], angle[2] - view[2]}
                    local smooth = {difference[1] / buf_1.smooth, difference[2] / buf_1.smooth}
                    setCameraPositionUnfixed((view[2] + smooth[2]), (view[1] + smooth[1]))
                end
            else
                for i = 0, sampGetMaxPlayerId() do
                    if sampIsPlayerConnected(i) then
                        local result, handlePed = sampGetCharHandleBySampPlayerId(i)
                        local color_ped = sampGetPlayerColor(i)
                        if result and color_ped ~= sampGetPlayerColor(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))) then
                            if isLineOfSightClear(myPos[1], myPos[2], myPos[3], ednPos[1], ednPos[2], ednPos[3], buf_1.checkBuild, buf_1.checkVehicle, false, buf_1.checkObject, false) then
                                local vector = {myPos[1] - ednPos[1], myPos[2] - ednPos[2], myPos[3] - ednPos[3]}
                                if isWidescreenOnInOptions() then coefficentZ = 0.0778 else coefficentZ = 0.103 end
                                local angle = {(math.atan2(vector[2], vector[1]) + 0.04253), (math.atan2((math.sqrt((math.pow(vector[1], 2) + math.pow(vector[2], 2)))), vector[3]) - math.pi / 2 - coefficentZ)}
                                local view = {fix(representIntAsFloat(readMemory(0xB6F258, 4, false))), fix(representIntAsFloat(readMemory(0xB6F248, 4, false)))}
                                local difference = {angle[1] - view[1], angle[2] - view[2]}
                                local smooth = {difference[1] / buf_1.smooth, difference[2] / buf_1.smooth}
                                setCameraPositionUnfixed((view[2] + smooth[2]), (view[1] + smooth[1]))
                            end
                        end
                    end
                end
            end
        end
    end
    return false
end


Вырезал вот от сюда
 

Вложения

  • AimAssist by Scar v0.7.1 Beta - Free Version.lua
    121.7 KB · Просмотры: 3

YarikVL

Известный
Проверенный
4,721
1,807
Как сделать сохранение с inputtext в ini?
 
  • Нравится
Реакции: MLycoris

Макс | Lycorn

Участник
166
13
Попробовал сделать как там, не работает
 

Макс | Lycorn

Участник
166
13
Что ты не так сделал, кинь свой код
Lua:
script_name('SMI HELPER')
script_author('tsunamiqq')
script_description('SMI HELPER')
script_version('1.0')
require "lib.moonloader"
local imgui = require 'imgui'
local key = require 'vkeys'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
cp1251 = encoding.CP1251
local inicfg = require 'inicfg'
local directIni = "moonloader\\SMIHelper\\ad.ini"
local directIni = "moonloader\\SMIHelper\\smihelper.ini"
local stateIni = inicfg.save(mainIni, directIni)
local mainIni = inicfg.load({
    config = {
        nickname = '',
        rang = '',
        org = '',
        sex = '',
        town = ''
}}, 'smihelper.ini')
local status = inicfg.load(mainIni, 'smihelper.ini')
if not doesFileExist('moonloader/SMIHelper/smihelper.ini') then inicfg.save(mainIni, 'smihelper.ini') end
local fa = require 'faIcons'
local fa_glyph_ranges = imgui.ImGlyphRanges({ fa.min_range, fa.max_range })

local nicknamecfg = imgui.ImBool(mainIni.config.nickname)
local nickname = new.char[256](u8(mainIni.config.nickname))
local rang = imgui.ImBuffer(256)
local org = imgui.ImBuffer(256)
local sex = imgui.ImBuffer(256)
local town = imgui.ImBuffer(256)
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/fontawesome-webfont.ttf', 14.0, font_config, fa_glyph_ranges)
    end
end
local main_window_state = imgui.ImBool(false)
function imgui.OnDrawFrame()
    local iScreenWidth, iScreenHeight = getScreenResolution()
    local btn_size = imgui.ImVec2(-1, 0)
    if main_window_state.v then
        imgui.SetNextWindowSize(imgui.ImVec2(1000, 500), imgui.Cond.FirstUseEver)
        imgui.Begin('SMI HELPER', main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
        imgui.BeginChild('##tabs', imgui.ImVec2(200, 460), true)
        if imgui.Button(fa.ICON_ADDRESS_BOOK .. ' Профиль', imgui.ImVec2(185,50), main_window_state) then act = 0 end
        if imgui.Button(fa.ICON_COG .. ' Настройки', imgui.ImVec2(185,50), main_window_state) then act = 1 end
        if imgui.Button(fa.ICON_BELL_O .. ' Собеседование', imgui.ImVec2(185,50), main_window_state) then act = 2 end
        if imgui.Button(fa.ICON_BULLHORN .. ' Эфиры', imgui.ImVec2(185,50), main_window_state) then act = 3 end
        if imgui.Button(fa.ICON_COMMENTING_O .. ' Проверка на знания', imgui.ImVec2(185,50), main_window_state) then act = 4 end
        if imgui.Button(fa.ICON_INFO .. ' О скрипте', imgui.ImVec2(185,50), main_window_state) then act = 5 end
        imgui.EndChild()
        imgui.SameLine()
        if act == 0 then
            imgui.BeginChild('##once121221', imgui.ImVec2(775,460), true)
            imgui.BeginChild('##once', imgui.ImVec2(760, 240), true)
            imgui.Text('Имя и Фамилия:')
            imgui.PushItemWidth(150)
            if imgui.InputText('##0', nickname, 256) then
                mainIni.config.nickname = u8:decode(str(nickname))
                inicfg.save(mainIni, 'smihelper.ini')
            end
            imgui.PopItemWidth()
            imgui.Text('Должность:')
            imgui.PushItemWidth(150)
            imgui.InputText('##1', rang)
            imgui.PopItemWidth()
            imgui.Text('Организация:')
            imgui.PushItemWidth(150)
            imgui.InputText('##2', org)
            imgui.PopItemWidth()
            imgui.Text('Пол:')
            imgui.PushItemWidth(150)
            imgui.InputText('##3', sex)
            imgui.PopItemWidth()
            imgui.Text('Город:')
            imgui.PushItemWidth(150)
            imgui.InputText('##4', town)
            imgui.PopItemWidth()
            imgui.EndChild()
            imgui.BeginChild('##2323223', imgui.ImVec2(760,200), true)
            imgui.SetCursorPosX(330)
            imgui.Text('Информация о вас')
            imgui.Separator()
            imgui.SetCursorPosX(50)
            imgui.Text(fa.ICON_ADDRESS_CARD_O .. ' Имя и Фамилия: ')
            imgui.SetCursorPosX(50)
            imgui.Text(fa.ICON_USER_O .. ' Должность: ')
            imgui.SetCursorPosX(50)
            imgui.Text(fa.ICON_BOOK .. ' Организация: ')
            imgui.SetCursorPosX(50)
            imgui.Text(fa.ICON_FEMALE .. ' Пол: ')
            imgui.SetCursorPosX(50)
            imgui.Text(fa.ICON_FIGHTER_JET .. ' Город:')
            imgui.EndChild()
            imgui.EndChild()
        elseif act == 1 then
            imgui.BeginChild('##3223', imgui.ImVec2(385,460), true)
            imgui.EndChild()
            imgui.SameLine()
            imgui.BeginChild('##once', imgui.ImVec2(385,460), true)
            imgui.EndChild()
        elseif act == 2 then
            imgui.BeginChild('##once', imgui.ImVec2(860, 460), true)
            imgui.EndChild()
        elseif act == 3 then
            imgui.BeginChild('##once', imgui.ImVec2(860, 460), true)
            imgui.EndChild()
        elseif act == 4 then
            imgui.BeginChild('##once', imgui.ImVec2(860, 460), true)
            imgui.EndChild()
        elseif act == 5 then
            imgui.BeginChild('##once', imgui.ImVec2(860, 460), true)
            imgui.Text(fa.ICON_USER_O .. ' Автор скрипта: tsunamiqq')
            imgui.Text(fa.ICON_USER_CIRCLE .. ' Discord: tsunamiqq#8608')
            imgui.Text(fa.ICON_COMMENT_O .. ' VK: https://vk.com/maks.tsunami')
            imgui.Text(fa.ICON_SUPERPOWERS .. ' Версия скрипта: 1.0')
            imgui.EndChild()
        end
    end
    imgui.End()
end
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(2000) end
    sampAddChatMessage(u8:decode'[SMI] Скрипт успешно запущен!', 0x00BFFF)
    sampAddChatMessage(u8:decode'[SMI] Активация: /smi', 0x00BFFF)
    sampAddChatMessage(u8:decode'[SMI] Автор: tsunamiqq', 0x00BFFF)
    sampRegisterChatCommand('famh', function() main_window_state.v = not main_window_state.v end)
    while true do
        wait(0)
        imgui.Process = main_window_state.v
    end
end
function apply_custom_style()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    
    colors[clr.Text]                 = ImVec4(1.00, 1.00, 1.00, 0.78)
    colors[clr.TextDisabled]         = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.WindowBg]             = ImVec4(0.11, 0.15, 0.17, 1.00)
    colors[clr.ChildWindowBg]        = ImVec4(0.15, 0.18, 0.22, 1.00)
    colors[clr.PopupBg]              = ImVec4(0.08, 0.08, 0.08, 0.94)
    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.20, 0.25, 0.29, 1.00)
    colors[clr.FrameBgHovered]       = ImVec4(0.12, 0.20, 0.28, 1.00)
    colors[clr.FrameBgActive]        = ImVec4(0.09, 0.12, 0.14, 1.00)
    colors[clr.TitleBg]              = ImVec4(0.53, 0.20, 0.16, 0.65)
    colors[clr.TitleBgActive]        = ImVec4(0.56, 0.14, 0.14, 1.00)
    colors[clr.TitleBgCollapsed]     = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.MenuBarBg]            = ImVec4(0.15, 0.18, 0.22, 1.00)
    colors[clr.ScrollbarBg]          = ImVec4(0.02, 0.02, 0.02, 0.39)
    colors[clr.ScrollbarGrab]        = ImVec4(0.20, 0.25, 0.29, 1.00)
    colors[clr.ScrollbarGrabHovered] = ImVec4(0.18, 0.22, 0.25, 1.00)
    colors[clr.ScrollbarGrabActive]  = ImVec4(0.09, 0.21, 0.31, 1.00)
    colors[clr.ComboBg]              = ImVec4(0.20, 0.25, 0.29, 1.00)
    colors[clr.CheckMark]            = ImVec4(1.00, 0.28, 0.28, 1.00)
    colors[clr.SliderGrab]           = ImVec4(0.64, 0.14, 0.14, 1.00)
    colors[clr.SliderGrabActive]     = ImVec4(1.00, 0.37, 0.37, 1.00)
    colors[clr.Button]               = ImVec4(0.59, 0.13, 0.13, 1.00)
    colors[clr.ButtonHovered]        = ImVec4(0.69, 0.15, 0.15, 1.00)
    colors[clr.ButtonActive]         = ImVec4(0.67, 0.13, 0.07, 1.00)
    colors[clr.Header]               = ImVec4(0.20, 0.25, 0.29, 0.55)
    colors[clr.HeaderHovered]        = ImVec4(0.98, 0.38, 0.26, 0.80)
    colors[clr.HeaderActive]         = ImVec4(0.98, 0.26, 0.26, 1.00)
    colors[clr.Separator]            = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.SeparatorHovered]     = ImVec4(0.60, 0.60, 0.70, 1.00)
    colors[clr.SeparatorActive]      = ImVec4(0.70, 0.70, 0.90, 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.06, 0.05, 0.07, 1.00)
    colors[clr.CloseButton]          = ImVec4(0.40, 0.39, 0.38, 0.16)
    colors[clr.CloseButtonHovered]   = ImVec4(0.40, 0.39, 0.38, 0.39)
    colors[clr.CloseButtonActive]    = ImVec4(0.40, 0.39, 0.38, 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.25, 1.00, 0.00, 0.43)
    colors[clr.ModalWindowDarkening] = ImVec4(1.00, 0.98, 0.95, 0.73)
end
apply_custom_style()
 
  • Грустно
Реакции: de_clain

goodflex

Активный
280
58
Есть ли какой нибуть гайд как в имгуи сделать херь чтобы темы менять можно было?