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

Vespan

loneliness
Проверенный
2,105
1,633
Как сделать что когда нажал на imgui.Button и около него вывилось сообщения,как тут:
43810
 

Mr_Incognito

Активный
331
50
Как открыть существующий диалог, если известен ид? Ну например меню, диалог ид 722. Как его открыть?
 

Quasper

Известный
834
354
Как открыть существующий диалог, если известен ид? Ну например меню, диалог ид 722. Как его открыть?
Если серверный диалог то ввести команду иначе ты никак не откроешь, если только он не был открыт последним
 
  • Нравится
Реакции: Mr_Incognito

JLCUHA

Участник
28
7
Как хукнуть ид игрока на которого прицелился?
Есть такой код -
Lua:
local valid, per = getCharPlayerIsTargeting(PLAYER_PED)
    if valid and doesCharExist(ped) then
    local result, id = sampGetPlayerIdByCharHandle(ped)
    if result then
      playerTargeting = id
    end
end
Но я не особо понимаю куда его писать чтобы работало
 

Quasper

Известный
834
354
Как хукнуть ид игрока на которого прицелился?
Есть такой код -
Lua:
local valid, per = getCharPlayerIsTargeting(PLAYER_PED)
    if valid and doesCharExist(ped) then
    local result, id = sampGetPlayerIdByCharHandle(ped)
    if result then
      playerTargeting = id
    end
end
Но я не особо понимаю куда его писать чтобы работало
в бесконечный цикл
 

AnWu

Guardian of Order
Всефорумный модератор
4,688
5,188
Как открыть существующий диалог, если известен ид? Ну например меню, диалог ид 722. Как его открыть?
никак. можно повторить визуально, но на адекватных серверах это не имеет смысла. воспроизводи условия открытия диалога
 

Mr_Incognito

Активный
331
50
Ребята, вопрос на миллион! Требуется узнать айди текстдрава, но его не видно, т.к. там куча других айди и они друг на друге. Можно ли как то, кликнув на текстдрав, получить его айди и вывести, например в print()?
никак. можно повторить визуально, но на адекватных серверах это не имеет смысла. воспроизводи условия открытия диалога
Я понял, спс. Я просто наивно думал, что любой диалог можно открыть из любой точки карты по его айдишнику))
 

JLCUHA

Участник
28
7
Ещё один трабл-
Lua:
require 'lib.moonloader'
local imgui = require 'imgui'
local key = require 'vkeys'
local lib = require 'lib.samp.events'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local playerTargeting = -1

local toggle = false
local ImBool1 = imgui.ImBool(false)
local ImBool2 = imgui.ImBool(false)
local ImBool3 = imgui.ImBool(false)
local wind = imgui.ImBool(false)
local settings_window = imgui.ImBool(false)

function imgui.OnDrawFrame()
      imgui.ShowCursor = wind.v
        local sw, sh = getScreenResolution()
    if wind.v then
      imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5)) --положение основного окна
      imgui.SetNextWindowSize(imgui.ImVec2(600, 470), imgui.Cond.FirstUseEver)--размер основного окна
      imgui.Begin('DanielsHelper', wind)
        imgui.PushItemWidth(150)
        imgui.SetCursorPos(imgui.ImVec2(435, 25))
    end imgui.PopItemWidth()
      imgui.SetCursorPos(imgui.ImVec2(7, 50))
      imgui.BeginChild('##id', imgui.ImVec2(580, 30), true)
        if (playerTargeting >= 0) then
          local name = sampGetPlayerNickname(tostring(playerTargeting))
          imgui.Text(u8' Цель: '..name..'('..tostring(playerTargeting)..')')
        end
        if (playerTargeting < 0) then
          imgui.Text(u8' Цель: Not Found')
        end
      imgui.EndChild()
       imgui.SetCursorPos (imgui.ImVec2(7, 85))
       imgui.BeginChild('##1', imgui.ImVec2(190, 180), true)
        local btn_size = imgui.ImVec2(-0.1, 0)
        imgui.Text(u8'Общение')
        imgui.Separator()
          if imgui.Button(u8'Приветствие в чате семьи', btn_size) then
              sampSendChat("/fam Привет!")
          end
          if imgui.Button(u8'Приветствие нового члена!', btn_size) then
              sampSendChat('/fam Добро пожаловать в гей клуб!')
          end
          if imgui.Button(u8'Поздравить с ДР', btn_size) then
             sampSendChat('/fam Поздравляю с ДР! Счастья, здоровья!')
          end
       imgui.EndChild()
       imgui.BeginChild('##2', imgui.ImVec2(190, 180), true)
       imgui.Text(u8'Перс')
       imgui.Separator()
          if imgui.Button(u8'Броня', btn_size) then
              sampSendChat("/armour")
          end
          if imgui.Button(u8'Маска', btn_size) then
              sampSendChat('/mask')
          end
          if imgui.Button(u8'Телефон', btn_size) then
              sampSendChat('/phone')
          end
          if imgui.Button(u8'Статистика', btn_size) then
              sampSendChat('/stats')
          end
          if imgui.Button(u8'Выход из игры', btn_size) then
              sampProcessChatInput ("/q")
          end
        imgui.EndChild()
------------------------------

        imgui.SameLine()

