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

yorenov

Участник
42
29
raksamp

lua:
function onReceiveRpc(id, bs)
    print(id)
    if id == 93 then
        local color = bs:readInt32()
        local lengthText = bs:readInt32()
        if lengthText > 0 and lengthText < 10000 then
            local chatText = bs:readString(lengthText)
            print(chatText)
            if chatText:find("подбросил Вас") then
                print("Админ подбросил вас!")
                require("requests").get(AnsiToUtf8(link .. '- Админ подбросил или тепнул тебя! Ник: ' .. nickname .. ' | Сервер: ' .. getServerName()))
                reconnect(60000)
            end
        end
    end
end
чат не хукает, кто пакеты скушал? Как фиксить?

raksamp

lua:
function onReceiveRpc(id, bs)
    print(id)
    if id == 93 then
        local color = bs:readInt32()
        local lengthText = bs:readInt32()
        if lengthText > 0 and lengthText < 10000 then
            local chatText = bs:readString(lengthText)
            print(chatText)
            if chatText:find("подбросил Вас") then
                print("Админ подбросил вас!")
                require("requests").get(AnsiToUtf8(link .. '- Админ подбросил или тепнул тебя! Ник: ' .. nickname .. ' | Сервер: ' .. getServerName()))
                reconnect(60000)
            end
        end
    end
end
чат не хукает, кто пакеты скушал? Как фиксить?
upd, решение гениальное. Функция должна называться onReceiveRPC()
 
Последнее редактирование:
  • Вау
Реакции: XRLM

vuyy

Активный
136
56
Пытаюсь округлить кнопку(mimgui) ну чета не работает attempt to call field 'PushStyleVar' (a nil value)
 
Последнее редактирование:
  • Клоун
Реакции: Air_Official

XRLM

Известный
2,562
882
raksamp

lua:
function onReceiveRpc(id, bs)
    print(id)
    if id == 93 then
        local color = bs:readInt32()
        local lengthText = bs:readInt32()
        if lengthText > 0 and lengthText < 10000 then
            local chatText = bs:readString(lengthText)
            print(chatText)
            if chatText:find("подбросил Вас") then
                print("Админ подбросил вас!")
                require("requests").get(AnsiToUtf8(link .. '- Админ подбросил или тепнул тебя! Ник: ' .. nickname .. ' | Сервер: ' .. getServerName()))
                reconnect(60000)
            end
        end
    end
end
чат не хукает, кто пакеты скушал? Как фиксить?


upd, решение гениальное. Функция должна называться onReceiveRPC()
а еще проще взять либу самп луа и не ебаться с чтением пакетов

Пытаюсь округлить кнопку(mimgui) ну чета не работает attempt to call field 'PushStyleVar' (a nil value)
imgui.PushStyleVarFloat(imgui.StyleVar.FrameRounding, 10)
imgui.PopStyleVar()
для цвета будет imgui.PushStyleColor и первый аргумент imgui.Col.Button к примеру
 
  • Клоун
  • Нравится
Реакции: trefa, Air_Official и vuyy

vuyy

Активный
136
56
Как сменить цвет этой брови ? +когда нажимаешь на кнопки там такой же цвет при нажатие его бы тоже заменить
1709253878612.png
 
  • Клоун
Реакции: Air_Official

Emily Grey

Активный
166
55
Здрасте, не знаю почему но сохраняет одно число в параметре ввода цен после перезагрузки скрипта
Lua:
local imgui     = require 'mimgui'
local fa        = require 'fAwesome5'
local se        = require 'samp.events'
local inicfg    = require 'inicfg'
local encoding  = require 'encoding'
local ffi       = require 'ffi'

encoding.default = 'CP1251'
u8 = encoding.UTF8
local new, str, sizeof = imgui.new, ffi.string, ffi.sizeof

