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

Cosmo

Известный
Друг
646
2,601
Как менять игровой ID у игроков/себя локально? Через rpc onSetPlayerName только ник меняется :(
 
  • Нравится
Реакции: MR_Lua

Ant

Новичок
2
0
Всем привет. Имеются два вопроса, которые меня мучают на протяжении нескольких месяцев. Естественно, перед тем как сюда писать - долго и мучительно пытался разобраться сам, но, увы, не получилось.

1. Как сделать у imgui.Selectable текст по центру, как imgui.Button? На гитхабе находил функцию стиля (хз как ещё это назвать), но её нет именно в imgui для MoonLoader.
2. Как закрыть imgui окно по нажатию на клавишу ESC? Как только не пытался, пауза всё-ровно ставится.

Заранее спасибо.
 

krol88

Участник
58
12

samartinell1

Участник
98
14
Код:
function fre_cmd(freid)
  if rank ~= '5' then sampSendChat('/free '..freid)
  elseif #freid == 0 and rank == '5' then sampAddChatMessage(tg..' Чтобы освободить игрока, введите /fre ID',main_color)
  elseif #freid ~= 0 and rank == '5' then
    rpnamefree, rpsurnamefree = string.match(sampGetPlayerNickname(freid), '(.+)_(.+)')
    sampSendChat('Если вы хотите воспользоваться услугами адвоката, назовите своё имя и фамилию.')
    sampAddChatMessage(tg..' Когда человек назовёт имя и фамилию, нажмите клавишу "J", чтобы продолжить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Хорошо, скажите пожалуйста, вы ООП?')
    sampSendChat('/n Если Вас посадили с 6 звёздами, админы или ФБР, адвокаты Вас не смогут освободить.')
    sampAddChatMessage(tg..' Нажмите клавишу "J", чтобы продолжить или "K", чтобы отменить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('В таком случае я могу Вас обслужить, сейчас подготовлю все документы.')
    wait(800)
    sampSendChat('/do В руках кейс с необходимой документацией.')
    wait(800)
    sampSendChat('/me открыл кейс и достал нужную бумагу, закрыл кейс и положил бумагу на него')
    wait(800)
    sampSendChat('/me начал оформление документов на УДО на имя '..rpnamefree..' '..rpsurnamefree)
    wait(800)
    sampSendChat('/todo Указав пальцем на места для росписи*Мне необходима ваша подпись здесь и здесь.')
    wait(800)
    sampSendChat('/me передал ручку человеку напротив')
    wait(1000)
    sampSendChat('/n /me расписался')
    sampAddChatMessage(tg.. ' Нажмите "J" для продолженния или "K" для отмены.',main_color)
    repeat
      wait(0)
    until sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Документы успешно заполнены, сейчас отправлю заявку на УДО.')
    sampSendChat('/me дал визитку в руки '..rpnamefree)
    sampSendChat('/do Информация на визитке: '..mainIni.config.podrazd_name..' | '..mainIni.config.name..' '..mainIni.config.surname..' | '..mainIni.config.rankname)
    sampSendChat('/free '..freid..' 9000')
    sampAddChatMessage(tg..' Если человека не удалось выпустить, нажмите клавишу "R"')
    if sampIsChatInputActive() == false and isKeyJustPressed(VK_R) then
      sampSendChat('Извините, мне поступила информация, что я не могу Вас обслужить.')
      sampSendChat('/n Вас посадили админы, ФБР, как ООП или по другой причине')
      end
    end
end
Как сделать так, чтобы сделать задержку между сообщениями и чтобы можно было продолжить заполнения документов по клавише J, а по клавише K отменить это? При любой задержке скрипт крашится, lua_thread.create(function() --код end) не имею представления куда вставить, когда в начале вставляю и в конце закрываю - скрипт не работает, помогите пожалуйста :)
 

Fott

Простреленный
3,435
2,280
Код:
function fre_cmd(freid)
  if rank ~= '5' then sampSendChat('/free '..freid)
  elseif #freid == 0 and rank == '5' then sampAddChatMessage(tg..' Чтобы освободить игрока, введите /fre ID',main_color)
  elseif #freid ~= 0 and rank == '5' then
    rpnamefree, rpsurnamefree = string.match(sampGetPlayerNickname(freid), '(.+)_(.+)')
    sampSendChat('Если вы хотите воспользоваться услугами адвоката, назовите своё имя и фамилию.')
    sampAddChatMessage(tg..' Когда человек назовёт имя и фамилию, нажмите клавишу "J", чтобы продолжить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Хорошо, скажите пожалуйста, вы ООП?')
    sampSendChat('/n Если Вас посадили с 6 звёздами, админы или ФБР, адвокаты Вас не смогут освободить.')
    sampAddChatMessage(tg..' Нажмите клавишу "J", чтобы продолжить или "K", чтобы отменить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('В таком случае я могу Вас обслужить, сейчас подготовлю все документы.')
    wait(800)
    sampSendChat('/do В руках кейс с необходимой документацией.')
    wait(800)
    sampSendChat('/me открыл кейс и достал нужную бумагу, закрыл кейс и положил бумагу на него')
    wait(800)
    sampSendChat('/me начал оформление документов на УДО на имя '..rpnamefree..' '..rpsurnamefree)
    wait(800)
    sampSendChat('/todo Указав пальцем на места для росписи*Мне необходима ваша подпись здесь и здесь.')
    wait(800)
    sampSendChat('/me передал ручку человеку напротив')
    wait(1000)
    sampSendChat('/n /me расписался')
    sampAddChatMessage(tg.. ' Нажмите "J" для продолженния или "K" для отмены.',main_color)
    repeat
      wait(0)
    until sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Документы успешно заполнены, сейчас отправлю заявку на УДО.')
    sampSendChat('/me дал визитку в руки '..rpnamefree)
    sampSendChat('/do Информация на визитке: '..mainIni.config.podrazd_name..' | '..mainIni.config.name..' '..mainIni.config.surname..' | '..mainIni.config.rankname)
    sampSendChat('/free '..freid..' 9000')
    sampAddChatMessage(tg..' Если человека не удалось выпустить, нажмите клавишу "R"')
    if sampIsChatInputActive() == false and isKeyJustPressed(VK_R) then
      sampSendChat('Извините, мне поступила информация, что я не могу Вас обслужить.')
      sampSendChat('/n Вас посадили админы, ФБР, как ООП или по другой причине')
      end
    end
end
Как сделать так, чтобы сделать задержку между сообщениями и чтобы можно было продолжить заполнения документов по клавише J, а по клавише K отменить это? При любой задержке скрипт крашится, lua_thread.create(function() --код end) не имею представления куда вставить, когда в начале вставляю и в конце закрываю - скрипт не работает, помогите пожалуйста :)
Вот тебе пример
Lua:
    sampSendChat('В таком случае я могу Вас обслужить, сейчас подготовлю все документы.')
    lua_thread.create(function()
    wait(800)
  sampSendChat('/do В руках кейс с необходимой документацией.')
end)
 
  • Нравится
Реакции: samartinell1

Мира

Участник
455
9
Model modelId = getCharModel(Ped ped)
получение скина персонажа, думаю if сделаешь сам

пробовал, но не получается. если знаешь, то сможешь вставить в мой скрипт?
Lua:
require "lib.moonloader"
local key = require 'vkeys'

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

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage(tag.."Helper for Damiano {d1db1c}by Mira Damiano", -1)
    repeat wait(0) until isSampAvailable()
    while true do
        wait(0)
        if isKeyJustPressed(110)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/uninvite  Выселен!")
            sampSetChatInputCursor(10)
        end
        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)
                    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")
                    sampSendChat("/me обозначил место в банде")
            end
        end
        if isKeyJustPressed(106)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/usedrugs 3")
        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 Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
        
        if isKeyJustPressed(101)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/vr Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
        
        if isKeyJustPressed(102)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/rt Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
            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
 

