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

Мира

Участник
455
9
Ставишь нужный ник, ip и порт и оно коннектит на нужный сервер с нужным ником
Если смена ника не нужна, то можно обойтись 1 строчкой
а можешь пример сделать? пж... просто я в этом 0. для меня это пока сложно. желательно активацию на левый шифт+цифра 0
Lua:
require "lib.moonloader"
local key = require 'vkeys'

local tag = "{DFCFCF}[Damiano Helper] {FFFFFF}"

local imgui = require 'imgui'
local bWnd = imgui.ImBool(false)

local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local band_list = {
    u8"The Rifa",
    u8"Grove Street",
    u8"Los-Santos Vagos",
    u8"East Side Ballas",
    u8"Varios Los Aztecas",
    u8"Night Wolves"
}
local gps = {
'1',
'2',
'3',
'4',
'5',
'10'
}
local inicfg = require 'inicfg'
local mainIni = inicfg.load({
    settings =
    {
        band = 0
    }
}, 'Random.ini')
if not doesFileExist("moonloader/config/Random.ini") then inicfg.save(mainIni, "Random.ini") end
local band = imgui.ImInt(mainIni.settings.band)

local ev = require "lib.samp.events"

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    repeat wait(0) until isSampAvailable()
    sampAddChatMessage(tag.."Helper for Damiano {DFCFCF}by Mira Damiano", -1)
    sampRegisterChatCommand('cc', function() ClearChat() end)
    while true do
        wait(0)
        imgui.Process = bWnd.v
        local res, ped = getCharPlayerIsTargeting(playerHandle)
        if res then
            local proverka = isKeyJustPressed(VK_1)
            if proverka then
                res, ped = getCharPlayerIsTargeting(playerHandle)
                res, id = sampGetPlayerIdByCharHandle(ped)
                id2 = id
                sampSendChat("/faminvite "..id)
            end
        end
        local res, ped = getCharPlayerIsTargeting(playerHandle)
        if res then
            local proverka = isKeyJustPressed(VK_2)
            if proverka then
                res, ped = getCharPlayerIsTargeting(playerHandle)
                res, id = sampGetPlayerIdByCharHandle(ped)
                id2 = id
                sampSendChat("/invite "..id)
                wait(1000)
                sampSendChat("/me выдал бандану человеку напротив")
            end
        end
        local res, ped = getCharPlayerIsTargeting(playerHandle)
        if res then
            local proverka = isKeyJustPressed(VK_3)
            if proverka then
                res, ped = getCharPlayerIsTargeting(playerHandle)
                res, id = sampGetPlayerIdByCharHandle(ped)
                id2 = id
                sampSendChat("/giverank "..id.." 7")
                wait(1000)
                sampSendChat("/me обозначил место в банде")
            end
        end
        if isKeyJustPressed(106)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/usedrugs 3")
        end
        if isKeyJustPressed(77)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            bWnd.v = not bWnd.v
        end
        if isKeyJustPressed(109)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/mask")
        end
        if isKeyJustPressed(107)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/armour")
        end
        if isKeyJustPressed(100)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat('/ad 1 Проходит набор в '..u8:decode(band_list[mainIni.settings.band+1])..'. Принимаем на 7 майку! Мы в GPS 8 - '..gps[mainIni.settings.band+1]..'!')
        end
        if isKeyJustPressed(101)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat('/vr Проходит набор в '..u8:decode(band_list[mainIni.settings.band+1])..'. Принимаем на 7 майку! Мы в GPS 8 - '..gps[mainIni.settings.band+1]..'!')
        end
        if isKeyJustPressed(66)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat(" ")
        end
        if isKeyJustPressed(99)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/giverank  7")
            sampSetChatInputCursor(10)
        end
        if isKeyJustPressed(98)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/invite ")
        end
        if isKeyJustPressed(97)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/faminvite ")
        end
        if isKeyJustPressed(110)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/uninvite  Выселен!!")
            sampSetChatInputCursor(10)
        end
        if isKeyJustPressed(102)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat('/rt Проходит набор в '..u8:decode(band_list[mainIni.settings.band+1])..'. Принимаем на 7 майку! Мы в GPS 8 - '..gps[mainIni.settings.band+1]..'!')
        end
    end
