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

Sedoj

Участник
56
1
Для получения названия машины лучше использовать таблицу ид модели, полученной функцией getCarModel - название, например так:

Lua:
g.veh = {
    [400] = "Landstalker",
    [401] = "Bravura",
    [402] = "Buffalo"
    -- т.д. сам допишешь или найдёшь готовую.
},


Что ты конкретно хочешь. Предоставь точную копию из лога строчку и результат, который ты хочешь получить после сравнения
Lua:
if text:match("%[FA%] .+ Family .+: .+") then
    color = argb_to_rgba(join_argb(211, colors.fam.r, colors.fam.g, colors.fam.b))
    return {color, text}
end
Туже процедуру что и выше делал с чатом фамы, все работает: чат изменяет цвет, который я укажу.


Lua:
if text:match("%[A%] Администратор %a+_%a+ %[%d+%]: .+") then
    color = argb_to_rgba(join_argb(211, colors.fam.r, colors.fam.g, colors.fam.b))
    return {color, text}
end
Здесь же просто красится время в чате, которое от timestamp, но мне нужно, чтобы красилось все
 

Smeruxa

Известный
1,304
684
Lua:
if text:match("%[FA%] .+ Family .+: .+") then
    color = argb_to_rgba(join_argb(211, colors.fam.r, colors.fam.g, colors.fam.b))
    return {color, text}
end
Туже процедуру что и выше делал с чатом фамы, все работает: чат изменяет цвет, который я укажу.


Lua:
if text:match("%[A%] Администратор %a+_%a+ %[%d+%]: .+") then
    color = argb_to_rgba(join_argb(211, colors.fam.r, colors.fam.g, colors.fam.b))
    return {color, text}
end
Здесь же просто красится время в чате, которое от timestamp, но мне нужно, чтобы красилось все
значит цвет задается новый {%x}. Попробуй получать значения цветов и экранировать их
UPD. опять же. тебе сказали дать полную строку из чат-лога..
 

Corrygаn

Участник
225
6
Как сделать другой шрифт в Imgui?
Как именно сделать не скажу, скину пример как я импортил шрифт Dopestyle
Код:
local ds_glyph_ranges = imgui.GetIO().Fonts:GetGlyphRangesCyrillic()

function imgui.BeforeDrawFrame()
    if default_font == nil then
        default_font = imgui.GetIO().Fonts:AddFontFromFileTTF(getFolderPath(0x14) .. '\\trebucbd.ttf', 16.0, nil, imgui.GetIO().Fonts:GetGlyphRangesCyrillic())
    end

    if ds_font == nil then
        local font_config = imgui.ImFontConfig()
        font_config.MergeMode = true
        ds_font = imgui.GetIO().Fonts:AddFontFromFileTTF("moonloader/resource/fonts/Dopestyle.ttf", 44.0, font_config, ds_glyph_ranges)
    end
end
Чтобы использовать его перед текстом пиши imgui.PushFont(ds_font) -- в моём случае ds_font
После текста imgui.PopFont()
 

Corrygаn

Участник
225
6
Установи для неё позицию через imgui.SetCursorPosX | imgui.SetCursorPosY
Чтоб табличка с ником и т.д. была справа перенеси чилд1 внутрь чилд2. A вот с фиговой позицией селектора я пока не разобрался C:

upd: если убираю newline - нормально всё встаёт
Мне нужно чтобы селектор был ПОД окошечком с инфой о персе и они оба были слева, в первой колонке, то селектор багается imgui.SetCursorPosY не работает
 

Corrygаn

Участник
225
6
Код:
local farm = imgui.ImBool(false)
selected = 1
local hlopokbot = imgui.ImBool(false)
local menu = {
    u8"Главная",
    u8"Бот для фермы",
    u8"Бот для шахты",
    u8"Другое"
}
local selected_label = imgui.ImInt(1)
local selector_pos = imgui.ImInt(0)