Bredd Lane

Известный
423
348
[ML] (error) CARFUNCS: cannot resume non-suspended coroutine
stack traceback:
[C]: in function 'copy'
D:\Games\GTA San Andreas Clear\moonloader\CARFUNCS.lua:3372: in function <D:\Games\GTA San Andreas Clear\moonloader\CARFUNCS.lua:3070>
[ML] (error) CARFUNCS: Script died due to an error. (08D0206C)

В чем ошибка?
 

krol88

Участник
58
12
Код:
function fre_cmd(freid)
  if rank ~= '5' then sampSendChat('/free '..freid)
  elseif #freid == 0 and rank == '5' then sampAddChatMessage(tg..' Чтобы освободить игрока, введите /fre ID',main_color)
  elseif #freid ~= 0 and rank == '5' then
    rpnamefree, rpsurnamefree = string.match(sampGetPlayerNickname(freid), '(.+)_(.+)')
    sampSendChat('Если вы хотите воспользоваться услугами адвоката, назовите своё имя и фамилию.')
    sampAddChatMessage(tg..' Когда человек назовёт имя и фамилию, нажмите клавишу "J", чтобы продолжить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Хорошо, скажите пожалуйста, вы ООП?')
    sampSendChat('/n Если Вас посадили с 6 звёздами, админы или ФБР, адвокаты Вас не смогут освободить.')
    sampAddChatMessage(tg..' Нажмите клавишу "J", чтобы продолжить или "K", чтобы отменить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('В таком случае я могу Вас обслужить, сейчас подготовлю все документы.')
    wait(800)
    sampSendChat('/do В руках кейс с необходимой документацией.')
    wait(800)
    sampSendChat('/me открыл кейс и достал нужную бумагу, закрыл кейс и положил бумагу на него')
    wait(800)
    sampSendChat('/me начал оформление документов на УДО на имя '..rpnamefree..' '..rpsurnamefree)
    wait(800)
    sampSendChat('/todo Указав пальцем на места для росписи*Мне необходима ваша подпись здесь и здесь.')
    wait(800)
    sampSendChat('/me передал ручку человеку напротив')
    wait(1000)
    sampSendChat('/n /me расписался')
    sampAddChatMessage(tg.. ' Нажмите "J" для продолженния или "K" для отмены.',main_color)
    repeat
      wait(0)
    until sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Документы успешно заполнены, сейчас отправлю заявку на УДО.')
    sampSendChat('/me дал визитку в руки '..rpnamefree)
    sampSendChat('/do Информация на визитке: '..mainIni.config.podrazd_name..' | '..mainIni.config.name..' '..mainIni.config.surname..' | '..mainIni.config.rankname)
    sampSendChat('/free '..freid..' 9000')
    sampAddChatMessage(tg..' Если человека не удалось выпустить, нажмите клавишу "R"')
    if sampIsChatInputActive() == false and isKeyJustPressed(VK_R) then
      sampSendChat('Извините, мне поступила информация, что я не могу Вас обслужить.')
      sampSendChat('/n Вас посадили админы, ФБР, как ООП или по другой причине')
      end
    end
end
Как сделать так, чтобы сделать задержку между сообщениями и чтобы можно было продолжить заполнения документов по клавише J, а по клавише K отменить это? При любой задержке скрипт крашится, lua_thread.create(function() --код end) не имею представления куда вставить, когда в начале вставляю и в конце закрываю - скрипт не работает, помогите пожалуйста :)