end

function sampSetChatInputCursor(start, finish)
    local finish = finish or start
    local start, finish = tonumber(start), tonumber(finish)
    local mem = require 'memory'
    local chatInfoPtr = sampGetInputInfoPtr()
    local chatBoxInfo = getStructElement(chatInfoPtr, 0x8, 4)
    mem.setint8(chatBoxInfo + 0x11E, start)
    mem.setint8(chatBoxInfo + 0x119, finish)
    return true
end

function imgui.OnDrawFrame()
  imgui.Begin(u8"Damiano Helper", bWnd)
  imgui.PushItemWidth(130)
  if imgui.Combo(u8'The choice of gang', band, band_list)then
        mainIni.settings.band = band.v
        inicfg.save(mainIni, "Random.ini")
    end imgui.PopItemWidth()
    imgui.End()
end

function ev.onSendChat(text)
    if text == '.time' then
        text = '/time'
        sampSendChat(text)
        return false
    end
    if text == '/ешьу' then
        text = '/time'
        sampSendChat(text)
        return false
    end
    if text == '.ешьу' then
        text = '/time'
        sampSendChat(text)
        return false
    end
    if text == '.lmenu' then
        text = '/lmenu'
        sampSendChat(text)
        return false
    end
    if text == '/дьутг' then
        text = '/lmenu'
        sampSendChat(text)
        return false
    end
    if text == '.дьутг' then
        text = '/lmenu'
        sampSendChat(text)
        return false
    end
    if text == '.armour' then
        text = '/armour'
        sampSendChat(text)
        return false
    end
    if text == '/фкьщгк' then
        text = '/armour'
        sampSendChat(text)
        return false
    end
    if text == '/фкьщгк' then
        text = '/armour'
        sampSendChat(text)
        return false
    end
    if text == '.usedrugs 3' then
        text = '/usedrugs'
        sampSendChat(text)
        return false
    end
    if text == '/гыувкгпы 3' then
        text = '/usedrugs'
        sampSendChat(text)
        return false
    end
    if text == '.гыувкгпы 3' then
        text = '/usedrugs'
        sampSendChat(text)
        return false
    end
    if text == '.mask' then
        text = '/mask'
        sampSendChat(text)
        return false
    end
    if text == '/ьфыл' then
        text = '/mask'
        sampSendChat(text)
        return false
    end
    if text == '.ьфыл' then
        text = '/mask'
        sampSendChat(text)
        return false
    end
end

function ClearChat()
    local memory = require "memory"
    memory.fill(sampGetChatInfoPtr() + 306, 0x0, 25200)
    memory.write(sampGetChatInfoPtr() + 306, 25562, 4, 0x0)
    memory.write(sampGetChatInfoPtr() + 0x63DA, 1, 1)
end
 

CaJlaT

Овощ
Модератор
2,806
2,604
а можешь пример сделать? пж... просто я в этом 0. для меня это пока сложно. желательно активацию на левый шифт+цифра 0
Lua:
require "lib.moonloader"
local key = require 'vkeys'

local tag = "{DFCFCF}[Damiano Helper] {FFFFFF}"

local imgui = require 'imgui'
local bWnd = imgui.ImBool(false)

local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local band_list = {
    u8"The Rifa",
    u8"Grove Street",
    u8"Los-Santos Vagos",
    u8"East Side Ballas",
    u8"Varios Los Aztecas",
    u8"Night Wolves"
}
local gps = {
'1',
'2',
'3',
'4',
'5',
'10'
}
local inicfg = require 'inicfg'
local mainIni = inicfg.load({
    settings =
    {
        band = 0
    }
}, 'Random.ini')
if not doesFileExist("moonloader/config/Random.ini") then inicfg.save(mainIni, "Random.ini") end
local band = imgui.ImInt(mainIni.settings.band)