function imgui.Selector(labels, size, selected, pos, speed)
    local rBool = false
    if not speed then speed = 10 end
    if (pos.v < (selected.v * size.y)) then
        pos.v = pos.v + speed
    elseif (pos.v > (selected.v * size.y)) then
        pos.v = pos.v - speed
    end
    imgui.SetCursorPos(imgui.ImVec2(0.00, pos.v))
    local draw_list = imgui.GetWindowDrawList()
    local p = imgui.GetCursorScreenPos()
    local radius = size.y * 0.50
    draw_list:AddRectFilled(imgui.ImVec2(p.x-size.x/2, p.y), imgui.ImVec2(p.x + radius + 1 * (size.x - radius * 2.0), p.y + radius*2), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.ButtonActive]))
    draw_list:AddRectFilled(imgui.ImVec2(p.x-size.x/2, p.y), imgui.ImVec2(p.x + 5, p.y + size.y), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.Button]), 0)
    draw_list:AddCircleFilled(imgui.ImVec2(p.x + radius + 1 * (size.x - radius * 2.0), p.y + radius), radius, imgui.GetColorU32(imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.ButtonActive])), radius/10*12)
    for i = 1, #labels do
        imgui.SetCursorPos(imgui.ImVec2(0, (i * size.y)))
        local p = imgui.GetCursorScreenPos()
        if imgui.InvisibleButton(labels[i], size) then selected.v = i rBool = true end
        if imgui.IsItemHovered() then
            draw_list:AddRectFilled(imgui.ImVec2(p.x-size.x/2, p.y), imgui.ImVec2(p.x + size.x, p.y + size.y), imgui.GetColorU32(imgui.ImVec4(0.58, 0.34, 0.46, 0.20)), radius/10*12)
        end
        imgui.SetCursorPos(imgui.ImVec2(20, (i * size.y + (size.y-imgui.CalcTextSize(labels[i]).y)/2)))
        imgui.Text(labels[i])
    end
    return rBool
end

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

    sampAddChatMessage("[Farm Bot]:" .. white_color .. "Скрипт успешно запущен! Активация на клавишу F2.", 0xFF0033)
    sampAddChatMessage("[Farm Bot]:" .. white_color .. "Обновлений не найдено, вы используете актуальную версию({FF0033}v1.0" .. white_color ..").", 0xFF0033)

    imgui.Process = false
   
    while true do
        wait(0)

        if isKeyJustPressed(0x71) then
            farm.v = not farm.v
            imgui.Process = farm.v
        end

        if farm.v == false then
            imgui.Process = false
        end
    end
end

local sw, sh = getScreenResolution()

