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

Myroslaw

Известный
133
5
У меня стоит на буковку P открытие телефона, я открываю репорт, пишу что то, нажимаю на букву P, и открывается телефон, как сделать, чтобы когда открыт чат или какой то диалог, игнорировалась клавиша
if not sampIsCursorActive() then
 

Myroslaw

Известный
133
5
У меня стоит на буковку P открытие телефона, я открываю репорт, пишу что то, нажимаю на букву P, и открывается телефон, как сделать, чтобы когда открыт чат или какой то диалог, игнорировалась клавиша
Lua:
if not sampIsCursorActive() then
    if isKeyJustPressed(75) then
        sampSendChat('/phone')
    end
end
типо так. Если на екране нету курсора, только тогда будет ВЬІполнятся действе
 

copypaste_scripter

Известный
1,218
223
Lua:
lua_thread.create(function()
    if text:find("чтобы закрыть организационный транспорт") and getDriverOfCar(storeCarCharIsInNoSave(PLAYER_PED)) == PLAYER_PED then
        wait(500)
        engineState = isCarEngineOn(storeCarCharIsInNoSave(PLAYER_PED))
        if engineState == 0 then sampSendChat('/engine') end
    else
        return false
    end
end)

как сделать чтобы работал?
надо чтобы когда сажусь в машину, и в чате находит сообщения - чекал заведен ли двигатель и если нет писал команду, а если заведен то просто ничего
 

why?

Участник
30
2
Такая шняга, как фиксить?
lua:
[22:41:55.852355] (error)    binder.lua: ...ke gta samp thrill smoke by fleyta\moonloader\binder.lua:43: 'end' expected (to close 'if' at line 30) near '<eof>'
[22:41:55.852355] (error)    binder.lua: Script died due to an error. (0B1D0D84)
 

why?

Участник
30
2
Есть end
lua:
require "lib.moonloader"
function main()

  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
  while true do
  wait(0)
  if not sampIsCursorActive() then
    if isKeyJustPressed(VK_ADD) then
      sampSendChat("/mask")
    end
    if not sampIsCursorActive() then
    if isKeyJustPressed(VK_SUBTRACT) then
  sampSendChat("/armour")
  end
               if not sampIsCursorActive() then
      if isKeyJustPressed(VK_DIVIDE) then
      sampSendChat("/usedrugs 3")
      end
                if not sampIsCursorActive() then
            if isKeyJustPressed(VK_K) then
        sampSendChat('/key')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_1) then
        sampSendChat('/anims 1')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_X) then
        sampSendChat('/style')   
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_L) then
        sampSendChat('/lock')
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_P) then
        sampSendChat('/phone')
    end
  end
  end
 

bottom_text

Известный
675
318
Есть end
lua:
require "lib.moonloader"
function main()

  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
  while true do
  wait(0)
  if not sampIsCursorActive() then
    if isKeyJustPressed(VK_ADD) then
      sampSendChat("/mask")
    end
    if not sampIsCursorActive() then
    if isKeyJustPressed(VK_SUBTRACT) then
  sampSendChat("/armour")
  end
               if not sampIsCursorActive() then
      if isKeyJustPressed(VK_DIVIDE) then
      sampSendChat("/usedrugs 3")
      end
                if not sampIsCursorActive() then
            if isKeyJustPressed(VK_K) then
        sampSendChat('/key')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_1) then
        sampSendChat('/anims 1')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_X) then
        sampSendChat('/style')  
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_L) then
        sampSendChat('/lock')
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_P) then
        sampSendChat('/phone')
    end
  end
  end