local ev = require "lib.samp.events"

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    repeat wait(0) until isSampAvailable()
    sampAddChatMessage(tag.."Helper for Damiano {DFCFCF}by Mira Damiano", -1)
    sampRegisterChatCommand('cc', function() ClearChat() end)
    while true do
        wait(0)
        imgui.Process = bWnd.v
        local res, ped = getCharPlayerIsTargeting(playerHandle)
        if res then
            local proverka = isKeyJustPressed(VK_1)
            if proverka then
                res, ped = getCharPlayerIsTargeting(playerHandle)
                res, id = sampGetPlayerIdByCharHandle(ped)
                id2 = id
                sampSendChat("/faminvite "..id)
            end
        end
        local res, ped = getCharPlayerIsTargeting(playerHandle)
        if res then
            local proverka = isKeyJustPressed(VK_2)
            if proverka then
                res, ped = getCharPlayerIsTargeting(playerHandle)
                res, id = sampGetPlayerIdByCharHandle(ped)
                id2 = id
                sampSendChat("/invite "..id)
                wait(1000)
                sampSendChat("/me выдал бандану человеку напротив")
            end
        end
        local res, ped = getCharPlayerIsTargeting(playerHandle)
        if res then
            local proverka = isKeyJustPressed(VK_3)
            if proverka then
                res, ped = getCharPlayerIsTargeting(playerHandle)
                res, id = sampGetPlayerIdByCharHandle(ped)
                id2 = id
                sampSendChat("/giverank "..id.." 7")
                wait(1000)
                sampSendChat("/me обозначил место в банде")
            end
        end
        if isKeyJustPressed(106)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/usedrugs 3")
        end
        if isKeyJustPressed(77)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            bWnd.v = not bWnd.v
        end
        if isKeyJustPressed(109)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/mask")
        end
        if isKeyJustPressed(107)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/armour")
        end
        if isKeyJustPressed(100)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat('/ad 1 Проходит набор в '..u8:decode(band_list[mainIni.settings.band+1])..'. Принимаем на 7 майку! Мы в GPS 8 - '..gps[mainIni.settings.band+1]..'!')
        end
        if isKeyJustPressed(101)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat('/vr Проходит набор в '..u8:decode(band_list[mainIni.settings.band+1])..'. Принимаем на 7 майку! Мы в GPS 8 - '..gps[mainIni.settings.band+1]..'!')
        end
        if isKeyJustPressed(66)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat(" ")
        end
        if isKeyJustPressed(99)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/giverank  7")
            sampSetChatInputCursor(10)
        end
        if isKeyJustPressed(98)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/invite ")
        end
        if isKeyJustPressed(97)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/faminvite ")
        end
        if isKeyJustPressed(110)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/uninvite  Выселен!!")
            sampSetChatInputCursor(10)
        end
        if isKeyJustPressed(102)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat('/rt Проходит набор в '..u8:decode(band_list[mainIni.settings.band+1])..'. Принимаем на 7 майку! Мы в GPS 8 - '..gps[mainIni.settings.band+1]..'!')
        end
    end
end

function sampSetChatInputCursor(start, finish)
    local finish = finish or start
    local start, finish = tonumber(start), tonumber(finish)
    local mem = require 'memory'
    local chatInfoPtr = sampGetInputInfoPtr()
    local chatBoxInfo = getStructElement(chatInfoPtr, 0x8, 4)
    mem.setint8(chatBoxInfo + 0x11E, start)
    mem.setint8(chatBoxInfo + 0x119, finish)
    return true
end