Lua:
local ev = require 'lib.samp.events'
local isActive = false

function ev.onServerMessage(color, text)
    if text:find("Здесь текст который пишется если игрока не получилось выпустить") and isActive then
        -- по желанию можно добавить and color == цвет сообщения когда не удалось выпустить, чтобы наверняка
        -- чтобы узнать цвет пропиши в этом же хуке sampAddChatMessage(color, -1) в месте где нету условий if
        lua_thread.create(function()
            sampSendChat('Извините, мне поступила информация, что я не могу Вас обслужить.')
            wait(800)
            sampSendChat('/n Вас посадили админы, ФБР, как ООП или по другой причине')
        end)
    end
    if text:find("(.+) расписался") or text:find("(.+) росписался") and isActive then
        lua_thread.create(function()
            -- сообщение 1
            wait(800)
            -- сообщение 2 и так далее
            isActive = false
        end)
    end
end

function fre_cmd(freid)
  if rank ~= '5' then sampSendChat('/free '..freid)
  elseif #freid == 0 and rank == '5' then sampAddChatMessage(tg..' Чтобы освободить игрока, введите /fre ID',main_color)
  elseif #freid ~= 0 and rank == '5' then
    rpnamefree, rpsurnamefree = string.match(sampGetPlayerNickname(freid), '(.+)_(.+)')
    isActive = true
    sampSendChat('Если вы хотите воспользоваться услугами адвоката, назовите своё имя и фамилию.')
    sampAddChatMessage(tg..' Когда человек назовёт имя и фамилию, нажмите клавишу "J", чтобы продолжить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J)
    sampSendChat('Хорошо, скажите пожалуйста, вы ООП?')
    sampSendChat('/n Если Вас посадили с 6 звёздами, админы или ФБР, адвокаты Вас не смогут освободить.')
    sampAddChatMessage(tg..' Нажмите клавишу "J", чтобы продолжить или "K", чтобы отменить.',main_color)
    repeat
      wait(0)
    until
    sampIsChatInputActive() == false and isKeyJustPressed(VK_J) and isActive
    sampSendChat('В таком случае я могу Вас обслужить, сейчас подготовлю все документы.')
    wait(800)
    sampSendChat('/do В руках кейс с необходимой документацией.')
    wait(800)
    sampSendChat('/me открыл кейс и достал нужную бумагу, закрыл кейс и положил бумагу на него')
    wait(800)
    sampSendChat('/me начал оформление документов на УДО на имя '..rpnamefree..' '..rpsurnamefree)
    wait(800)
    sampSendChat('/todo Указав пальцем на места для росписи*Мне необходима ваша подпись здесь и здесь.')
    wait(800)
    sampSendChat('/me передал ручку человеку напротив')
    wait(1000)
    sampSendChat('/n /me расписался')
    sampAddChatMessage(tg.. ' "K" для отмены.',main_color)
end

-- мейн
while true do
    wait(0)
    if isKeyJustPressed(VK_K) and isActive and not sampIsChatInputActive then isActive = false sampAddChatMessage("Отменено", -1) end
end

попробуй так. не проверял. если ошибка - лог кидай
пробовал, но не получается. если знаешь, то сможешь вставить в мой скрипт?
Lua:
require "lib.moonloader"
local key = require 'vkeys'

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

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage(tag.."Helper for Damiano {d1db1c}by Mira Damiano", -1)
    repeat wait(0) until isSampAvailable()
    while true do
        wait(0)
        if isKeyJustPressed(110)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/uninvite  Выселен!")
            sampSetChatInputCursor(10)
        end
        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)
                    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")
                    sampSendChat("/me обозначил место в банде")
            end
        end
        if isKeyJustPressed(106)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/usedrugs 3")
        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 Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
       
        if isKeyJustPressed(101)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/vr Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
       
        if isKeyJustPressed(102)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/rt Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
            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