local resX, resY = getScreenResolution()
local start = false
local timeDo = false
local move = false
local cursor = false
local fontsList = {'Arial', 'Bahnschrift', 'Candara', 'Georgia', 'Segoe UI', 'Tahoma', 'Ubuntu'}
local fonts  = imgui.new['const char*'][#fontsList](fontsList)

local directIni = ('fishTracker.ini')
local ini = inicfg.load(inicfg.load({
    main = {
        saveStats = true,
        time = 0,
        cotton = 0,
        line = 0,
        texttyt = 0,
        textet = 0,
        dye = 0,
        display = false,
        method = 0,
        posX = resX / 12,
        posY = resY / 2,
    },
    render = {
        fontName = 0,
        fontSize = 12,
    },
}, directIni))
inicfg.save(ini, directIni)

local window = imgui.new.bool()
local overlay = imgui.new.bool()
local render = imgui.new.bool()
local saveStats = imgui.new.bool(ini.main.saveStats)
local time = imgui.new.int(0)
local cotton = imgui.new.int(0)
local line = imgui.new.int(0)
local dye = imgui.new.int(0)
local larec = imgui.new.int(0)
local tojilka = imgui.new.int(0)
local money = imgui.new.int(0)
local method = imgui.new.int(0)
local display = imgui.new.bool(ini.main.display)
local fontName = imgui.new.int(0)
local fontSize = imgui.new.int(0)
local texttyt = imgui.new.char[256]()
local textet = imgui.new.char[257]()

function main()
    while not isSampAvailable() do wait(0) end
    mainFont = renderCreateFont(fontsList[ini.render.fontName+1], ini.render.fontSize, 5)
    sampRegisterChatCommand('fish', function()
        window[0] = not window[0]
    end)
    lua_thread.create(countTime)
    sampAddChatMessage('[Fish Tracker]{AAAAAA}: {DEFFDB}Меню скрипта - {E32D39}/fish{DEFFDB}.', 0xAFFF5E)
    if saveStats[0] then
        time[0] = ini.main.time
        line[0] = ini.main.line
        cotton[0] = ini.main.cotton
        dye[0] = ini.main.dye
        textet[0] = ini.main.textet
        texttyt[0] = ini.main.texttyt
    end
    fontSize[0] = ini.render.fontSize
    fontName[0] = ini.render.fontName
    method[0] = ini.main.method
    while true do
        wait(0)

        if render[0] then
            renderFontDrawText(mainFont, string.format('%s\nРыба: %s\nЛарец рыболова: %s\nЗаточка для бронежилета: %s', get_clock(time[0]), line[0], cotton[0], dye[0]), ini.main.posX, ini.main.posY, 0xFFFFFFFF)
            if renderFontDrawClickableText(true, mainFont, timeDo and 'Остановка счётчика' or 'Запуск счётчика', ini.main.posX, ini.main.posY+ini.render.fontSize*6.7, 0xFFD0D0D0, 0xFFA0A0A0) then
                state()
            end
            if renderFontDrawClickableText(true, mainFont, 'Сброс счётчика', ini.main.posX, ini.main.posY+ini.render.fontSize*8.2, 0xFFD0D0D0, 0xFFA0A0A0) then
                reset()
            end
        end
        if isKeyDown(0x12) and isKeyJustPressed(0x01) then
            cursor = not cursor
            showCursor(cursor, cursor)
        end
        if move then
            
            showCursor(true, true)
            window[0] = false
            ini.main.posX, ini.main.posY = getCursorPos()
            if isKeyJustPressed(0x20) then
                move = false
                window[0] = true
                inicfg.save(ini, directIni)
                sampAddChatMessage('[Fish Tracker]{AAAAAA}: {DEFFDB}Позиция сохранена!', 0xAFFF5E)
                showCursor(false, false)
            end
        end

        if display[0] then
            if method[0] == 0 then
                overlay[0] = true
                render[0] = false
            elseif method[0] == 1 then
                overlay[0] = false
                render[0] = true
            end
            save()
        else
            overlay[0] = false
            render[0] = false
        end
    end
end

imgui.OnInitialize(function()
    a_la_vk_style()
    imgui.GetIO().IniFilename = nil
    local config = imgui.ImFontConfig()
    config.MergeMode = true
    local glyph_ranges = imgui.GetIO().Fonts:GetGlyphRangesCyrillic()
    local iconRanges = imgui.new.ImWchar[3](fa.min_range, fa.max_range, 0)
    imgui.GetIO().Fonts:AddFontFromFileTTF('trebucbd.ttf', 14.0, nil, glyph_ranges)
    icon = imgui.GetIO().Fonts:AddFontFromFileTTF('moonloader/resource/fonts/fa-solid-900.ttf', 10, config, iconRanges)
    medium = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 23.0, _, glyph_ranges)
end)