function imgui.OnDrawFrame()
  imgui.Begin(u8"Damiano Helper", bWnd)
  imgui.PushItemWidth(130)
  if imgui.Combo(u8'The choice of gang', band, band_list)then
        mainIni.settings.band = band.v
        inicfg.save(mainIni, "Random.ini")
    end imgui.PopItemWidth()
    imgui.End()
end

function ev.onSendChat(text)
    if text == '.time' then
        text = '/time'
        sampSendChat(text)
        return false
    end
    if text == '/ешьу' then
        text = '/time'
        sampSendChat(text)
        return false
    end
    if text == '.ешьу' then
        text = '/time'
        sampSendChat(text)
        return false
    end
    if text == '.lmenu' then
        text = '/lmenu'
        sampSendChat(text)
        return false
    end
    if text == '/дьутг' then
        text = '/lmenu'
        sampSendChat(text)
        return false
    end
    if text == '.дьутг' then
        text = '/lmenu'
        sampSendChat(text)
        return false
    end
    if text == '.armour' then
        text = '/armour'
        sampSendChat(text)
        return false
    end
    if text == '/фкьщгк' then
        text = '/armour'
        sampSendChat(text)
        return false
    end
    if text == '/фкьщгк' then
        text = '/armour'
        sampSendChat(text)
        return false
    end
    if text == '.usedrugs 3' then
        text = '/usedrugs'
        sampSendChat(text)
        return false
    end
    if text == '/гыувкгпы 3' then
        text = '/usedrugs'
        sampSendChat(text)
        return false
    end
    if text == '.гыувкгпы 3' then
        text = '/usedrugs'
        sampSendChat(text)
        return false
    end
    if text == '.mask' then
        text = '/mask'
        sampSendChat(text)
        return false
    end
    if text == '/ьфыл' then
        text = '/mask'
        sampSendChat(text)
        return false
    end
    if text == '.ьфыл' then
        text = '/mask'
        sampSendChat(text)
        return false
    end
end

function ClearChat()
    local memory = require "memory"
    memory.fill(sampGetChatInfoPtr() + 306, 0x0, 25200)
    memory.write(sampGetChatInfoPtr() + 306, 25562, 4, 0x0)
    memory.write(sampGetChatInfoPtr() + 0x63DA, 1, 1)
end
Lua:
if isKeyDown(16) and isKeyJustPressed(48) then -- в беск.цикл
    local ip, port = sampGetCurrentServerAddress()
    sampConnectToServer(ip, port)
end
 
  • Нравится
Реакции: sep

Мира

Участник
455
9
Lua:
if isKeyDown(16) and isKeyJustPressed(48) then -- в беск.цикл
    local ip, port = sampGetCurrentServerAddress()
    sampConnectToServer(ip, port)
end
1593792933041.png

не работает
 

rayprod

Участник
96
1
ибо ты обнуляешь при проверке на дату, а я сказал обнуляй ТОЛЬКО при проверке на время... сейчас комментариев добавлю в код...

Lua:
local inicfg = require 'inicfg'
local mainIni = inicfg.load(
{
    settings = {
        date = os.date('%d.%m.%y'),
        iszeroing = false -- проверка, было ли обнуление в данный день
    }
}
,"Random.ini")
if not doesFileExist("moonloader/config/Random.ini") then inicfg.save(mainIni, "Random.ini") end
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    if mainIni.settings.iszeroing then
        if mainIni.settings.date ~= os.date('%d.%m.%y') then
            mainIni.settings.date = os.date('%d.%m.%y') -- устанавливает текущую дату в ини
            mainIni.settings.iszeroing = false -- ставит обнулению значение false (НЕ был обнулён)
            inicfg.save(mainIni, "Random.ini")
            sampAddChatMessage('Наступил новый день, ждём 17:20 по МСК для обнуления!', -1)
        else
            sampAddChatMessage('Сегодня уже было обнуление!', -1)
        end
    else
        sampAddChatMessage('Сегодня обнуления ещё не было, ждём 17:20 по МСК для обнуления!', -1)
    end
    while true do
        wait(0)
        if not mainIni.settings.iszeroing and os.date( "!%H:%M", os.time(utc) + 3 * 3600 ) >= '17:20' then
            sampAddChatMessage('Произошло обнуление ини!', -1)
            mainIni.settings.date = os.date('%d.%m.%y') -- устанавливает день
            mainIni.settings.iszeroing = true -- ставит данному дню статус обнуления
            --тут добавь обнуление
            inicfg.save(mainIni, "Random.ini")
        end
    end