не вижу обновления в скрипте. попробую вписать.
 
  • Нравится
Реакции: samartinell1

krol88

Участник
58
12
пробовал, но не получается. если знаешь, то сможешь вставить в мой скрипт?
Lua:
require "lib.moonloader"
local key = require 'vkeys'

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

function main()
    if not isSampLoaded() and not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage(tag.."Helper for Damiano {d1db1c}by Mira Damiano", -1)
    repeat wait(0) until isSampAvailable()
    while true do
        wait(0)
        if isKeyJustPressed(110)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/uninvite  Выселен!")
            sampSetChatInputCursor(10)
        end
        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)
                    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")
                    sampSendChat("/me обозначил место в банде")
            end
        end
        if isKeyJustPressed(106)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/usedrugs 3")
        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 Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
       
        if isKeyJustPressed(101)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/vr Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
       
        if isKeyJustPressed(102)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/rt Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
            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
Код:
script_version("1.0")
script_version_number(1)

require "lib.moonloader"
local key = require 'vkeys'
local dlstatus = require('moonloader').download_status
local inicfg = require 'inicfg'
local tag = "{d1db1c}[Damiano Helper] {FFFFFF}"

state = false
local uurl = "link" -- ini file url link from github
local upath = getWorkingDirectory() .. "/config/vers.ini"
local surl = "link" -- script file url link from github
local spath = thisScript().path