Lua:
require "lib.moonloader"
function main()
  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
  while true do wait(0)
    if not sampIsCursorActive() then
        if isKeyJustPressed(VK_ADD) then
            sampSendChat("/mask")
        end
    if not sampIsCursorActive() then
        if isKeyJustPressed(VK_SUBTRACT) then
            sampSendChat("/armour")
        end
               if not sampIsCursorActive() then
                 if isKeyJustPressed(VK_DIVIDE) then
      sampSendChat("/usedrugs 3")
      end
                if not sampIsCursorActive() then
            if isKeyJustPressed(VK_K) then
        sampSendChat('/key')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_1) then
        sampSendChat('/anims 1')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_X) then
        sampSendChat('/style')   
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_L) then
        sampSendChat('/lock')
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_P) then
        sampSendChat('/phone')
    end
  end
end
end
  end
end 
end
end 
end
end
end
Код ужаснейший, у тебя не было кучи end. Нормально оформлять код за тебя я не буду, поэтому держи исправленный как есть
 
  • Влюблен
Реакции: Vintik

Vintik

Мечтатель
Проверенный
1,467
916
Есть end
lua:
require "lib.moonloader"
function main()

  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
  while true do
  wait(0)
  if not sampIsCursorActive() then
    if isKeyJustPressed(VK_ADD) then
      sampSendChat("/mask")
    end
    if not sampIsCursorActive() then
    if isKeyJustPressed(VK_SUBTRACT) then
  sampSendChat("/armour")
  end
               if not sampIsCursorActive() then
      if isKeyJustPressed(VK_DIVIDE) then
      sampSendChat("/usedrugs 3")
      end
                if not sampIsCursorActive() then
            if isKeyJustPressed(VK_K) then
        sampSendChat('/key')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_1) then
        sampSendChat('/anims 1')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_X) then
        sampSendChat('/style')  
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_L) then
        sampSendChat('/lock')
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_P) then
        sampSendChat('/phone')
    end
  end
  end
end должен закрывать каждый if, while, for и прочие (циклы + операторы ветвления).
 

ollydbg

Известный
163
113
Есть end
lua:
require "lib.moonloader"
function main()

  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
  while true do
  wait(0)
  if not sampIsCursorActive() then
    if isKeyJustPressed(VK_ADD) then
      sampSendChat("/mask")
    end
    if not sampIsCursorActive() then
    if isKeyJustPressed(VK_SUBTRACT) then
  sampSendChat("/armour")
  end
               if not sampIsCursorActive() then
      if isKeyJustPressed(VK_DIVIDE) then
      sampSendChat("/usedrugs 3")
      end
                if not sampIsCursorActive() then
            if isKeyJustPressed(VK_K) then
        sampSendChat('/key')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_1) then
        sampSendChat('/anims 1')
    end
                 if not sampIsCursorActive() then
            if isKeyJustPressed(VK_X) then
        sampSendChat('/style')  
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_L) then
        sampSendChat('/lock')
    end
                 if not sampIsCursorActive() then
          if isKeyJustPressed(VK_P) then
        sampSendChat('/phone')
    end
  end
  end
you can use functions to reduce code size
Lua:
require "lib.moonloader"

function main()
    repeat wait(0) until isSampAvailable()
        while true do
            wait(0)
            sendchat("/mask", VK_ADD)
            sendchat("/armour", VK_SUBTRACT)
            sendchat("/usedrugs 3", VK_DIVIDE)
            sendchat("/key", VK_K)
            sendchat("/anims 1", VK_1) 
            sendchat("/style", VK_X)
            sendchat("/lock", VK_L)
            sendchat("/phone", VK_P)
        end
    end

    function sendchat(text, key)
        if not sampIsCursorActive() and wasKeyPressed(key) then
            sampSendChat(text)
        end
    end
 
  • Нравится
Реакции: Vintik

copypaste_scripter

Известный
1,218
223
Lua:
lua_thread.create(function()
    if text:find("чтобы закрыть организационный транспорт") and getDriverOfCar(storeCarCharIsInNoSave(PLAYER_PED)) == PLAYER_PED then
        wait(500)
        engineState = isCarEngineOn(storeCarCharIsInNoSave(PLAYER_PED))
        if engineState == 0 then sampSendChat('/engine') end
    else
        return false
    end
end)