end

Сделал как ты сказал, начал проверять. Ставлю на пк 23:59 перезахожу и он мне говорит это.
1593802971263.png

Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    if mainIni.config.iszeroing then
        if mainIni.config.date ~= os.date('%d.%m.%y') then
            mainIni.config.date = os.date('%d.%m.%y') -- устанавливает текущую дату в ини
            mainIni.config.iszeroing = false -- ставит обнулению значение false (НЕ был обнулён)
            inicfg.save(mainIni, "Random.ini")
            sampAddChatMessage('Наступил новый день, ждём 05:03 по МСК для обнуления!', -1)
        else
            sampAddChatMessage('Сегодня уже было обнуление!', -1)
        end
    else
        sampAddChatMessage('Сегодня обнуления ещё не было, ждём 05:20 по МСК для обнуления!', -1)
    end
    while true do
    wait(0)
        if not mainIni.config.iszeroing and os.date( "!%H:%M", os.time(utc) + 3 * 3600 ) >= '05:03' then
            sampAddChatMessage('Произошло обнуление ини!', -1)
            mainIni.config.date = os.date('%d.%m.%y') -- устанавливает день
            mainIni.config.iszeroing = true -- ставит данному дню статус обнулен
            mainIni.config.alls = 0
            mainIni.config.ans = 0
            mainIni.config.offwarn = 0
            mainIni.config.offjail = 0
            mainIni.config.offmute = 0
            mainIni.config.nookay = 0
             mainIni.config.prespawn = 0
            mainIni.config.kick = 0
            mainIni.config.warn = 0
            mainIni.config.jail = 0
            mainIni.config.mute = 0
            mainIni.config.ban = 0
            mainIni.config.offban = 0
            mainIni.config.okay = 0
            mainIni.config.slap = 0
            mainIni.config.ans1 = 0
            mainIni.config.offwarn1 = 0
            mainIni.config.offjail1 = 0
            mainIni.config.offmute1 = 0
            mainIni.config.nookay1 = 0
            mainIni.config.prespawn1 = 0
            mainIni.config.kick1 = 0
            mainIni.config.warn1 = 0
            mainIni.config.jail1 = 0
            mainIni.config.mute1 = 0
            mainIni.config.ban1 = 0
            mainIni.config.offban1 = 0
               mainIni.config.okay1 = 0
            mainIni.config.slap1 = 0
            inicfg.save(mainIni, "stats.ini")
        end
    end