local frame = imgui.OnFrame(
    function() return window[0] end,
    function(player)
        local sizeX, sizeY = 500, 350
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('##mainWindow', window, imgui.WindowFlags.NoDecoration, imgui.WindowFlags.NoResize)
        imgui.PushFont(medium)
        imgui.Text('Fish Tracker')
        imgui.PopFont()
        imgui.SetCursorPos(imgui.ImVec2(imgui.GetWindowSize().x - 25, 7))
        imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(0.25, 0.25, 0.26, 0.0))
        imgui.PushStyleColor(imgui.Col.Border, imgui.ImVec4(0.25, 0.25, 0.26, 0.0))
        imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(0.25, 0.25, 0.26, 0.0))
        imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(0.25, 0.25, 0.26, 0.0))
        if imgui.Button(fa.ICON_FA_TIMES) then
            window[0] = false
            showCursor(false, false)
        end
        imgui.PopStyleColor(4)
        imgui.SetCursorPosY(35)
        imgui.Separator()
        if imgui.Checkbox(fa.ICON_FA_SAVE..u8' Сохранение статистики после перезахода', saveStats) then
            save()
        end
        if imgui.Checkbox(fa.ICON_FA_WINDOW_RESTORE..u8' Отображать статистику.', display) then
            save()
        end
        imgui.NewLine()
        imgui.Text(u8'Метод отображения статистики:')
        if imgui.RadioButtonIntPtr(u8'Имгуи окно', method, 0) then
            save()
        end
        imgui.SameLine()
        if imgui.RadioButtonIntPtr(u8'Рендер текста', method, 1) then
            save()
        end
        if imgui.Button(fa.ICON_FA_ARROWS_ALT..u8' Изменить расположение статистики.', imgui.ImVec2(-1,20)) then
            move = true
            sampAddChatMessage('[Fish Tracker]{AAAAAA}: {DEFFDB}Для сохранения положения нажмите {E32D39}ПРОБЕЛ{DEFFDB}.', 0xAFFF5E)
        end
        imgui.NewLine()
        imgui.Text(u8'Стиль рендера:')
        if imgui.Combo(u8'Шрифт текста', fontName, fonts, #fontsList) then
            save()
            mainFont = renderCreateFont(fontsList[ini.render.fontName+1], ini.render.fontSize, 5)
        end
        if imgui.InputInt(u8'Размер текста', fontSize, 1, 1) then
            save()
            mainFont = renderCreateFont(fontsList[ini.render.fontName+1], ini.render.fontSize, 5)
        end
        imgui.Text(u8'Цены:')
        if imgui.InputText(u8"Ларец", texttyt, 256) then
            save()
        end
        if imgui.InputText(u8"Заточка", textet, 257) then
            save()
        end
        imgui.End()
    end
)

imgui.OnFrame(function() return overlay[0] and not isGamePaused() end,
function()
        local sizeX, sizeY = 210, 105
        imgui.SetNextWindowPos(imgui.ImVec2(ini.main.posX+sizeX/2-10, ini.main.posY+sizeY), imgui.Cond.Always, imgui.ImVec2(1, 1))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)
        imgui.Begin('', overlay, imgui.WindowFlags.NoDecoration + imgui.WindowFlags.NoMove + imgui.WindowFlags.AlwaysAutoResize)
        imgui.CustomText(fa.ICON_FA_CLOCK..' '..get_clock(time[0]), _, 'center')
        imgui.CustomText(fa.ICON_FA_SEEDLING..u8' Рыба: '..line[0], _, 'center')
        imgui.CustomText(fa.ICON_FA_SEEDLING..u8' Ларец рыболова : '..cotton[0], _, 'center')
        imgui.CustomText(fa.ICON_FA_SEEDLING..u8' Заточка для бронежилета: '..dye[0], _, 'center')
        imgui.CustomText(fa.ICON_FA_SEEDLING..u8' Заработано с ларцов: '..larec[0], _, 'center')
        imgui.CustomText(fa.ICON_FA_SEEDLING..u8' Заработано с заточек: '..tojilka[0], _, 'center')
        imgui.CustomText(fa.ICON_FA_SEEDLING..u8' Всего денег заработано '..money[0], _, 'center')
        if timeDo then
            imgui.CustomText(u8'Остановка счётчика', 'start','center', _, imgui.ImVec4(0.6, 0.6, 0.6, 1.0 ))
        else
            imgui.CustomText(u8'Запуск счётчика', 'start','center', _, imgui.ImVec4(0.6, 0.6, 0.6, 1.0 ))
        end
        imgui.CustomText(u8'Сброс счётчика', 'reset', 'center', imgui.ImVec4(0.6, 0.6, 0.6, 1.0 ))
        imgui.End()
    end
).HideCursor = true
                                        
