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

#Northn

Police Helper «Reborn» — уже ШЕСТЬ лет!
Всефорумный модератор
2,641
2,492
  • Нравится
Реакции: Musaigen

mr.qldu

Известный
46
0
если сообщение было отправлено - повторно оно отправится только через 15 секунд, это предотвратит тебя от кика за флуд
а как мне остановить процесс отправки сообщения каждые 15 секунд? А для чего создавать новый поток?
 

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
а как мне остановить процесс отправки сообщения каждые 15 секунд? А для чего создавать новый поток?
он прекратится сам, когда сервер пришлет тебе любое сообщение(можно сэмулировать), новый поток позволит тебе делать wait без остановки других задач(касается main цикла, остальное вроде не нужно, но лишним не будет0))
 

mr.qldu

Известный
46
0
Не работает бинд клавиши NUMPAD2 и автоподача объявлений сразу после выпуска старой объявы.
Lua:
local spev = require 'lib.samp.events'
local key = require 'vkeys'
local send = false

local outPass = "Высадка пассажиров"
local count = 0        
local money = -3000 

local sendAd = "/ad обменяю FCR-900 на Huntley с доплатой"
local searchAd = "Отправил Franco_DeRienzo"


function main()
  while true do
    wait(0)
        if isKeyJustPressed(key.VK_F1) then
            sampSendChat("/c 60")
            wait(500)
            sampSendChat("/me задумчиво взглянул на часы")
        end
       
        if isKeyJustPressed(key.VK_DELETE) then
            if count ~= 0 then
                sampAddChatMessage(string.format("{32CD32}Счётчики обнулены. Заработано примерно {FFFF00}%d${32CD32} за {FFFF00}%d{32CD32} рейсов.", money, count), -1)
                count = 0
                money = -3000
            else
                sampAddChatMessage("{32CD32}Счётчики уже обнулены.")
            end
        end
       
        if isKeyJustPressed(key.VK_ADD) then
            sampSendChat(sendAd)
        end
       
        if isKeyJustPressed(key.VK_F9) then
            sampSetChatInputText("/f • ")
            sampSetChatInputEnabled(true)
        end
       
        if isKeyJustPressed(key.VK_NUMPAD2) then
            sampSendChat("/airpair")
            wait(500)
            sampSendChat("/airfill")
        end
    
  end
end


function spev.onServerMessage(clr,text)
    str, --[[string]] prefstr, --[[int]] colstr, --[[int]] pcolstr = sampGetChatString(--[[int]] 99)
    if string.find(str, outPass, 0, true) ~= nil then
        pilotCount()
        send = true
    end
   
    if string.find(str, searchAd, 0, true) ~= nil then
        sampSendChat(sendAd)
        send = true
    end
   
    if send then
        wait(5000)
    end
end
    
    


function pilotCount()
        count = count + 1
        money = money + 1500
       
        if money > 0 then
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
            text1 = string.format("{3333FF}Совершено рейсов: {007DFF}%d", count)
            sampAddChatMessage(text1, -1)
            text2 = string.format("{3333FF}Заработано примерно: {008000}%d$", money)
            sampAddChatMessage(text2, -1)
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
        else
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
            text1 = string.format("{3333FF}Совершено рейсов: {007DFF}%d", count)
            sampAddChatMessage(text1, -1)
            text2 = string.format("{3333FF}Заработано примерно: {FFA500}%d$", money)
            sampAddChatMessage(text2, -1)
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
        end
end
Ошибка в логе:
Код:
[17:07:26.317414] (error)    mybind.lua: F:\Program Files\Last GTA\moonloader\mybind.lua:64: attempt to yield across C-call boundary
stack traceback:
    [C]: in function 'wait'
    F:\Program Files\Last GTA\moonloader\mybind.lua:64: in function 'callback'
    ...ogram Files\Last GTA\moonloader\lib\samp\events\core.lua:82: in function <...ogram Files\Last GTA\moonloader\lib\samp\events\core.lua:54>
[17:07:26.326441] (error)    mybind.lua: Script died due to an error. (0BA3E444)
 

rraggerr

проверенный какой-то
1,626
847
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Не работает бинд клавиши NUMPAD2 и автоподача объявлений сразу после выпуска старой объявы.
Lua:
local spev = require 'lib.samp.events'
local key = require 'vkeys'
local send = false

local outPass = "Высадка пассажиров"
local count = 0       
local money = -3000

local sendAd = "/ad обменяю FCR-900 на Huntley с доплатой"
local searchAd = "Отправил Franco_DeRienzo"


function main()
  while true do
    wait(0)
        if isKeyJustPressed(key.VK_F1) then
            sampSendChat("/c 60")
            wait(500)
            sampSendChat("/me задумчиво взглянул на часы")
        end
      
        if isKeyJustPressed(key.VK_DELETE) then
            if count ~= 0 then
                sampAddChatMessage(string.format("{32CD32}Счётчики обнулены. Заработано примерно {FFFF00}%d${32CD32} за {FFFF00}%d{32CD32} рейсов.", money, count), -1)
                count = 0
                money = -3000
            else
                sampAddChatMessage("{32CD32}Счётчики уже обнулены.")
            end
        end
      
        if isKeyJustPressed(key.VK_ADD) then
            sampSendChat(sendAd)
        end
      
        if isKeyJustPressed(key.VK_F9) then
            sampSetChatInputText("/f • ")
            sampSetChatInputEnabled(true)
        end
      
        if isKeyJustPressed(key.VK_NUMPAD2) then
            sampSendChat("/airpair")
            wait(500)
            sampSendChat("/airfill")
        end
   
  end
end


