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

ufdhbi

Известный
Проверенный
1,455
861
Как получить оружие в руках игрока?
sampAddChatMessage(getCurrentCharWeapon(i), 0xFFD00000) - вылетает (где i - id существующего игрока на экране )
sampAddChatMessage(getCurrentCharWeapon(PlayerPed), 0xFFD00000) - возвращает свое
надо не айди а хэндл, получай хэндл с помощью айди
Lua:
function onWindowMessage(msg, wparam, lparam)
    if msg == 0x100 or msg == 0x101 then
        if (wparam == 0x1B and imgui_window.bEnable.v) and not isPauseMenuActive() then -- и тут не забудь переменную поменять, 0x1B это VK_ESCAPE
            consumeWindowMessage(true, false)
            if msg == 0x101 then
                imgui_window.bEnable.v = false -- тут переменнаяя твоего окна
            end
        end
    end
end
Про CollapsingHeader:
Lua:
if imgui.CollapsingHeader("Open", false) then
  -- code
end
 
  • Нравится
Реакции: D3AMWYT
D

deleted-user-204957

Гость
Парни такой вопрос как сделать так что бы при нажатии на ESC закрывалось окно Imgui но не выходило в меню игры.
И еще как сделать так что бы окно Imgui не сохраняло открытие imgui.ColapsingHeader то есть я открыл выбрал в нем кнопку и меню закрылось, но когда я его открою мне нужно что бы imgui.ColapsingHeader были скрыты
Lua:
addEventHandler("onWindowMessage", function (msg, wparam, lparam)
    if wparam == key.VK_ESCAPE then -- or wparam == key.VK_TAB
        if Название Окна.v then Название Окна.v = false consumeWindowMessage(true, true) end
    end
end)
 
  • Нравится
Реакции: D3AMWYT

S-Sirius

Известный
353
21
Можете кинуть простой пример использование и сохранение данный inicfg? Либо кинуть скрипт где есть данная фишка
 

daite na_vodky

Известный
147
47
почему выводит сообщение при отрицательном id, несмотря на проверку?
Lua:
local sampev = require "lib.samp.events"



function sampev.onSendCommand(cmd)
    if cmd:find("/id ") then
        lua_thread.create(thread)
        id = cmd:match("%d+")
        id = tonumber(id)
    end
end

function thread()
local level = sampGetPlayerScore(id)
local hex = (("%06X"):format(bit.band(sampGetPlayerColor(id), 0xFFFFFF)))
wait(150)
    if hex == 'FFFFFF' then org = 'Homeless'
        elseif hex == 'fsaforg = ' then org = 'Hells angels'
        elseif hex == '526651' then org = 'Outlaws'
        elseif hex == 'A58E54' then org = 'Bandidos'
        elseif hex == '6300F8' then org = 'Columbian Mafia'
        elseif hex == '9EFF4F' then org = 'Mexican Mafia'
        elseif hex == 'FF0000' then org = 'Yakuza'
        elseif hex == 'AF2FF3' then org = 'Ballas'
        elseif hex == '00EEEE' then org = 'Aztec'
        elseif hex == 'FBD400' then org = 'Vagos'
        elseif hex == '6666FF' then org = 'Rifa'
        elseif hex == '009900' then org = 'Grove'
        elseif hex == '000CFF' then org = 'FBI'
        elseif hex == '1060AC' then org = 'Police'
        elseif hex == 'FF4F00' then org = 'Mass Media'
        elseif hex == 'FF52A4' then org = 'Ministry of Health'
        elseif hex == '704214' then org = 'Ministry of Defence'
        elseif hex == 'E6FB01' then org = 'Government'
        elseif hex == 'FFE7BA' then org = 'Autoschool'
        elseif hex == '7A7667' then org = 'Mask'
end
    if id==nil or id<0 then return false else
        sampAddChatMessage(string.format('lvl: {%s}%u{FFFFFF}, org: {%s}%s', hex, level, hex, org), -1)
    end
org = nil
end
 

Aniki

🐰
Администратор
1,225
1,507
почему выводит сообщение при отрицательном id, несмотря на проверку?
Lua:
local sampev = require "lib.samp.events"



function sampev.onSendCommand(cmd)
    if cmd:find("/id ") then
        lua_thread.create(thread)
        id = cmd:match("%d+")
        id = tonumber(id)
    end
end