function save()
    ini.main.overlay = overlay[0]
    ini.main.render = render[0]
    ini.main.saveStats = saveStats[0]
    ini.main.method = method[0]
    ini.main.display = display[0]
    ini.render.fontSize = fontSize[0]
    ini.render.fontName = fontName[0]
    if saveStats[0] then
        ini.main.time = time[0]
        ini.main.line = line[0]
        ini.main.cotton = cotton[0]
        ini.main.texttyt = texttyt[0]
        ini.main.textet = textet[0]
        ini.main.dye = dye[0]
    end
    inicfg.save(ini, directIni)
end

function state()
    timeDo = not timeDo
    sampAddChatMessage('{AFFF5E}[Fish Tracker]{AAAAAA}: {DEFFDB}'..(timeDo and 'Счётчик запущен!' or 'Счётчик остановлен!'), -1)
end

function reset()
    time[0] = 0
    cotton[0] = 0
    line[0] = 0
    dye[0] = 0
    textet[0] = 0
    texttyt[0] = 0
    timeDo = false
    save()
    sampAddChatMessage('[Fish Tracker]{AAAAAA}: {DEFFDB}Счётчик сброшен!', 0xAFFF5E)
end

function imgui.CustomText(text, action, pos, color)
    if pos == 'center' then
        imgui.SetCursorPosX(imgui.GetWindowSize().x / 2 - imgui.CalcTextSize(text).x / 2)
    end
    if color ~= nil then
        imgui.TextColored(color, text)
    else
        imgui.Text(text)
    end
    if imgui.IsItemClicked() then
        if action == 'reset' then
            reset()
        end
        if action == 'start' then
            state()
        end
    end
end

function countTime()
    while true do
        wait(1000)
        if timeDo then
            time[0] = time[0] + 1
            ini.main.time = time[0]
            inicfg.save(ini, directIni)
        end
    end
end                                       
function renderFontDrawClickableText(active, font, text, posX, posY, color, color_hovered)
    local cursorX, cursorY = getCursorPos()
    local lenght = renderGetFontDrawTextLength(font, text)
    local height = renderGetFontDrawHeight(font)
    local hovered = false
    local result = false
    if active and cursorX > posX and cursorY > posY and cursorX < posX + lenght and cursorY < posY + height then
        hovered = true
        if isKeyJustPressed(0x01) then
            result = true
        end
    end   
    renderFontDrawText(font, text, posX, posY, hovered and color_hovered or color)
    return result
end

function get_clock(time)
    local timezone_offset = 86400 - os.date('%H', 0) * 3600
    if tonumber(time) >= 86400 then onDay = true else onDay = false end
    return os.date((onDay and math.floor(time / 86400)..'д ' or '')..'%H:%M:%S', time + timezone_offset)
end


function se.onServerMessage(color, text)
    if timeDo and text:find("Вам был добавлен предмет 'Заточка для бронежилета'. Откройте инвентарь, используйте клавишу 'Y' или /invent") then
        dye[0] = dye[0] + 1
        tojilka[0] = textet[0]*dye[0]
        save()
    end
    if timeDo and text:find("%[Рыбалка%]{ffffff} Вы поймали рыбу") then
         line[0] = line[0] + 1
        save()
    end
     if timeDo and text:find("Вам был добавлен предмет 'Ларец рыболова'. Откройте инвентарь, используйте клавишу 'Y' или /invent") then
        cotton[0] = cotton[0] + 1
        larec[0] = texttyt[0]*cotton[0]
        save()
        money[0] = larec[0] + tojilka[0]
    end
end