function imgui.OnDrawFrame()
    if farm.v then
        imgui.SetNextWindowSize(imgui.ImVec2(900, 525), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin("##1", farm, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
        imgui.NewLine()
        imgui.PushFont(ds_font)
        imgui.Text("Farm Bot")
        imgui.PopFont()
        imgui.Separator()
        imgui.Columns(2, "##columns1", true)
        imgui.SetColumnWidth(-1, 225)
        imgui.BeginChild("##child2", imgui.ImVec2(218, 860), false)
            imgui.BeginChild("##child1", imgui.ImVec2(210, 160), true)
                _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
                nick = sampGetPlayerNickname(id)
                ping = sampGetPlayerPing(id)
                x, y, z = getCharCoordinates(PLAYER_PED)
                imgui.Text(u8"Ваш NickName: " .. nick)
                imgui.Text(u8"Ваш ID: " .. id)
                imgui.Text(u8"Ваш пинг: " .. ping)
                imgui.Text(u8"Ваше местоположение:\nX: " .. math.floor(x) .. "\nY: " .. math.floor(y) .. "\nZ: " .. math.floor(z))
            imgui.EndChild()
            imgui.SetCursorPosY((imgui.GetWindowWidth() - 50) / 5)
            imgui.Selector(menu, imgui.ImVec2(130, 50), selected_label, selector_pos, 10)
        imgui.EndChild()
        imgui.NextColumn()
        imgui.BeginChild("##child3", imgui.ImVec2(657, 440), true)
            if selected_label == 1 then

            elseif selected_label == 2 then
                imgui.NewLine()
                if imgui.ToggleButton(u8"Hlopok", hlopokbot) then
                    lua_thread.create(function()
                        for i = 1, #hlopok do
                            setCharCoordinates(PLAYER_PED, hlopok[i][1], hlopok[i][2], hlopok[i][3])
                            wait(1)
                            setCharKeyDown(0xA4)
                        end
                    end)
                end
                imgui.SameLine()
                imgui.Text(u8"Добыча хлопка")
            elseif selected_label == 3 then

            elseif selected_label == 4 then
               
            end
        imgui.EndChild()
        imgui.End()
    end
end
 

Tol4ek

Активный
217
56
Код:
local farm = imgui.ImBool(false)
selected = 1
local hlopokbot = imgui.ImBool(false)
local menu = {
    u8"Главная",
    u8"Бот для фермы",
    u8"Бот для шахты",
    u8"Другое"
}
local selected_label = imgui.ImInt(1)
local selector_pos = imgui.ImInt(0)

function imgui.Selector(labels, size, selected, pos, speed)
    local rBool = false
    if not speed then speed = 10 end
    if (pos.v < (selected.v * size.y)) then
        pos.v = pos.v + speed
    elseif (pos.v > (selected.v * size.y)) then
        pos.v = pos.v - speed
    end
    imgui.SetCursorPos(imgui.ImVec2(0.00, pos.v))
    local draw_list = imgui.GetWindowDrawList()
    local p = imgui.GetCursorScreenPos()
    local radius = size.y * 0.50
    draw_list:AddRectFilled(imgui.ImVec2(p.x-size.x/2, p.y), imgui.ImVec2(p.x + radius + 1 * (size.x - radius * 2.0), p.y + radius*2), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.ButtonActive]))
    draw_list:AddRectFilled(imgui.ImVec2(p.x-size.x/2, p.y), imgui.ImVec2(p.x + 5, p.y + size.y), imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.Button]), 0)
    draw_list:AddCircleFilled(imgui.ImVec2(p.x + radius + 1 * (size.x - radius * 2.0), p.y + radius), radius, imgui.GetColorU32(imgui.GetColorU32(imgui.GetStyle().Colors[imgui.Col.ButtonActive])), radius/10*12)
    for i = 1, #labels do
        imgui.SetCursorPos(imgui.ImVec2(0, (i * size.y)))
        local p = imgui.GetCursorScreenPos()
        if imgui.InvisibleButton(labels[i], size) then selected.v = i rBool = true end
        if imgui.IsItemHovered() then
            draw_list:AddRectFilled(imgui.ImVec2(p.x-size.x/2, p.y), imgui.ImVec2(p.x + size.x, p.y + size.y), imgui.GetColorU32(imgui.ImVec4(0.58, 0.34, 0.46, 0.20)), radius/10*12)
        end
        imgui.SetCursorPos(imgui.ImVec2(20, (i * size.y + (size.y-imgui.CalcTextSize(labels[i]).y)/2)))
        imgui.Text(labels[i])
    end
    return rBool
end

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

    sampAddChatMessage("[Farm Bot]:" .. white_color .. "Скрипт успешно запущен! Активация на клавишу F2.", 0xFF0033)
    sampAddChatMessage("[Farm Bot]:" .. white_color .. "Обновлений не найдено, вы используете актуальную версию({FF0033}v1.0" .. white_color ..").", 0xFF0033)

    imgui.Process = false
  
    while true do
        wait(0)

        if isKeyJustPressed(0x71) then
            farm.v = not farm.v
            imgui.Process = farm.v
        end

        if farm.v == false then
            imgui.Process = false
        end
    end
end

local sw, sh = getScreenResolution()

