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

Good8432

Новичок
10
0
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('time', time)
    while true do
        wait(0)
    end
end

function time(arg)
    lua_thread.create(function()
        sampSendChat('/me взглянул на часы с гравировкой "Name"')
        wait(500)
        sampSendChat('/do На часах '..os.date("%H:%M:%S"))
    end
end)
В строке с wait(500) своё значение. Вроде бы должно робить
Вообще не работает
 

why?

Участник
30
2
Фикс?
[18:13:49.096921] (error) binder.lua: D:\GTA San Andreas by rage\moonloader\binder.lua:65: 'end' expected (to close 'function' at line 2) near '<eof>'
[18:13:49.096921] (error) binder.lua: Script died due to an error. (0735F2AC)
lua:
require "lib.moonloader"
function main()
  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
            ---------------- Сокращение команды ----------------    
               
    sampRegisterChatCommand('fh',function(arg) sampSendChat('/findihouse '..arg) end)
  sampRegisterChatCommand('fh',function(arg)
         if type(arg) == 'string' then
        if arg == '' then
            sampSendChat('/findihouse  '..arg)
        end
    end
end)
            --------------- Сокращение команды ----------------
  while true do wait(0)
               if not sampIsCursorActive() then
          if testCheat('shar') then
            sampSendChat("/vr Куплю шарики в евро, жду в ЦБ")
    end
               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
p.s не кидайте палками, мой первый скрипт, код говно, в курсе
 

M0rtelli

Участник
34
6
Фикс?
[18:13:49.096921] (error) binder.lua: D:\GTA San Andreas by rage\moonloader\binder.lua:65: 'end' expected (to close 'function' at line 2) near '<eof>'
[18:13:49.096921] (error) binder.lua: Script died due to an error. (0735F2AC)
lua:
require "lib.moonloader"
function main()
  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
            ---------------- Сокращение команды ----------------   
              
    sampRegisterChatCommand('fh',function(arg) sampSendChat('/findihouse '..arg) end)
  sampRegisterChatCommand('fh',function(arg)
         if type(arg) == 'string' then
        if arg == '' then
            sampSendChat('/findihouse  '..arg)
        end
    end
end)
            --------------- Сокращение команды ----------------
  while true do wait(0)
               if not sampIsCursorActive() then
          if testCheat('shar') then
            sampSendChat("/vr Куплю шарики в евро, жду в ЦБ")
    end
               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
p.s не кидайте палками, мой первый скрипт, код говно, в курсе
не нужно писать много if'ов. достаточно сделать так.
сама проблема была в недостатке end
Lua:
require "lib.moonloader"
function main()
  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
            ---------------- Сокращение команды ----------------    
               
    sampRegisterChatCommand('fh',function(arg) sampSendChat('/findihouse '..arg) end)
  sampRegisterChatCommand('fh',function(arg)
         if type(arg) == 'string' then
        if arg == '' then
            sampSendChat('/findihouse  '..arg)
        end
    end
end)
            --------------- Сокращение команды ----------------
  while true do wait(0)
              while not sampIsCursorActive() do
if testCheat('shar') then
    sampSendChat("/vr Куплю шарики в евро, жду в ЦБ")
end
               
if isKeyJustPressed(VK_ADD) then
    sampSendChat("/mask")
end
                    
if isKeyJustPressed(VK_SUBTRACT) then
    sampSendChat("/armour")
end
              
if isKeyJustPressed(VK_DIVIDE) then
    sampSendChat("/usedrugs 3")
end
              
if isKeyJustPressed(VK_K) then
    sampSendChat('/key')
end
              
if isKeyJustPressed(VK_1) then
    sampSendChat('/anims 1')
end
              
if isKeyJustPressed(VK_X) then
    sampSendChat('/style')  
end
               
if isKeyJustPressed(VK_L) then
    sampSendChat('/lock')
end
              
if isKeyJustPressed(VK_P) then
    sampSendChat('/phone')
end
  end
end
end
 

Good8432

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


function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('time', time)
while true do
wait(0)
end
end


function time(arg)
sampSendChat('/me взглянул на часы с гравировкой "Name"')
sampSendChat('/do На часах '..os.date("%H:%M:%S"))
end
Всё ещё в силе
 

M0rtelli

Участник
34
6
в 14 строке укажи вместо моего текста задержку в миллисекундах.
Lua:
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('time', time)
while true do
wait(0)
end
end


function time(arg)
lua.thread_create(function()
sampSendChat('/me взглянул на часы с гравировкой "Name"')
wait(задержка в миллисекундах)
sampSendChat('/do На часах '..os.date("%H:%M:%S"))
end)
end
 

why?

Участник
30
2
не нужно писать много if'ов. достаточно сделать так.
сама проблема была в недостатке end
Lua:
require "lib.moonloader"
function main()
  if not isSampfuncsLoaded() or not isSampLoaded() then return end
  while not isSampAvailable() do wait(100) end
            ---------------- Сокращение команды ----------------   
              
    sampRegisterChatCommand('fh',function(arg) sampSendChat('/findihouse '..arg) end)
  sampRegisterChatCommand('fh',function(arg)
         if type(arg) == 'string' then
        if arg == '' then
            sampSendChat('/findihouse  '..arg)
        end
    end
end)
            --------------- Сокращение команды ----------------
  while true do wait(0)
              while not sampIsCursorActive() do
if testCheat('shar') then
    sampSendChat("/vr Куплю шарики в евро, жду в ЦБ")
end
              
if isKeyJustPressed(VK_ADD) then
    sampSendChat("/mask")
end
                   
if isKeyJustPressed(VK_SUBTRACT) then
    sampSendChat("/armour")
end
             
if isKeyJustPressed(VK_DIVIDE) then
    sampSendChat("/usedrugs 3")
end
             
if isKeyJustPressed(VK_K) then
    sampSendChat('/key')
end
             
if isKeyJustPressed(VK_1) then
    sampSendChat('/anims 1')
end
             
if isKeyJustPressed(VK_X) then
    sampSendChat('/style') 
end
              
if isKeyJustPressed(VK_L) then
    sampSendChat('/lock')
end
             
if isKeyJustPressed(VK_P) then
    sampSendChat('/phone')
end
  end
end
end
Спасибо за код, но, мне нужно мой код пофиксить а не твой использовать
 

Good8432

Новичок
10
0
в 14 строке укажи вместо моего текста задержку в миллисекундах.
Lua:
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('time', time)
while true do
wait(0)
end
end


function time(arg)
lua.thread_create(function()
sampSendChat('/me взглянул на часы с гравировкой "Name"')
wait(задержка в миллисекундах)
sampSendChat('/do На часах '..os.date("%H:%M:%S"))
end)
end
Тогда скрипт вообще перестаёт работать
 

Good8432

Новичок
10
0
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('time', time)
while true do
wait(0)
end
end


function time(arg)
lua.thread_create(function()
sampSendChat('/me взглянул на часы с гравировкой "Name"')
wait(1000)
sampSendChat('/do На часах '..os.date("%H:%M:%S"))
end)
end
 

ollydbg

Известный
163
113
Тогда скрипт вообще перестаёт работать
Lua:
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampRegisterChatCommand('time', time)
wait(-1)
end


function time(arg)
-- lua.thread.create(function() -- wrong
lua_thread.create(function() -- well
wait(0)
sampSendChat('/me взглянул на часы с гравировкой "Name"')
sampSendChat('/do На часах '..os.date("%H:%M:%S"))
end)
end