end
Сделал как ты сказал, начал проверять. Ставлю на пк 23:59 перезахожу и он мне говорит это.
1593802971263.png

Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    if mainIni.config.iszeroing then
        if mainIni.config.date ~= os.date('%d.%m.%y') then
            mainIni.config.date = os.date('%d.%m.%y') -- устанавливает текущую дату в ини
            mainIni.config.iszeroing = false -- ставит обнулению значение false (НЕ был обнулён)
            inicfg.save(mainIni, "Random.ini")
            sampAddChatMessage('Наступил новый день, ждём 05:03 по МСК для обнуления!', -1)
        else
            sampAddChatMessage('Сегодня уже было обнуление!', -1)
        end
    else
        sampAddChatMessage('Сегодня обнуления ещё не было, ждём 05:20 по МСК для обнуления!', -1)
    end
    while true do
    wait(0)
        if not mainIni.config.iszeroing and os.date( "!%H:%M", os.time(utc) + 3 * 3600 ) >= '05:03' then
            sampAddChatMessage('Произошло обнуление ини!', -1)
            mainIni.config.date = os.date('%d.%m.%y') -- устанавливает день
            mainIni.config.iszeroing = true -- ставит данному дню статус обнулен
            mainIni.config.alls = 0
            mainIni.config.ans = 0
            mainIni.config.offwarn = 0
            mainIni.config.offjail = 0
            mainIni.config.offmute = 0
            mainIni.config.nookay = 0
             mainIni.config.prespawn = 0
            mainIni.config.kick = 0
            mainIni.config.warn = 0
            mainIni.config.jail = 0
            mainIni.config.mute = 0
            mainIni.config.ban = 0
            mainIni.config.offban = 0
            mainIni.config.okay = 0
            mainIni.config.slap = 0
            mainIni.config.ans1 = 0
            mainIni.config.offwarn1 = 0
            mainIni.config.offjail1 = 0
            mainIni.config.offmute1 = 0
            mainIni.config.nookay1 = 0
            mainIni.config.prespawn1 = 0
            mainIni.config.kick1 = 0
            mainIni.config.warn1 = 0
            mainIni.config.jail1 = 0
            mainIni.config.mute1 = 0
            mainIni.config.ban1 = 0
            mainIni.config.offban1 = 0
               mainIni.config.okay1 = 0
            mainIni.config.slap1 = 0
            inicfg.save(mainIni, "stats.ini")
        end
    end
end
Но. Если поменять сразу дату на некст день и на 05:02 он обнуляет в 05:03 как нужно.
 

Мира

Участник
455
9
на арз чтобы написать в репорт надо написать /rep или /report. открывается окно и в это окно надо вписать жб, а потом нажать на enter. возможно сделать так, чтобы когда я писал /rep 228 ДМ, то жб сразу же отправлялась?
 

CaJlaT

Овощ
Модератор
2,806
2,604
Сделал как ты сказал, начал проверять. Ставлю на пк 23:59 перезахожу и он мне говорит это.
Посмотреть вложение 61241
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    if mainIni.config.iszeroing then
        if mainIni.config.date ~= os.date('%d.%m.%y') then
            mainIni.config.date = os.date('%d.%m.%y') -- устанавливает текущую дату в ини
            mainIni.config.iszeroing = false -- ставит обнулению значение false (НЕ был обнулён)
            inicfg.save(mainIni, "Random.ini")
            sampAddChatMessage('Наступил новый день, ждём 05:03 по МСК для обнуления!', -1)
        else
            sampAddChatMessage('Сегодня уже было обнуление!', -1)
        end
    else
        sampAddChatMessage('Сегодня обнуления ещё не было, ждём 05:20 по МСК для обнуления!', -1)
    end
    while true do
    wait(0)
        if not mainIni.config.iszeroing and os.date( "!%H:%M", os.time(utc) + 3 * 3600 ) >= '05:03' then
            sampAddChatMessage('Произошло обнуление ини!', -1)
            mainIni.config.date = os.date('%d.%m.%y') -- устанавливает день
            mainIni.config.iszeroing = true -- ставит данному дню статус обнулен
            mainIni.config.alls = 0
            mainIni.config.ans = 0
            mainIni.config.offwarn = 0
            mainIni.config.offjail = 0
            mainIni.config.offmute = 0
            mainIni.config.nookay = 0
             mainIni.config.prespawn = 0
            mainIni.config.kick = 0
            mainIni.config.warn = 0
            mainIni.config.jail = 0
            mainIni.config.mute = 0
            mainIni.config.ban = 0
            mainIni.config.offban = 0
            mainIni.config.okay = 0
            mainIni.config.slap = 0
            mainIni.config.ans1 = 0
            mainIni.config.offwarn1 = 0
            mainIni.config.offjail1 = 0
            mainIni.config.offmute1 = 0
            mainIni.config.nookay1 = 0
            mainIni.config.prespawn1 = 0
            mainIni.config.kick1 = 0
            mainIni.config.warn1 = 0
            mainIni.config.jail1 = 0
            mainIni.config.mute1 = 0
            mainIni.config.ban1 = 0
            mainIni.config.offban1 = 0
               mainIni.config.okay1 = 0
            mainIni.config.slap1 = 0
            inicfg.save(mainIni, "stats.ini")
        end
    end