function imgui.OnDrawFrame()
    if farm.v then
        imgui.SetNextWindowSize(imgui.ImVec2(900, 525), imgui.Cond.FirstUseEver)
        imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.Begin("##1", farm, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
        imgui.NewLine()
        imgui.PushFont(ds_font)
        imgui.Text("Farm Bot")
        imgui.PopFont()
        imgui.Separator()
        imgui.Columns(2, "##columns1", true)
        imgui.SetColumnWidth(-1, 225)
        imgui.BeginChild("##child2", imgui.ImVec2(218, 860), false)
            imgui.BeginChild("##child1", imgui.ImVec2(210, 160), true)
                _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
                nick = sampGetPlayerNickname(id)
                ping = sampGetPlayerPing(id)
                x, y, z = getCharCoordinates(PLAYER_PED)
                imgui.Text(u8"Ваш NickName: " .. nick)
                imgui.Text(u8"Ваш ID: " .. id)
                imgui.Text(u8"Ваш пинг: " .. ping)
                imgui.Text(u8"Ваше местоположение:\nX: " .. math.floor(x) .. "\nY: " .. math.floor(y) .. "\nZ: " .. math.floor(z))
            imgui.EndChild()
            imgui.SetCursorPosY((imgui.GetWindowWidth() - 50) / 5)
            imgui.Selector(menu, imgui.ImVec2(130, 50), selected_label, selector_pos, 10)
        imgui.EndChild()
        imgui.NextColumn()
        imgui.BeginChild("##child3", imgui.ImVec2(657, 440), true)
            if selected_label == 1 then

            elseif selected_label == 2 then
                imgui.NewLine()
                if imgui.ToggleButton(u8"Hlopok", hlopokbot) then
                    lua_thread.create(function()
                        for i = 1, #hlopok do
                            setCharCoordinates(PLAYER_PED, hlopok[i][1], hlopok[i][2], hlopok[i][3])
                            wait(1)
                            setCharKeyDown(0xA4)
                        end
                    end)
                end
                imgui.SameLine()
                imgui.Text(u8"Добыча хлопка")
            elseif selected_label == 3 then

            elseif selected_label == 4 then
              
            end
        imgui.EndChild()
        imgui.End()
    end
end
Блин, хз чё тут у тебя. Скорее всего, нужно в функции самого Selected менять значения. Либо Child перенеси ниже, в котом эта кнопка заключена
 

Corrygаn

Участник
225
6
[19:43:42.993049] (error) Central Market.lua: D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:98: stack index 3, expected string, received number: (bad argument into 'void(const classstd::basic_string<char,std::char_traits<char>,std::allocator<char> >&)')
stack traceback:
[C]: in function '__newindex'
D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:98: in function 'iniLoad'
D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:223: in function <D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:215>
[19:43:42.993049] (error) Central Market.lua: Script died due to an error. (08CC8D1C)

Не пойму при чём здесь плохой аргумент? xD
Пытался сделать флудер, и он работал, пока я не сделал иникфг

Lua:
local inicfg = require "inicfg"

local text_buffer1 = imgui.ImBuffer(256)
local text_buffer2 = imgui.ImBuffer(256)
local text_buffer3 = imgui.ImBuffer(256)
local text_buffer4 = imgui.ImBuffer(256)
local text_buffer5 = imgui.ImBuffer(256)
local text_buffer6 = imgui.ImBuffer(256)
local text_buffer7 = imgui.ImBuffer(256)
local text_buffer8 = imgui.ImBuffer(256)
local text_buffer9 = imgui.ImBuffer(256)
local text_buffer10 = imgui.ImBuffer(256)
local text_buffer11 = imgui.ImBuffer(256)
local text_buffer12 = imgui.ImBuffer(256)
local text_zader1 = imgui.ImBuffer(256)
local text_zader2 = imgui.ImBuffer(256)
local text_zader3 = imgui.ImBuffer(256)
local text_zader4 = imgui.ImBuffer(256)
local text_zader5 = imgui.ImBuffer(256)
local text_zader6 = imgui.ImBuffer(256)
local text_zader7 = imgui.ImBuffer(256)
local text_zader8 = imgui.ImBuffer(256)
local text_zader9 = imgui.ImBuffer(256)
local text_zader10 = imgui.ImBuffer(256)
local text_zader11 = imgui.ImBuffer(256)
local text_zader12 = imgui.ImBuffer(256)
local eatingwait = imgui.ImBuffer(256)

local configuration_path = 'Central Market\\flooder.ini'

function iniReset()
    inicfg.save({
        flooder = {
            stfld = "",
            ndfld = "",
            rdfld = "",
            frthfld = "",
            fethfld = "",
            sxthfld = "",
            snthfld = "",
            etthfld = "",
            nethfld = "",
            tnthfld = "",
            enthfld = "",
            tethfld = "",
        },
        zadershka = {
            stzdr = "",
            ndzdr = "",
            rdzdr = "",
            frthzdr = "",
            fethzdr = "",
            sxthzdr = "",
            snthzdr = "",
            etthzdr = "",
            nethzdr = "",
            tnthzdr = "",
            enthzdr = "",
            tethzdr = "",
        }
    }, configuration_path)

    print("[Конфигурационный файл 'flooder.ini' не был найден, скрипт создал его автоматически]")
end

function iniLoad()
    configuration = inicfg.load(nil, configuration_path)

    if configuration == nil then
        iniReset()
    else
        text_buffer1.v = configuration.flooder.stfld
        text_buffer2.v = configuration.flooder.ndfld
        text_buffer3.v = configuration.flooder.rdfld
        text_buffer4.v = configuration.flooder.frthfld
        text_buffer5.v = configuration.flooder.frthfld
        text_buffer6.v = configuration.flooder.sxthfld
        text_buffer7.v = configuration.flooder.snthfld
        text_buffer8.v = configuration.flooder.etthfld
        text_buffer9.v = configuration.flooder.nethfld
        text_buffer10.v = configuration.flooder.tnthfld
        text_buffer11.v = configuration.flooder.enthfld
        text_buffer12.v = configuration.flooder.tethfld
        text_zader1.v = configuration.zadershka.stzdr -- та самая проблемная строка 98
        text_zader2.v = configuration.zadershka.ndzdr
        text_zader3.v = configuration.zadershka.rdzdr
        text_zader4.v = configuration.zadershka.frthzdr
        text_zader5.v = configuration.zadershka.fethzdr
        text_zader6.v = configuration.zadershka.sxthzdr
        text_zader7.v = configuration.zadershka.snthzdr
        text_zader8.v = configuration.zadershka.etthzdr
        text_zader9.v = configuration.zadershka.nethzdr
        text_zader10.v = configuration.zadershka.tnthzdr
        text_zader11.v = configuration.zadershka.enthzdr
        text_zader12.v = configuration.zadershka.tethzdr
    end
end

function iniSave()
    inicfg.save({
        flooder = {
            stfld = text_buffer1.v,
            ndfld = text_buffer2.v,
            rdfld = text_buffer3.v,
            frthfld = text_buffer4.v,
            fethfld = text_buffer5.v,
            sxthfld = text_buffer6.v,
            snthfld = text_buffer7.v,
            etthfld = text_buffer8.v,
            nethfld = text_buffer9.v,
            tnthfld = text_buffer10.v,
            enthfld = text_buffer11.v,
            tethfld = text_buffer12.v,
        },
        zadershka = {
            stzdr = text_zader1.v,
            ndzdr = text_zader2.v,
            rdzdr = text_zader3.v,
            frthzdr = text_zader4.v,
            fethzdr = text_zader5.v,
            sxthzdr = text_zader6.v,
            snthzdr = text_zader7.v,
            etthzdr = text_zader8.v,
            nethzdr = text_zader9.v,
            tnthzdr = text_zader10.v,
            enthzdr = text_zader11.v,
            tethzdr = text_zader12.v,
        }
    }, configuration_path)
end

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

    iniLoad()

    stproflood = false
    ndproflood = false
    rdproflood = false
    fourthproflood = false
    fivethproflood = false
    sixthproflood = false
    seventhproflood = false
    eightthproflood = false
    ninethproflood = false
    tenthproflood = false
    eleventhproflood = false
    twelvethproflood = false

    sampRegisterChatCommand("cm", cmd_cm)

    imgui.Process = false
   
    while true do
        wait(0)

        if main_window_helper.v == false then
            imgui.Process = false
        end
    end
end
 

ARMOR

kjor32 is legend
Модератор
4,847
6,101
Как рендерить скины/транспорт через renderDrawTexture?
 

Corrygan

Новичок
26
1
Как добавить кнопку, нажатие на которое будет создавать инпут текст, но с новой переменной, точнее как добавить кнопку знаю, но как сделать этот функционал не представляю
 

BARRY BRADLEY

Известный
711
176
[19:43:42.993049] (error) Central Market.lua: D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:98: stack index 3, expected string, received number: (bad argument into 'void(const classstd::basic_string<char,std::char_traits<char>,std::allocator<char> >&)')
stack traceback:
[C]: in function '__newindex'
D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:98: in function 'iniLoad'
D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:223: in function <D:\ARIZONA GAMES\bin\Scripts\moonloader\Central Market.lua:215>
[19:43:42.993049] (error) Central Market.lua: Script died due to an error. (08CC8D1C)

Не пойму при чём здесь плохой аргумент? xD
Пытался сделать флудер, и он работал, пока я не сделал иникфг

Lua:
local inicfg = require "inicfg"

local text_buffer1 = imgui.ImBuffer(256)
local text_buffer2 = imgui.ImBuffer(256)
local text_buffer3 = imgui.ImBuffer(256)
local text_buffer4 = imgui.ImBuffer(256)
local text_buffer5 = imgui.ImBuffer(256)
local text_buffer6 = imgui.ImBuffer(256)
local text_buffer7 = imgui.ImBuffer(256)
local text_buffer8 = imgui.ImBuffer(256)
local text_buffer9 = imgui.ImBuffer(256)
local text_buffer10 = imgui.ImBuffer(256)
local text_buffer11 = imgui.ImBuffer(256)
local text_buffer12 = imgui.ImBuffer(256)
local text_zader1 = imgui.ImBuffer(256)
local text_zader2 = imgui.ImBuffer(256)
local text_zader3 = imgui.ImBuffer(256)
local text_zader4 = imgui.ImBuffer(256)
local text_zader5 = imgui.ImBuffer(256)
local text_zader6 = imgui.ImBuffer(256)
local text_zader7 = imgui.ImBuffer(256)
local text_zader8 = imgui.ImBuffer(256)
local text_zader9 = imgui.ImBuffer(256)
local text_zader10 = imgui.ImBuffer(256)
local text_zader11 = imgui.ImBuffer(256)
local text_zader12 = imgui.ImBuffer(256)
local eatingwait = imgui.ImBuffer(256)

local configuration_path = 'Central Market\\flooder.ini'

function iniReset()
    inicfg.save({
        flooder = {
            stfld = "",
            ndfld = "",
            rdfld = "",
            frthfld = "",
            fethfld = "",
            sxthfld = "",
            snthfld = "",
            etthfld = "",
            nethfld = "",
            tnthfld = "",
            enthfld = "",
            tethfld = "",
        },
        zadershka = {
            stzdr = "",
            ndzdr = "",
            rdzdr = "",
            frthzdr = "",
            fethzdr = "",
            sxthzdr = "",
            snthzdr = "",
            etthzdr = "",
            nethzdr = "",
            tnthzdr = "",
            enthzdr = "",
            tethzdr = "",
        }
    }, configuration_path)

    print("[Конфигурационный файл 'flooder.ini' не был найден, скрипт создал его автоматически]")
end

function iniLoad()
    configuration = inicfg.load(nil, configuration_path)

    if configuration == nil then
        iniReset()
    else
        text_buffer1.v = configuration.flooder.stfld
        text_buffer2.v = configuration.flooder.ndfld
        text_buffer3.v = configuration.flooder.rdfld
        text_buffer4.v = configuration.flooder.frthfld
        text_buffer5.v = configuration.flooder.frthfld
        text_buffer6.v = configuration.flooder.sxthfld
        text_buffer7.v = configuration.flooder.snthfld
        text_buffer8.v = configuration.flooder.etthfld
        text_buffer9.v = configuration.flooder.nethfld
        text_buffer10.v = configuration.flooder.tnthfld
        text_buffer11.v = configuration.flooder.enthfld
        text_buffer12.v = configuration.flooder.tethfld
        text_zader1.v = configuration.zadershka.stzdr -- та самая проблемная строка 98
        text_zader2.v = configuration.zadershka.ndzdr
        text_zader3.v = configuration.zadershka.rdzdr
        text_zader4.v = configuration.zadershka.frthzdr
        text_zader5.v = configuration.zadershka.fethzdr
        text_zader6.v = configuration.zadershka.sxthzdr
        text_zader7.v = configuration.zadershka.snthzdr
        text_zader8.v = configuration.zadershka.etthzdr
        text_zader9.v = configuration.zadershka.nethzdr
        text_zader10.v = configuration.zadershka.tnthzdr
        text_zader11.v = configuration.zadershka.enthzdr
        text_zader12.v = configuration.zadershka.tethzdr
    end
end

function iniSave()
    inicfg.save({
        flooder = {
            stfld = text_buffer1.v,
            ndfld = text_buffer2.v,
            rdfld = text_buffer3.v,
            frthfld = text_buffer4.v,
            fethfld = text_buffer5.v,
            sxthfld = text_buffer6.v,
            snthfld = text_buffer7.v,
            etthfld = text_buffer8.v,
            nethfld = text_buffer9.v,
            tnthfld = text_buffer10.v,
            enthfld = text_buffer11.v,
            tethfld = text_buffer12.v,
        },
        zadershka = {
            stzdr = text_zader1.v,
            ndzdr = text_zader2.v,
            rdzdr = text_zader3.v,
            frthzdr = text_zader4.v,
            fethzdr = text_zader5.v,
            sxthzdr = text_zader6.v,
            snthzdr = text_zader7.v,
            etthzdr = text_zader8.v,
            nethzdr = text_zader9.v,
            tnthzdr = text_zader10.v,
            enthzdr = text_zader11.v,
            tethzdr = text_zader12.v,
        }
    }, configuration_path)
end

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

    iniLoad()

    stproflood = false
    ndproflood = false
    rdproflood = false
    fourthproflood = false
    fivethproflood = false
    sixthproflood = false
    seventhproflood = false
    eightthproflood = false
    ninethproflood = false
    tenthproflood = false
    eleventhproflood = false
    twelvethproflood = false

    sampRegisterChatCommand("cm", cmd_cm)

    imgui.Process = false
   
    while true do
        wait(0)

        if main_window_helper.v == false then
            imgui.Process = false
        end
    end
end
Господи.. циклы и таблицы для слабаков....
 
  • Ха-ха
Реакции: user390868

BARRY BRADLEY

Известный
711
176
Как добавить кнопку, нажатие на которое будет создавать инпут текст, но с новой переменной, точнее как добавить кнопку знаю, но как сделать этот функционал не представляю
Lua:
if imgui.Button(u8("Кнопка")) then
   input = not input
end
if input then
  if imgui.InputText("Text", buffer) then
     -- code
  end
end
Если нужно создавать несколько инпутов по нажатии на кнопку, то в кнопке добавляй в таблицу новый input: tableInput[#tableInput+1] = imgui.Buffer(1000), после чего просто через for выводи инпуты:
Lua:
for key, val in pairs(tableInput) do
  if val then
    if imgui.InputText("Text##"..key, val) then
      -- code
    end
  end
end