как сделать чтобы работал?
надо чтобы когда сажусь в машину, и в чате находит сообщения - чекал заведен ли двигатель и если нет писал команду, а если заведен то просто ничего
 

ollydbg

Известный
163
113
Lua:
lua_thread.create(function()
    if text:find("чтобы закрыть организационный транспорт") and getDriverOfCar(storeCarCharIsInNoSave(PLAYER_PED)) == PLAYER_PED then
        wait(500)
        engineState = isCarEngineOn(storeCarCharIsInNoSave(PLAYER_PED))
        if engineState == 0 then sampSendChat('/engine') end
    else
        return false
    end
end)

как сделать чтобы работал?
надо чтобы когда сажусь в машину, и в чате находит сообщения - чекал заведен ли двигатель и если нет писал команду, а если заведен то просто ничего
i don't speak russian but i think you can try this
Lua:
local se = require 'lib.samp.events'
function se.onServerMessage(color,text)
    if text:find("чтобы закрыть организационный транспорт") then
        if isCharInAnyCar(PLAYER_PED) then
            if not isCarEngineOn(storeCarCharIsInNoSave(PLAYER_PED)) then
                lua_thread.create(function()
                wait(0)
                sampSendChat('/engine')
                end)
            end
        end
    end
end
 
  • Нравится
Реакции: copypaste_scripter

sep

Известный
672
76
в вертолёте багается подправте плиз
код:
script_name('Vehicle Material Color Example')
local mad = require 'MoonAdditions'

function main()
    while true do
        wait(0)
        if isPlayerPlaying(PLAYER_HANDLE) then
            if isCharInAnyCar(PLAYER_PED) and testCheat('car') then
                local car = storeCarCharIsInNoSave(PLAYER_PED)
                local new_r = 30
                local new_g = 255
                local new_b = 50
                for_each_vehicle_material(car, function(mat)
                    local r, g, b, a = mat:get_color()
                    if (r == 0x3C and g == 0xFF and b == 0x00) or (r == 0xFF and g == 0x00 and b == 0xAF) then
                        mat:set_color(new_r, new_g, new_b, a)
                    end
                end)
            end
        end
    end
end


function for_each_vehicle_material(car, func)
    for _, comp in ipairs(mad.get_all_vehicle_components(car)) do
        for _, obj in ipairs(comp:get_objects()) do
            for _, mat in ipairs(obj:get_materials()) do
                func(mat)
            end
        end
    end
end
 

SurnikSur

Активный
284
40
Код:
function sampev.onServerMessage(color, text)
if act then
lua_thread.create(function()
    if text:match("Привет") then
       setCharCoordinates(PLAYER_PED, -145.2968, 150.5510, 1.7366)
       wait(400)
       goKeyPressed(18)
    end
    if text:match("chek") then
       setCharCoordinates(PLAYER_PED, -190.9286, 195.3275, 1.8735)
       end
    end)
    end
    end
почему не работает ?
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,768
11,210
Код:
function sampev.onServerMessage(color, text)
if act then
lua_thread.create(function()
    if text:match("Привет") then
       setCharCoordinates(PLAYER_PED, -145.2968, 150.5510, 1.7366)
       wait(400)
       goKeyPressed(18)
    end
    if text:match("chek") then
       setCharCoordinates(PLAYER_PED, -190.9286, 195.3275, 1.8735)
       end
    end)
    end
    end
почему не работает ?
Lua:
function sampev.onServerMessage(color, text)
    if act then
        lua_thread.create(function()
        if text:find("Привет") then
           setCharCoordinates(PLAYER_PED, -145.2968, 150.5510, 1.7366)
           wait(400)
           goKeyPressed(18)
        end
        if text:find("chek") then
           setCharCoordinates(PLAYER_PED, -190.9286, 195.3275, 1.8735)
           end
        end)
    end
end