function imgui.Link(link, text)
    text = text or link
    local tSize = imgui.CalcTextSize(text)
    local p = imgui.GetCursorScreenPos()
    local DL = imgui.GetWindowDrawList()
    local col = { 0xFFFF7700, 0xFFFF9900 }
    if imgui.InvisibleButton("##" .. link, tSize) then os.execute("explorer " .. link) end
    local color = imgui.IsItemHovered() and col[1] or col[2]
    DL:AddText(p, color, text)
    DL:AddLine(imgui.ImVec2(p.x, p.y + tSize.y), imgui.ImVec2(p.x + tSize.x, p.y + tSize.y), color)
end

function a_la_vk_style()
    imgui.SwitchContext()

    -- -- -- -- -- B O R D E R S -- -- -- -- --
    imgui.GetStyle().WindowBorderSize = 0.0
    imgui.GetStyle().ChildBorderSize  = 0.0
    imgui.GetStyle().PopupBorderSize  = 0.0
    imgui.GetStyle().FrameBorderSize  = 0.0
    imgui.GetStyle().TabBorderSize    = 0.0


    -- -- -- -- -- R O U D I N G -- -- -- -- --
    imgui.GetStyle().WindowRounding     = 8.0
    imgui.GetStyle().ChildRounding      = 0.0
    imgui.GetStyle().FrameRounding      = 4.0
    imgui.GetStyle().PopupRounding      = 2.0
    imgui.GetStyle().ScrollbarRounding  = 5.0
    imgui.GetStyle().GrabMinSize        = 2.0
    imgui.GetStyle().GrabRounding       = 2.0

    imgui.GetStyle().ItemSpacing       =  imgui.ImVec2(3, 5)

    -- -- -- -- -- C O L O R S -- -- -- -- --
    imgui.GetStyle().Colors[imgui.Col.Text]                    = imgui.ImVec4(0.95, 0.95, 0.95, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TextDisabled]            = imgui.ImVec4(0.48, 0.49, 0.50, 1.00)
    imgui.GetStyle().Colors[imgui.Col.WindowBg]                = imgui.ImVec4(0.08, 0.08, 0.08, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ChildBg]                 = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
    imgui.GetStyle().Colors[imgui.Col.PopupBg]                 = imgui.ImVec4(0.08, 0.08, 0.08, 0.94)
    imgui.GetStyle().Colors[imgui.Col.Border]                  = imgui.ImVec4(0.43, 0.43, 0.50, 0.50)
    imgui.GetStyle().Colors[imgui.Col.BorderShadow]            = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
    imgui.GetStyle().Colors[imgui.Col.FrameBg]                 = imgui.ImVec4(0.13, 0.13, 0.13, 1.00)
    imgui.GetStyle().Colors[imgui.Col.FrameBgHovered]          = imgui.ImVec4(0.13, 0.13, 0.13, 1.00)
    imgui.GetStyle().Colors[imgui.Col.FrameBgActive]           = imgui.ImVec4(0.13, 0.13, 0.13, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TitleBg]                 = imgui.ImVec4(0.13, 0.13, 0.13, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TitleBgActive]           = imgui.ImVec4(0.13, 0.13, 0.13, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TitleBgCollapsed]        = imgui.ImVec4(0.20, 0.20, 0.20, 1.00)
    imgui.GetStyle().Colors[imgui.Col.MenuBarBg]               = imgui.ImVec4(0.13, 0.13, 0.13, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarBg]             = imgui.ImVec4(0.26, 0.26, 0.26, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarGrab]           = imgui.ImVec4(0.41, 0.41, 0.41, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarGrabHovered]    = imgui.ImVec4(0.48, 0.48, 0.48, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ScrollbarGrabActive]     = imgui.ImVec4(0.63, 0.63, 0.63, 1.00)
    imgui.GetStyle().Colors[imgui.Col.CheckMark]               = imgui.ImVec4(0.47, 0.67, 0.93, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SliderGrab]              = imgui.ImVec4(0.59, 0.59, 0.59, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SliderGrabActive]        = imgui.ImVec4(0.75, 0.75, 0.75, 1.00)
    imgui.GetStyle().Colors[imgui.Col.Button]                  = imgui.ImVec4(0.15, 0.15, 0.15, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ButtonHovered]           = imgui.ImVec4(0.23, 0.23, 0.23, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ButtonActive]            = imgui.ImVec4(0.30, 0.30, 0.30, 1.00)
    imgui.GetStyle().Colors[imgui.Col.Header]                  = imgui.ImVec4(0.16, 0.16, 0.16, 1.00)
    imgui.GetStyle().Colors[imgui.Col.HeaderHovered]           = imgui.ImVec4(0.23, 0.23, 0.23, 1.00)
    imgui.GetStyle().Colors[imgui.Col.HeaderActive]            = imgui.ImVec4(0.23, 0.23, 0.23, 1.00)
    imgui.GetStyle().Colors[imgui.Col.Separator]               = imgui.ImVec4(1.00, 1.00, 1.00, 0.70)
    imgui.GetStyle().Colors[imgui.Col.SeparatorHovered]        = imgui.ImVec4(0.26, 0.26, 0.26, 1.00)
    imgui.GetStyle().Colors[imgui.Col.SeparatorActive]         = imgui.ImVec4(0.26, 0.26, 0.26, 1.00)
    imgui.GetStyle().Colors[imgui.Col.ResizeGrip]              = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
    imgui.GetStyle().Colors[imgui.Col.ResizeGripHovered]       = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
    imgui.GetStyle().Colors[imgui.Col.ResizeGripActive]        = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
    imgui.GetStyle().Colors[imgui.Col.Tab]                     = imgui.ImVec4(0.14, 0.14, 0.14, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TabHovered]              = imgui.ImVec4(0.26, 0.26, 0.26, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TabActive]               = imgui.ImVec4(0.47, 0.67, 0.93, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TabUnfocused]            = imgui.ImVec4(0.47, 0.67, 0.93, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TabUnfocusedActive]      = imgui.ImVec4(0.47, 0.67, 0.93, 1.00)
    imgui.GetStyle().Colors[imgui.Col.TextSelectedBg]          = imgui.ImVec4(0.14, 0.36, 0.76, 1.00)