function main()

    if not isSampLoaded() and not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampAddChatMessage(tag.."Helper for Damiano {d1db1c}by Mira Damiano", -1)

    downloadUrlToFile(uurl,upath,function(id, status)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            upd = inicfg.load(nil, upath)
            if tonumber(upd.vers.number) > thisScript().version_num then
                sampAddChatMessage("текущая версия: " .. thisScript().version .. ", версия с сервера: " .. upd.vers.text)
                state = true
            end
            os.remove(upath)
        end
    end)

    repeat wait(0) until isSampAvailable()

    while true do
        wait(0)

        if state then
            downloadUrlToFile(surl, spath, function(id, status)
                sampAddChatMessage("обновлён", -1)
                thisScript():reload()
            end)
        end

        if isKeyJustPressed(110)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSetChatInputEnabled(true)
            sampSetChatInputText("/uninvite  Выселен!")
            sampSetChatInputCursor(10)
        end
        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)
                    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")
                    sampSendChat("/me обозначил место в банде")
            end
        end
        if isKeyJustPressed(106)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/usedrugs 3")
        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 Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
        
        if isKeyJustPressed(101)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/vr Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        end
        
        if isKeyJustPressed(102)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
        then
            sampSendChat("/rt Проходит Набор в \"Vagos\". Принимаем на 7 майку ! Мы в GPS 8 - 3")
        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
попробуй так
забыл добавить иник:
INI:
[vers]
number=1
text=1.0
 

sep

Известный
673
76
при первом вкл имгуи окна это работает норм
но когда следуший раз окно вкл , мышка из поле быстро уходит ГДЕ Я НАКАСЯЧИЛ ?

код:
local bind1 = imgui.ImBuffer('' .. (mainIni.bind.bind1), 256)
local bind2 = imgui.ImBuffer('' .. (mainIni.bind.bind2), 256)
--ИТД ЕЩЕ 23 РАЗА

imgui.InputText(u8:decode'1  ', bind1)
imgui.SameLine(nil, 5)
if imgui.Button(u8'сохранить1') then
    mainIni.bind.bind1 = bind1.v
    inicfg.save(mainIni, directIni)
    sampAddChatMessage(u8:decode(mainIni.bind.bind1), -1)
end
--
--
imgui.InputText(u8:decode'2  ', bind2)
imgui.SameLine(nil, 5)
if imgui.Button(u8'сохранить2') then
    mainIni.bind.bind2 = bind2.v
    inicfg.save(mainIni, directIni)
    sampAddChatMessage(u8:decode(mainIni.bind.bind2), -1)
end
-- итд ЕЩЕ 23 РАЗ
 

krol88

Участник
58
12
при первом вкл имгуи окна это работает норм
но когда следуший раз окно вкл , мышка из поле быстро уходит ГДЕ Я НАКАСЯЧИЛ ?

код:
local bind1 = imgui.ImBuffer('' .. (mainIni.bind.bind1), 256)
local bind2 = imgui.ImBuffer('' .. (mainIni.bind.bind2), 256)
--ИТД ЕЩЕ 23 РАЗА

imgui.InputText(u8:decode'1  ', bind1)
imgui.SameLine(nil, 5)
if imgui.Button(u8'сохранить1') then
    mainIni.bind.bind1 = bind1.v
    inicfg.save(mainIni, directIni)
    sampAddChatMessage(u8:decode(mainIni.bind.bind1), -1)
end
--
--
imgui.InputText(u8:decode'2  ', bind2)
imgui.SameLine(nil, 5)
if imgui.Button(u8'сохранить2') then
    mainIni.bind.bind2 = bind2.v
    inicfg.save(mainIni, directIni)
    sampAddChatMessage(u8:decode(mainIni.bind.bind2), -1)
end
-- итд ЕЩЕ 23 РАЗ
зачем так топорно? для чего
imgui.InputTextMultiline(const char* label,char* buf,size_t buf_size,const ImVec2& size = ImVec20,)?