--2 блок
------------------------------
        imgui.SetCursorPos(imgui.ImVec2(204, 85))
        imgui.BeginChild('##3', imgui.ImVec2(190, 180), true)
        imgui.Text(u8'Здоровье')
        imgui.Separator()
          if imgui.Button(u8'Покушать за 300$', btn_size) then
             sampSendClickTextdraw(645)
          end
          if imgui.Button(u8'Нарко 3г', btn_size) then
             sampSendChat('/usedrugs 3')
          end
          if imgui.Button(u8'Попить водяры за 500$', btn_size) then
             sampSendClickTextdraw(644)
          end
        imgui.EndChild()
        imgui.SetCursorPos(imgui.ImVec2(204, 269))
        imgui.BeginChild('##4', imgui.ImVec2(190, 180), true)
        imgui.Text('Cars')
        imgui.Separator()
          if imgui.Button(u8'Заправить', btn_size) then
              sampSendChat("/fillcar")
          end
          if imgui.Button(u8'Починка', btn_size) then
              sampSendChat('/repcar')
          end
          if imgui.Button(u8'Закрыть кар', btn_size) then
              sampSendChat('/lock')
          end
          if imgui.Button(u8'Вставить/вытащить ключи', btn_size) then
              sampSendChat('/key')
          end
        imgui.EndChild()
------------------------------------

        imgui.SameLine()
--3 блок
------------------------------------
        imgui.SetCursorPos(imgui.ImVec2(401, 85))
        imgui.BeginChild('##5', imgui.ImVec2(190, 180), true)
        imgui.Text(u8'В разработке')
        imgui.Separator()
          if imgui.Button(u8'Трейд', btn_size) then
            sampAddChatMessage('/trade'..tostring(playerTargeting), -1)
          end
        imgui.EndChild()
        imgui.SetCursorPos(imgui.ImVec2(401, 269))
        imgui.BeginChild('##6', imgui.ImVec2(190, 180), true)
        imgui.Text(u8'В разработке')
        imgui.Separator()
        imgui.EndChild()
      imgui.End()
end

function main()
  while true do
    wait(0)
    if wasKeyPressed(key.VK_X) then -- активация
        wind.v = not wind.v
    end
    local valid, ped = GetCharPlayerIsTargeting(PLAYER_HANDLE)
     if valid and doesCharExist(ped) then
     local result, id = sampGetPlayerIdByCharHandle(ped)
     if result then
       playerTargeting = id
     end
    end
    imgui.Process = wind.v
  end
end


function apply_custom_style()
    imgui.SwitchContext()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4

    style.WindowRounding = 2.0
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.84)
    style.ChildWindowRounding = 2.0
    style.FrameRounding = 2.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0

    colors[clr.FrameBg]                = ImVec4(0.48, 0.16, 0.16, 0.54)
    colors[clr.FrameBgHovered]         = ImVec4(0.98, 0.26, 0.26, 0.40)
    colors[clr.FrameBgActive]          = ImVec4(0.98, 0.26, 0.26, 0.67)
    colors[clr.TitleBg]                = ImVec4(0.04, 0.04, 0.04, 1.00)
    colors[clr.TitleBgActive]          = ImVec4(0.48, 0.16, 0.16, 1.00)
    colors[clr.TitleBgCollapsed]       = ImVec4(0.00, 0.00, 0.00, 0.51)
    colors[clr.CheckMark]              = ImVec4(0.98, 0.26, 0.26, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.88, 0.26, 0.24, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.98, 0.26, 0.26, 1.00)
    colors[clr.Button]                 = ImVec4(0.98, 0.26, 0.26, 0.40)
    colors[clr.ButtonHovered]          = ImVec4(0.98, 0.26, 0.26, 1.00)
    colors[clr.ButtonActive]           = ImVec4(0.98, 0.06, 0.06, 1.00)
    colors[clr.Header]                 = ImVec4(0.98, 0.26, 0.26, 0.31)
    colors[clr.HeaderHovered]          = ImVec4(0.98, 0.26, 0.26, 0.80)
    colors[clr.HeaderActive]           = ImVec4(0.98, 0.26, 0.26, 1.00)
    colors[clr.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.75, 0.10, 0.10, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.75, 0.10, 0.10, 1.00)
    colors[clr.ResizeGrip]             = ImVec4(0.98, 0.26, 0.26, 0.25)
    colors[clr.ResizeGripHovered]      = ImVec4(0.98, 0.26, 0.26, 0.67)
    colors[clr.ResizeGripActive]       = ImVec4(0.98, 0.26, 0.26, 0.95)
    colors[clr.TextSelectedBg]         = ImVec4(0.98, 0.26, 0.26, 0.35)
    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = ImVec4(0.06, 0.06, 0.06, 0.94)
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = ImVec4(0.43, 0.43, 0.50, 0.50)
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.MenuBarBg]              = ImVec4(0.14, 0.14, 0.14, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]          = ImVec4(0.31, 0.31, 0.31, 1.00)
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    colors[clr.CloseButtonHovered]     = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]      = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.80, 0.80, 0.80, 0.35)
end
apply_custom_style()
Сампфункс - 136: attempt to call global 'GetCharPlayerIsTargeting' (a nil value)
 
Последнее редактирование:

Mr_Incognito

Активный
331
50
Гуру, помогите.
Есть функция, которая отключает вип чат на Аризоне.
Lua:
function vipOff()
    sampSendChat('/phone')
    sampSendDialogResponse(1000, 1, 0, -1)
    sampSendClickTextdraw(2096)
    sampSendDialogResponse(966, 1, 1, -1)
    sampSendDialogResponse(800, 1, 5, -1)
end
Но после всего, остаётся диалог. Как его закрыть?
 

Будущий ИБ

Новичок
1
0
Нужна помощь,как сделать так ,чтобы при использовании команды искался гоночный маркер ,после по синхе ставились координаты перса на этот маркер .