end
 

mooh

Известный
160
45
Здрасте, не знаю почему но сохраняет одно число в параметре ввода цен после перезагрузки скрипта
Привет, замени imgui.new.char на imgui.new.int на 57 и 58 строке.
Вроде все работает, и цены сохраняются полностью
1709296955022.png
 
  • Влюблен
Реакции: Emily Grey

Emily Grey

Активный
166
55
Привет, замени imgui.new.char на imgui.new.int на 57 и 58 строке.
Вроде все работает, и цены сохраняются полностью
Посмотреть вложение 233379
[ML] (error) fish.lua: E:\ARIZONA\moonloader\fish.lua:189: bad argument #2 to 'InputText' (cannot convert 'int [256]' to 'char *')
stack traceback:
[C]: in function 'InputText'
E:\ARIZONA\moonloader\fish.lua:189: in function '_draw'
E:\ARIZONA\moonloader\lib\mimgui\init.lua:107: in function <E:\ARIZONA\moonloader\lib\mimgui\init.lua:91>
[ML] (error) fish.lua: Script died due to an error. (96C4ED1C)
 

mooh

Известный
160
45
[ML] (error) fish.lua: E:\ARIZONA\moonloader\fish.lua:189: bad argument #2 to 'InputText' (cannot convert 'int [256]' to 'char *')
stack traceback:
[C]: in function 'InputText'
E:\ARIZONA\moonloader\fish.lua:189: in function '_draw'
E:\ARIZONA\moonloader\lib\mimgui\init.lua:107: in function <E:\ARIZONA\moonloader\lib\mimgui\init.lua:91>
[ML] (error) fish.lua: Script died due to an error. (96C4ED1C)
Удали fishTracker.ini и перезагрузи
 
  • Влюблен
Реакции: Emily Grey

Emily Grey

Активный
166
55
Удали fishTracker.ini и перезагрузи
[ML] (error) fish.lua: E:\ARIZONA\moonloader\fish.lua:189: bad argument #2 to 'InputText' (cannot convert 'int [256]' to 'char *')
stack traceback:
[C]: in function 'InputText'
E:\ARIZONA\moonloader\fish.lua:189: in function '_draw'
E:\ARIZONA\moonloader\lib\mimgui\init.lua:107: in function <E:\ARIZONA\moonloader\lib\mimgui\init.lua:91>
[ML] (error) fish.lua: Script died due to an error. (225A029C)
 

vuyy

Активный
136
56
1709317980333.png

как можно сделать так чтобы при нажатие кнопки она светилась зелёным и типо она нажата и включена если нажать ещё раз то переставала светится типо офнута
(mimgui)
 
  • Клоун