function thread()
local level = sampGetPlayerScore(id)
local hex = (("%06X"):format(bit.band(sampGetPlayerColor(id), 0xFFFFFF)))
wait(150)
    if hex == 'FFFFFF' then org = 'Homeless'
        elseif hex == 'fsaforg = ' then org = 'Hells angels'
        elseif hex == '526651' then org = 'Outlaws'
        elseif hex == 'A58E54' then org = 'Bandidos'
        elseif hex == '6300F8' then org = 'Columbian Mafia'
        elseif hex == '9EFF4F' then org = 'Mexican Mafia'
        elseif hex == 'FF0000' then org = 'Yakuza'
        elseif hex == 'AF2FF3' then org = 'Ballas'
        elseif hex == '00EEEE' then org = 'Aztec'
        elseif hex == 'FBD400' then org = 'Vagos'
        elseif hex == '6666FF' then org = 'Rifa'
        elseif hex == '009900' then org = 'Grove'
        elseif hex == '000CFF' then org = 'FBI'
        elseif hex == '1060AC' then org = 'Police'
        elseif hex == 'FF4F00' then org = 'Mass Media'
        elseif hex == 'FF52A4' then org = 'Ministry of Health'
        elseif hex == '704214' then org = 'Ministry of Defence'
        elseif hex == 'E6FB01' then org = 'Government'
        elseif hex == 'FFE7BA' then org = 'Autoschool'
        elseif hex == '7A7667' then org = 'Mask'
end
    if id==nil or id<0 then return false else
        sampAddChatMessage(string.format('lvl: {%s}%u{FFFFFF}, org: {%s}%s', hex, level, hex, org), -1)
    end
org = nil
end
потому что ты никак не передаешь ее в тред. вообще лучше сделать ее сразу в хуке до вызова функции треда
 

daite na_vodky

Известный
147
47
потому что ты никак не передаешь ее в тред. вообще лучше сделать ее сразу в хуке до вызова функции треда
так? ничего не изменилось. Покажи, пожалуйста, наглядно. А я завтра проснусь и пойму, что дурак.

Lua:
function sampev.onSendCommand(cmd)
    if cmd:find("/id ") then
        id = cmd:match("%d+")
        id = tonumber(id)
        lua_thread.create(thread)
    end
end
 

ufdhbi

Известный
Проверенный
1,455
861
так? ничего не изменилось. Покажи, пожалуйста, наглядно. А я завтра проснусь и пойму, что дурак.

Lua:
function sampev.onSendCommand(cmd)
    if cmd:find("/id ") then
        id = cmd:match("%d+")
        id = tonumber(id)
        lua_thread.create(thread)
    end
end
А зачем тебе поток? И создай таблицу с цветами и с ней работай
 

Lucifer Melton

Активный
164
57
почему выводит сообщение при отрицательном id, несмотря на проверку?
Lua:
local sampev = require "lib.samp.events"



function sampev.onSendCommand(cmd)
    if cmd:find("/id ") then
        lua_thread.create(thread)
        id = cmd:match("%d+")
        id = tonumber(id)
    end
end

function thread()
local level = sampGetPlayerScore(id)
local hex = (("%06X"):format(bit.band(sampGetPlayerColor(id), 0xFFFFFF)))
wait(150)
    if hex == 'FFFFFF' then org = 'Homeless'
        elseif hex == 'fsaforg = ' then org = 'Hells angels'
        elseif hex == '526651' then org = 'Outlaws'
        elseif hex == 'A58E54' then org = 'Bandidos'
        elseif hex == '6300F8' then org = 'Columbian Mafia'
        elseif hex == '9EFF4F' then org = 'Mexican Mafia'
        elseif hex == 'FF0000' then org = 'Yakuza'
        elseif hex == 'AF2FF3' then org = 'Ballas'
        elseif hex == '00EEEE' then org = 'Aztec'
        elseif hex == 'FBD400' then org = 'Vagos'
        elseif hex == '6666FF' then org = 'Rifa'
        elseif hex == '009900' then org = 'Grove'
        elseif hex == '000CFF' then org = 'FBI'
        elseif hex == '1060AC' then org = 'Police'
        elseif hex == 'FF4F00' then org = 'Mass Media'
        elseif hex == 'FF52A4' then org = 'Ministry of Health'
        elseif hex == '704214' then org = 'Ministry of Defence'
        elseif hex == 'E6FB01' then org = 'Government'
        elseif hex == 'FFE7BA' then org = 'Autoschool'
        elseif hex == '7A7667' then org = 'Mask'
end
    if id==nil or id<0 then return false else
        sampAddChatMessage(string.format('lvl: {%s}%u{FFFFFF}, org: {%s}%s', hex, level, hex, org), -1)
    end
org = nil
end
Хочешь сделать такую же вещь?))
46290
 
  • Нравится
Реакции: daite na_vodky

getsdfssdfsdfs

Участник
45
0
Всем привет. Помогите сделать хук ближайшего игрока, и вставка этого id в текст( примерно так: sampAddChatMessage('Выбран игрок с '..ID..' Выберите действие.') )
т.е мне нужна функция которая будет хукать этот ID ближайшего игрока.


И кому не сложно проверьте правильно ли.
Lua:
local ped, id = sampGetPlayerIdByCharHandle(ped)

if wasKeyPressed(key.VK_5) then
    if sampIsChatInputActive() then
        sampAddChatMessage('1', cINFO)
    else
        if ped then
        sampAddChatMessage('Ближайший игрок'..id..'', cINFO)
        end
    end
end
 
Последнее редактирование: