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

qdIbp

Автор темы
Проверенный
1,450
1,197

вайега52

Налуашил состояние
Модератор
2,976
3,094
Как правильно убрать говно с помощью цикла из этого кода?
Lua:
local mainIni = inicfg.load({
    carInfo = {
        actived = true,
        model = true,
        id = true,
        engine = true,
        hp = true,
        dist = true
    },
}, "AHelper.ini")

local config = {
    carInfo = {
        actived = new.bool(mainIni.carInfo.actived),
        data = {
            model = new.bool(mainIni.carInfo.model),
            id = new.bool(mainIni.carInfo.id),
            engine = new.bool(mainIni.carInfo.engine),
            hp = new.bool(mainIni.carInfo.hp),
            dist = new.bool(mainIni.carInfo.dist)
        }
    },
}

if imgui.ToggleButton("Model", config.carInfo.data.model) then
    mainIni.carInfo.model = config.carInfo.data.model[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("ID", config.carInfo.data.id) then
    mainIni.carInfo.id = config.carInfo.data.id[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("Engine", config.carInfo.data.engine) then
    mainIni.carInfo.engine = config.carInfo.data.engine[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("HP", config.carInfo.data.hp) then
    mainIni.carInfo.hp = config.carInfo.data.hp[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("Distance", config.carInfo.data.dist) then
    mainIni.carInfo.dist = config.carInfo.data.dist[0]
    inicfg.save(mainIni, "AHelper.ini")
end
 
  • Грустно
Реакции: qdIbp

chapo

tg/inst: @moujeek
Всефорумный модератор
9,203
12,526
Как правильно убрать говно с помощью цикла из этого кода?
Lua:
local mainIni = inicfg.load({
    carInfo = {
        actived = true,
        model = true,
        id = true,
        engine = true,
        hp = true,
        dist = true
    },
}, "AHelper.ini")

local config = {
    carInfo = {
        actived = new.bool(mainIni.carInfo.actived),
        data = {
            model = new.bool(mainIni.carInfo.model),
            id = new.bool(mainIni.carInfo.id),
            engine = new.bool(mainIni.carInfo.engine),
            hp = new.bool(mainIni.carInfo.hp),
            dist = new.bool(mainIni.carInfo.dist)
        }
    },
}

if imgui.ToggleButton("Model", config.carInfo.data.model) then
    mainIni.carInfo.model = config.carInfo.data.model[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("ID", config.carInfo.data.id) then
    mainIni.carInfo.id = config.carInfo.data.id[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("Engine", config.carInfo.data.engine) then
    mainIni.carInfo.engine = config.carInfo.data.engine[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("HP", config.carInfo.data.hp) then
    mainIni.carInfo.hp = config.carInfo.data.hp[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("Distance", config.carInfo.data.dist) then
    mainIni.carInfo.dist = config.carInfo.data.dist[0]
    inicfg.save(mainIni, "AHelper.ini")
end
Lua:
for name, state in pairs(config.carInfo.data) do
    if imgui.ToggleButton(name, state) then
        mainIni.carInfo[name] = state[0]
        inicfg.save(mainIni, "AHelper.ini")
    end
end
 
Последнее редактирование:
  • Нравится
Реакции: ARMOR и вайега52

XRLM

Против ветра рождённый
Модератор
1,631
1,281
Как правильно убрать говно с помощью цикла из этого кода?
Lua:
local mainIni = inicfg.load({
    carInfo = {
        actived = true,
        model = true,
        id = true,
        engine = true,
        hp = true,
        dist = true
    },
}, "AHelper.ini")

local config = {
    carInfo = {
        actived = new.bool(mainIni.carInfo.actived),
        data = {
            model = new.bool(mainIni.carInfo.model),
            id = new.bool(mainIni.carInfo.id),
            engine = new.bool(mainIni.carInfo.engine),
            hp = new.bool(mainIni.carInfo.hp),
            dist = new.bool(mainIni.carInfo.dist)
        }
    },
}

if imgui.ToggleButton("Model", config.carInfo.data.model) then
    mainIni.carInfo.model = config.carInfo.data.model[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("ID", config.carInfo.data.id) then
    mainIni.carInfo.id = config.carInfo.data.id[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("Engine", config.carInfo.data.engine) then
    mainIni.carInfo.engine = config.carInfo.data.engine[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("HP", config.carInfo.data.hp) then
    mainIni.carInfo.hp = config.carInfo.data.hp[0]
    inicfg.save(mainIni, "AHelper.ini")
end
if imgui.ToggleButton("Distance", config.carInfo.data.dist) then
    mainIni.carInfo.dist = config.carInfo.data.dist[0]
    inicfg.save(mainIni, "AHelper.ini")
end
сохранять изменения в конфиг лучше через функу onScriptTerminaled
 

ARMOR

Я креветка
Модератор
5,068
7,374
сохранять изменения в конфиг лучше через функу onScriptTerminaled
Тогда при выходе через диспетчер задач ( когда игра залагает ), или если у тебя есть плагин GameExitFix.sf то настройки просто не сохранятся.
 

AeSiK256

Участник
56
24
Помогите сделать активацию и деактивацию на F2. У меня что-то не работает.
Lua:
function main()
 setCharUsesUpperbodyDamageAnimsOnly(PLAYER_PED, 1)
 if isKeyJustPressed(VK_F2) then --and sampIsChatInputActive() and not sampIsDialogActive()    
        end
    end
А где собственно действие после нажатия, переменная на активацию?
См. здесь - https://blast.hk/threads/48833/
 

Kroot

Новичок
2
0
Здравствуйте , как получит игровой уровень игрока через диалог?
Скриншот снизу

sa-mp-848.png
 

qdIbp

Автор темы
Проверенный
1,450
1,197
Здравствуйте , как получит игровой уровень игрока через диалог?
Скриншот снизу

Посмотреть вложение 185485
Попробуй так
Lua:
require('samp.events').onShowDialog = function(did, style, title, b1, b2, text)
    local lvl = string.match(text,'Игровок уровень:%c(%d+)')
    if lvl then
        sampAddChatMessage('Ваш лвл: '..lvl,-1)
    end
end

Помогите сделать активацию и деактивацию на F2. У меня что-то не работает.
Lua:
function main()
 setCharUsesUpperbodyDamageAnimsOnly(PLAYER_PED, 1)
 if isKeyJustPressed(VK_F2) then --and sampIsChatInputActive() and not sampIsDialogActive()    
        end
    end
Lua:
local status = false
function main()

    while true do wait(0)
         setCharUsesUpperbodyDamageAnimsOnly(PLAYER_PED, status)
         if isKeyJustPressed(113) then --and sampIsChatInputActive() and not sampIsDialogActive()
            status = not status
        end
    end
end
 
Последнее редактирование:

jenees.21

Участник
73
9
Попробуй так
Lua:
require('samp.events').onShowDialog = function(did, style, title, b1, b2, text)
    local lvl = string.match(text,'Игровок уровень:%c(%d+)')
    if lvl then
        sampAddChatMessage('Ваш лвл: '..lvl,-1)
    end
end


Lua:
local status = false
function main()

    while true do wait(0)
         setCharUsesUpperbodyDamageAnimsOnly(PLAYER_PED, status)
         if isKeyJustPressed(113) then --and sampIsChatInputActive() and not sampIsDialogActive()
            status = not status
        end
    end
end
Lua:
require 'lib.moonloader'
local samp = require 'lib.samp.events'
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('stun', function()
        status = not status
        if status then
            printStyledString('Enabled', 1000, 4)
        else
            printStyledString('Disabled', 1000, 4)
        end
    end)
    while true do
        wait(0)
    end
end

function samp.onSendPlayerSync(data)
    if status then
        if data.animationId == 1084 then
            data.animationFlags = 32772
            data.animationId = 1189
        end
    end
end

Можешь сделать активацию и деактивацию по кнопке F2? а регистр команды вырезать
 
  • Эм
Реакции: qdIbp

qdIbp

Автор темы
Проверенный
1,450
1,197
Lua:
require 'lib.moonloader'
local samp = require 'lib.samp.events'
function main()
    if not isSampfuncsLoaded() or not isSampLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('stun', function()
        status = not status
        if status then
            printStyledString('Enabled', 1000, 4)
        else
            printStyledString('Disabled', 1000, 4)
        end
    end)
    while true do
        wait(0)
    end
end

function samp.onSendPlayerSync(data)
    if status then
        if data.animationId == 1084 then
            data.animationFlags = 32772
            data.animationId = 1189
        end
    end
end

Можешь сделать активацию и деактивацию по кнопке F2? а регистр команды вырезать
Lua:
require('lib.moonloader')
local samp = require('lib.samp.events')

local status = false
function main()
    while not isSampAvailable() do wait(100) end
    
    while true do wait(0)
         setCharUsesUpperbodyDamageAnimsOnly(PLAYER_PED, status)
         if isKeyJustPressed(113) then --and not sampIsChatInputActive() and not sampIsDialogActive() then
            status = not status
            printStyledString(status and 'Enabled' or 'Disabled', 1000, 4)
        end
    end
end

function samp.onSendPlayerSync(data)
    if status then
        if data.animationId == 1084 then
            data.animationFlags = 32772
            data.animationId = 1189
            return data
        end
    end
end
 
  • Нравится
Реакции: jenees.21