Реакции: Air_Official

хромиус)

спокойно, это всего лишь слива
Друг
4,958
3,236
Посмотреть вложение 233420
как можно сделать так чтобы при нажатие кнопки она светилась зелёным и типо она нажата и включена если нажать ещё раз то переставала светится типо офнута
(mimgui)
только под мимгуи переделать надо,но там ничего трудного нет
 

MLycoris

Режим чтения
Проверенный
1,826
1,882
Посмотреть вложение 233420
как можно сделать так чтобы при нажатие кнопки она светилась зелёным и типо она нажата и включена если нажать ещё раз то переставала светится типо офнута
(mimgui)
могу такой вариант предложить
Lua:
function imgui.stBut(text,bool,size)
    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(bool and 0.2 or 0.98,bool and 0.8 or 0.26,bool and 0.2 or 0.26, 0.55))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(bool and 0.2 or 0.98,bool and 0.8 or 0.26,bool and 0.2 or 0.26, 0.55))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(bool and 0.2 or 0.98,bool and 0.8 or 0.26,bool and 0.2 or 0.26, 0.55))
    local button = imgui.Button(text, size)
    imgui.PopStyleColor(3)
    return button
end

или прост цветная кнопка, там уже свои цвета укажешь
Lua:
function imgui.ColoredButton(text,hex,trans,size)
    local r,g,b = tonumber("0x"..hex:sub(1,2)), tonumber("0x"..hex:sub(3,4)), tonumber("0x"..hex:sub(5,6))
    if tonumber(trans) ~= nil and tonumber(trans) < 101 and tonumber(trans) > 0 then a = trans else a = 60 end
    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(r/255, g/255, b/255, a/100))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(r/255, g/255, b/255, a/100))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(r/255, g/255, b/255, a/100))
    local button = imgui.Button(text, size)
    imgui.PopStyleColor(3)
    return button
end
 
  • Влюблен
Реакции: vuyy

vuyy

Активный
136
56
могу такой вариант предложить
Lua:
function imgui.stBut(text,bool,size)
    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(bool and 0.2 or 0.98,bool and 0.8 or 0.26,bool and 0.2 or 0.26, 0.55))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(bool and 0.2 or 0.98,bool and 0.8 or 0.26,bool and 0.2 or 0.26, 0.55))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(bool and 0.2 or 0.98,bool and 0.8 or 0.26,bool and 0.2 or 0.26, 0.55))
    local button = imgui.Button(text, size)
    imgui.PopStyleColor(3)
    return button
end

или прост цветная кнопка, там уже свои цвета укажешь
Lua:
function imgui.ColoredButton(text,hex,trans,size)
    local r,g,b = tonumber("0x"..hex:sub(1,2)), tonumber("0x"..hex:sub(3,4)), tonumber("0x"..hex:sub(5,6))
    if tonumber(trans) ~= nil and tonumber(trans) < 101 and tonumber(trans) > 0 then a = trans else a = 60 end
    imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(r/255, g/255, b/255, a/100))
    imgui.PushStyleColor(imgui.Col.ButtonHovered, imgui.ImVec4(r/255, g/255, b/255, a/100))
    imgui.PushStyleColor(imgui.Col.ButtonActive, imgui.ImVec4(r/255, g/255, b/255, a/100))
    local button = imgui.Button(text, size)
    imgui.PopStyleColor(3)
    return button
end
а есть у меня например 2 кнопки, как сделать так чтобы если я 2 активирую 2 светились? я просто нажимаю 1 кнопку потом 2 и 1 сразу выключается и включается 2
 
  • Клоун
Реакции: Air_Official

MLycoris

Режим чтения
Проверенный
1,826
1,882
а есть у меня например 2 кнопки, как сделать так чтобы если я 2 активирую 2 светились? я просто нажимаю 1 кнопку потом 2 и 1 сразу выключается и включается 2
их состояние ведь хранится где-то? Вот простой пример с таблицей
Lua:
--вне тела мимгуи
local buttons = {
    {name = 'buttonOne', status = false},
    {name = 'buttonTwo', status = false},
    {name = 'buttonThree', status = false},
}

--в мимгуи
for k, v in pairs(buttons) do
    if imgui.stBut(v.name,v.status) then
        v.status = not v.status
    end
end