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

Lucifer Melton

Активный
164
57
Учусь ЛУА по видосам theChampGuess, не виводит текст и пишет ошибку.


Код:


Посмотреть вложение 59280
Код:
script_name("Punisher")
script_author("Punisher")
script_description("Test")

require "lib.moonloader"

local tag = '[My first script]:'

function main()

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

sampAddChatMessage("some text", 0xFFFFFF)

    while true do
    wait(0)


    end

end
"end" забыл в 12 строке
while not isSampAvailable() do wait(100) end
 

SHARLYBUTTOM

Известный
598
117
"end" забыл в 12 строке
while not isSampAvailable() do wait(100) end
1592075616066.png
 

neverlane

t.me/neverlane00
Друг
997
1,132
Lua:
local did = {
'-1029514497',
'-16776961'
}
require('samp.events').onPlayerChatBubble = function(playerId, color, distance, duration, message)
        if color == did then
        print('11', -1)
        end
end
Почему не работает?
color это же не массив

Lua:
local did = {
['-1029514497'] = true,
['-16776961'] = true
}
require('samp.events').onPlayerChatBubble = function(playerId, color, distance, duration, message)
        if did[tostring(color)] then
        print('11', -1)
        end
end
 
  • Нравится
Реакции: user31883

Izvinisb

Известный
Проверенный
964
598
Lua:
local did = {
'-1029514497',
'-16776961'
}
require('samp.events').onPlayerChatBubble = function(playerId, color, distance, duration, message)
        if color == did then
        print('11', -1)
        end
end
Почему не работает?
Сравниваешь переменную с массивом
upd: так? а и возможно tostring() надо, я хз какой тип возвращает функа
Lua:
local did =
{
    '-1029514497', -- did[1]
    '-16776961' -- did[2]
}

require'samp.events'.onPlayerChatBubble = function(playerId, color, distance, duration, message)
    if tostring(color) == did[1] or tostring(color) == did[2] then
        print('123')
    end
end
 
Последнее редактирование:
  • Нравится
  • Ха-ха
Реакции: neverlane и user31883

G W

Участник
141
5
Не понял как сохранять true и false в ini при помощи imgui.Checkbox. Можете пример показать.
 

49IME

Участник
32
7
Появился вопрос, можно ли как-то прочекать юзает ли игрок анимку любую в данный момент?

и если да то как?

(хотяб кусочек кода, будьте так добры)
 

G W

Участник
141
5
Почему не сохраняется ? UP: Сделал.
Код:
                imgui.BeginChild("49", imgui.ImVec2(632, 0), true)

                if imgui.Checkbox(u8'AirBrake', checkairbrake) then
                    if checkairbrake.v then
                        mainini.cheat.checkairbrake = true
                        checkairbrake.v = true
                        inicfg.save(mainini, "config/Admin_Tools.ini")
                    end
                if not checkairbrake.v then
                        checkairbrake.v = false
                        mainini.cheat.checkairbrake = false
                        inicfg.save(mainini, "config/Admin_Tools.ini")
                    end
                end

            imgui.SameLine()
            imgui.SetCursorPosY((imgui.GetWindowWidth() - 616) / 2)
            mainini.cheat.checkairbrake = checkairbrake.v
            if imgui.Button(u8"Сохранить", imgui.ImVec2(200, 35)) then
            if inicfg.save(mainIni, directIni) then
            notf.addNotification(string.format("...........................................\nУспех\n...........................................", 228, os.date()), 5)
        end
    end
                imgui.EndChild()
               
checkairbrake =  imgui.ImBool(mainini.cheat.checkairbrake)
Lua:
checkairbrake =  imgui.ImBool(mainini.cheat.checkairbrake)


              imgui.BeginChild("49", imgui.ImVec2(632, 0), true)

                if imgui.Checkbox(u8'AirBrake', checkairbrake) then
                    if checkairbrake.v then
                        mainini.cheat.checkairbrake = checkairbrake.v
                        inicfg.save(mainini, "Admin_Tools.ini")
                    end
                if not checkairbrake.v then
                    mainini.cheat.checkairbrake = checkairbrake.v
                        inicfg.save(mainini, "Admin_Tools.ini")
                    end
                end

            imgui.SameLine()
            imgui.SetCursorPosY((imgui.GetWindowWidth() - 616) / 2)
            if imgui.Button(u8"Сохранить", imgui.ImVec2(200, 35)) then
            if inicfg.save(mainIni, directIni) then
            notf.addNotification(string.format("...........................................\nУспех\n...........................................", 228, os.date()), 5)
        end
    end
                imgui.EndChild()
И нах тебе кнопка сохранить если оно автоматом будет сохранять?
А хз, пусть будет.
 
Последнее редактирование:
  • Ха-ха
Реакции: MaksQ

MaksQ

Известный
967
816
Почему не сохраняется ? UP: Сделал.
Код:
                imgui.BeginChild("49", imgui.ImVec2(632, 0), true)

                if imgui.Checkbox(u8'AirBrake', checkairbrake) then
                    if checkairbrake.v then
                        mainini.cheat.checkairbrake = true
                        checkairbrake.v = true
                        inicfg.save(mainini, "config/Admin_Tools.ini")
                    end
                if not checkairbrake.v then
                        checkairbrake.v = false
                        mainini.cheat.checkairbrake = false
                        inicfg.save(mainini, "config/Admin_Tools.ini")
                    end
                end

            imgui.SameLine()
            imgui.SetCursorPosY((imgui.GetWindowWidth() - 616) / 2)
            mainini.cheat.checkairbrake = checkairbrake.v
            if imgui.Button(u8"Сохранить", imgui.ImVec2(200, 35)) then
            if inicfg.save(mainIni, directIni) then
            notf.addNotification(string.format("...........................................\nУспех\n...........................................", 228, os.date()), 5)
        end
    end
                imgui.EndChild()
             
checkairbrake =  imgui.ImBool(mainini.cheat.checkairbrake)

А хз, пусть будет.
Lua:
checkairbrake =  imgui.ImBool(mainini.cheat.checkairbrake)
 
 
              imgui.BeginChild("49", imgui.ImVec2(632, 0), true)

                if imgui.Checkbox(u8'AirBrake', checkairbrake) then
                    mainini.cheat.checkairbrake = checkairbrake.v
                    inicfg.save(mainini, "Admin_Tools.ini")
                end
               

            imgui.SameLine()
            imgui.SetCursorPosY((imgui.GetWindowWidth() - 616) / 2)
            if imgui.Button(u8"Сохранить", imgui.ImVec2(200, 35)) then
            if inicfg.save(mainIni, directIni) then
            notf.addNotification(string.format("...........................................\nУспех\n...........................................", 228, os.date()), 5)
        end
    end
                imgui.EndChild()
 
  • Ха-ха
Реакции: G W

user31883

Потрачен
101
219
Как проверить была ли только что развернута игра? То есть окно игры стало активным