end

Но. Если поменять сразу дату на некст день и на 05:02 он обнуляет в 05:03 как нужно.
Так и должно быть
-Чел играл, вышел до обнуления
-зашёл на другой день, стата должна обновится и ждать следующего обновления (5:03)
на арз чтобы написать в репорт надо написать /rep или /report. открывается окно и в это окно надо вписать жб, а потом нажать на enter. возможно сделать так, чтобы когда я писал /rep 228 ДМ, то жб сразу же отправлялась?
Lua:
local samp = require 'samp.events'
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    while true do
        wait(0)
    end
end
function samp.onSendCommand(cmd)
    if cmd:find('/rep (.+)') then
        report = cmd:match('/rep (.+)')
        cmd = '/rep'
        return {cmd}
    end
    if cmd:find('/report (.+)') then
        report = cmd:match('/report (.+)')
        cmd = '/report'
        return {cmd}
    end
    if cmd:find('/ask (.+)') then
        report = cmd:match('/ask (.+)')
        cmd = '/ask'
        return {cmd}
    end
end
function samp.onShowDialog(id,s,t,b1,b2,text)
    if id == 32 and report ~= nil then
        sampSendDialogResponse(id, 1, _, report)
        report = nil
        return false
    end
end
sa-mp-548.png

sa-mp-549.png
 
Последнее редактирование:
  • Нравится
Реакции: Мира

rayprod

Участник
96
1
Так и должно быть
-Чел играл, вышел до обнуления
-зашёл на другой день, стата должна обновится и ждать следующего обновления (5:03)

Крч, зашёл в игру в 23:59, наступил некст день, стата не сбросилась, перезапустил скрипт, сбросилась, хотя время сброса на 05:03 стоит.
Ну думал мб так и нужно, поставил 05:03 и стата не сбросилась. Из-за чего может быть?
 

Maximilian_A_Diamond

Потрачен
7
0
Форматирование кода
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Как вот этот код:
Зациклить 50 раз?

BeginToPoint(2863.590088, 1472.709961, 11.060000, 1.000000, -255, false)
wait(1000)
EmulateKey(VK_F, true)
wait(20)
EmulateKey(VK_F, false)
wait(1000)
BeginToPoint(2864.209961, 1454.699951, 11.760000, 1.000000, -255, false)
wait(1000)
EmulateKey(VK_F, true)
wait(20)
EmulateKey(VK_F, false)
 

Izvinisb

Известный
Проверенный
964
598
Как вот этот код:
Зациклить 50 раз?

BeginToPoint(2863.590088, 1472.709961, 11.060000, 1.000000, -255, false)
wait(1000)
EmulateKey(VK_F, true)
wait(20)
EmulateKey(VK_F, false)
wait(1000)
BeginToPoint(2864.209961, 1454.699951, 11.760000, 1.000000, -255, false)
wait(1000)
EmulateKey(VK_F, true)
wait(20)
EmulateKey(VK_F, false)
for i = 1, 50 do
 

enyag

Известный
345
12
как сделать, что бы при нажатии на кнопку в listbox открывалось ещё одно окно, а предыдущее закрывалось?
 

CaJlaT

Овощ
Модератор
2,806
2,604
а, диалог? серверный или клиентский?