function spev.onServerMessage(clr,text)
    str, --[[string]] prefstr, --[[int]] colstr, --[[int]] pcolstr = sampGetChatString(--[[int]] 99)
    if string.find(str, outPass, 0, true) ~= nil then
        pilotCount()
        send = true
    end
  
    if string.find(str, searchAd, 0, true) ~= nil then
        sampSendChat(sendAd)
        send = true
    end
  
    if send then
        wait(5000)
    end
end
   
   


function pilotCount()
        count = count + 1
        money = money + 1500
      
        if money > 0 then
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
            text1 = string.format("{3333FF}Совершено рейсов: {007DFF}%d", count)
            sampAddChatMessage(text1, -1)
            text2 = string.format("{3333FF}Заработано примерно: {008000}%d$", money)
            sampAddChatMessage(text2, -1)
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
        else
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
            text1 = string.format("{3333FF}Совершено рейсов: {007DFF}%d", count)
            sampAddChatMessage(text1, -1)
            text2 = string.format("{3333FF}Заработано примерно: {FFA500}%d$", money)
            sampAddChatMessage(text2, -1)
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
        end
end
Ошибка в логе:
Код:
[17:07:26.317414] (error)    mybind.lua: F:\Program Files\Last GTA\moonloader\mybind.lua:64: attempt to yield across C-call boundary
stack traceback:
    [C]: in function 'wait'
    F:\Program Files\Last GTA\moonloader\mybind.lua:64: in function 'callback'
    ...ogram Files\Last GTA\moonloader\lib\samp\events\core.lua:82: in function <...ogram Files\Last GTA\moonloader\lib\samp\events\core.lua:54>
[17:07:26.326441] (error)    mybind.lua: Script died due to an error. (0BA3E444)
создавай отдельный поток , wait(5000) тебе ничего не даст, ты не понимаешь как работает мой код
 

штейн

Известный
Проверенный
1,001
687
попробуй заменить setCharKeyDown на setVirtualKeyDown.

Lua:
    lua_thread.create(function()
        while true do wait(0)
            if wasKeyPressed(VK_Y) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() then
                if isCharInCarDriver(playerPed) then
                    setCharKeyDown(0x32, true)
                    wait(200)
                    setCharKeyDown(0x32, false)
                end
            end
        end
    end)

тут всё работает
 

штейн

Известный
Проверенный
1,001
687
как на луа сделать сокращенные команды по типу /giverang id rang = /gr id rang

Lua:
function fd(param)
    local id = string.match(param, '(%d+)')
    if id ~= nil then
        sampSendChat(string.format("/find %d", id))
    else
    sampAddChatMessage("[ {800000}HitMan {ffffff}]: Поиск игрока [ {800000}/fd ID {ffffff}].", -1)
  end
end
 

mr.qldu

Известный
46
0
Сделал, просто флудит в чат и Server closed the connection
Lua:
local spev = require 'lib.samp.events'
local key = require 'vkeys'
local send = false

local outPass = "Высадка пассажиров"
local count = 0        
local money = -3000 

local sendAd = "/ad обменяю FCR-900 на Huntley с доплатой"
local searchAd = "Отправил Franco_DeRienzo"


function main()
  while true do
    wait(0)
    if isKeyJustPressed(key.VK_F1) then
        sampSendChat("/c 60")
        wait(500)
        sampSendChat("/me задумчиво взглянул на часы")
    end

    if isKeyJustPressed(key.VK_DELETE) then
        if count ~= 0 then
            sampAddChatMessage(string.format("{32CD32}Счётчики обнулены. Заработано примерно {FFFF00}%d${32CD32} за {FFFF00}%d{32CD32} рейсов.", money, count), -1)
            count = 0
            money = -3000
        else
            sampAddChatMessage("{32CD32}Счётчики уже обнулены.")
        end
    end

    if isKeyJustPressed(key.VK_ADD) then
        sampSendChat(sendAd)
    end

    if isKeyJustPressed(key.VK_F9) then
        sampSetChatInputText("/f • ")
        sampSetChatInputEnabled(true)
    end

    if isKeyJustPressed(key.VK_NUMPAD2) then
        sampSendChat("/airpair")
        wait(500)
        sampSendChat("/airfill")
    end
    
  end
  wait(-1)
end


function spev.onServerMessage(clr,text)
    str, --[[string]] prefstr, --[[int]] colstr, --[[int]] pcolstr = sampGetChatString(--[[int]] 99)
    if string.find(str, outPass, 0, true) ~= nil then
        pilotCount()
        send = true
    end
   
    if string.find(str, searchAd, 0, true) ~= nil then
        sampSendChat(sendAd)
        send = true
    end
   
    lua_thread.create(waiting)
end
    
    


function pilotCount()
        count = count + 1
        money = money + 1500
       
        if money > 0 then
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
            text1 = string.format("{3333FF}Совершено рейсов: {007DFF}%d", count)
            sampAddChatMessage(text1, -1)
            text2 = string.format("{3333FF}Заработано примерно: {008000}%d$", money)
            sampAddChatMessage(text2, -1)
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
        else
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
            text1 = string.format("{3333FF}Совершено рейсов: {007DFF}%d", count)
            sampAddChatMessage(text1, -1)
            text2 = string.format("{3333FF}Заработано примерно: {FFA500}%d$", money)
            sampAddChatMessage(text2, -1)
            sampAddChatMessage("{75C1FF}--------------------------------------------------", -1)
        end
end

function waiting()
    if send then
        wait(5000)
    end
end
 

Musaigen

abobusnik
Проверенный
1,585
1,310
Как работает цикл for? Мне нужно чтобы перебирались значения с 0 до 999 (Иды игроков). Заранее спасибо.