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

7PEX

Известный
101
13
Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    imgui.Text(u8'Введите ID Вконтакте')
        imgui.InputText(u8'Вводить сюда',text_buffer)
    if imgui.Button(u8'Отправить') then -- а вот и кнопка с действием
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..text_buffer..'&message=sosat.xui&v=5.37&access_token='..token, nil --[[Аргументы запроса]],
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
      printStringNow(u8'Отправлено', 1000)
    end
    imgui.End()
  end
end
не?
Не,крашится
 

sdfaw

Активный
718
150
как эту ошибку исправить?
914cghN.png
 
  • Нравится
Реакции: lpox12i31il2s

senyank

Новичок
3
0
Lua:
local sampev = require 'lib.samp.events'
local mati, id = sampGetCurrentDialogId()

function main()
    if not isSampAvailable() or not isSampfuncsLoaded() then return
    end
    while not isSampAvailable() do wait(100)
    end
    sampRegisterChatCommand("as", assha)
    sampAddChatMessage("{FFFFFF}AvtoSklad by senyank for {46494F}BLAST.{2265E8}HK", -1)
end

function sampev.onShowDialog(id, style, title, btn1, btn2, text)
     -- code
end

К кому можно обратиться за помощью, чтобы вылечить мой кривой мозг?
 

Di3

Участник
432
20
Lua:
local sampev = require 'lib.samp.events'
local mati, id = sampGetCurrentDialogId()

function main()
    if not isSampAvailable() or not isSampfuncsLoaded() then return
    end
    while not isSampAvailable() do wait(100)
    end
    sampRegisterChatCommand("as", assha)
    sampAddChatMessage("{FFFFFF}AvtoSklad by senyank for {46494F}BLAST.{2265E8}HK", -1)
end

function sampev.onShowDialog(id, style, title, btn1, btn2, text)
     -- code
end

К кому можно обратиться за помощью, чтобы вылечить мой кривой мозг?

local mati, id = sampGetCurrentDialogId()
А зачем в начале?) Сделай получение ID диалога на кнопку и все.
А onShowDialog так.

Lua:
require 'lib.moonloader'
local sampev = require 'lib.samp.events'

function main()
if not isSampLoaded() or not  isSampfuncsLoaded() then return end
sampRegisterChatCommand("as", assha)
    sampAddChatMessage("{FFFFFF}AvtoSklad by senyank for {46494F}BLAST.{2265E8}HK", -1)
while not isSampAvailable() do wait(100) end
if isKeyJustPressed(49) then
local mati, id = sampGetCurrentDialogId()
sampAddChatMessage(id,-1) -- Получаем ид диалога по нажатию клавиши '1'
end
wait(0)
end
end

function sampev.onShowDialog(id, style, title, btn1, btn2, text)
     -- code
end

а чо за инфа?
Lua:
local distance, time = response.text:match('<p>.+<span id="totalDistance">(%d+)</span>.+<span id="totalTime">(%d+:%d+)</span></p>')
Lua:
function  SE.onServerMessage(collor,msg)
if msg:find('Nik %[(.*)%]  R%-IP %[(.*)%]  IP %[(.*)%]') and statuschecktrue == true then
    lua_thread.create(function()
    statuschecktrue = false
    if statusproverkiregov == false then
local reginick,regip,reglast =    msg:match('Nik %[(.*)%]  R%-IP %[(.*)%]  IP %[(.*)%]')
    statusproverkiregov=true
regdanny2 = {}
regdanny =  {}
    async_http_request("GET", 'http://ip-api.com/json/'..regip..'?lang=ru', rast,
    function(response)
        local regvrem = u8:decode(response.text)
local city,country,isp = regvrem:match('city%":%"(.*)%"%,%"country%":%"(.*)%"%,%"countryCode.*%"org%":%"(.*)%"%,%"query%"')
        regdanny = {country,city,isp}
    end,
    function(err)
    print(err)
    sampAddChatMessage('[Ошибка] Не удалось загрузить информацию о REG IP', 0xFF0000)
regdanny[1] = 'ERROR'
    end)
    async_http_request("GET", 'http://ip-api.com/json/'..reglast..'?lang=ru', rast,
    function(response)
        local regvrem = u8:decode(response.text)
local city,country,isp = regvrem:match('city%":%"(.*)%"%,%"country%":%"(.*)%"%,%"countryCode.*%"org%":%"(.*)%"%,%"query%"')
regdanny2 = {country,city,isp}
    end,
    function(err)
                sampAddChatMessage('[Ошибка] Не удалось загрузить информацию о LAST IP', 0xFF0000)
    print(err)
regdanny2[1] = 'ERROR'
    end)
    while regdanny[1] == nil or  regdanny2[1] == nil do wait(0)  end
    if not tostring(regdanny[1]):find('ERROR') and not tostring(regdanny2[1]):find('ERROR')  then
        if   not (tostring(regdanny[1]) == tostring(regdanny2[1])) or not (tostring(regdanny[2]) == tostring(regdanny2[2])) then
async_http_request("GET", 'https://www.avtodispetcher.ru/distance/?from='..u8(regdanny[2])..'&to='..u8(regdanny2[2]), dist,
            function(response)
                rastregi = nil
                    timerastayan = nil
                        rastregi, timerastayan = response.text:match('<p>.+<span id="totalDistance">(%d+)</span>.+<span id="totalTime">(%d+:%d+)</span></p>')
if not rastregi or not timerastayan then
rastregi = 'Неизвестно'
timerastayan = 'Неизвестно'
end
            end,
            function(err)
                        sampAddChatMessage('[Ошибка] Не удалось загрузить информацию о расстоянии', 0xFF0000)
            print(err)
            rastregi = 'Неизвестно'
            timerastayan = 'Неизвестно'
            end)
            while not rastregi do wait(0) end
        else
            rastregi=0
            timerastayan='00:00'
        end
sampAddChatMessage('['..reginick..'] R-IP: ['..regip..'] L-IP: ['..reglast..']', -89368321)
sampAddChatMessage('[REG] Страна: '..regdanny[1]..' [LAST] Страна: '..regdanny2[1], -89368321)
sampAddChatMessage('[REG] Город: '..regdanny[2]..' [LAST] Город: '..regdanny2[2], -89368321)
sampAddChatMessage('[REG] Провайдер: '..regdanny[3]..' [LAST] Провайдер: '..regdanny2[3], -89368321)
sampAddChatMessage('[Расстояние] От '..regdanny[2]..' до '..regdanny2[2]..' ~'..rastregi..' Км. Время: ~'..timerastayan, -89368321)
else
sampAddChatMessage('Ошибка! Повторите попытку.', -89368321)
end
wait(1000)
statusproverkiregov=false
else
    sampAddChatMessage('[Ошибка] Не флуди.', -1)
end
return
end)
return false
end

end
Все выводится,но через какое-то время гташку тупо оффает) Не сможешь помочь?
 
  • Нравится
Реакции: [SA ARZ]

senyank

Новичок
3
0
local mati, id = sampGetCurrentDialogId()
А зачем в начале?) Сделай получение ID диалога на кнопку и все.
А onShowDialog так.

Lua:
require 'lib.moonloader'
local sampev = require 'lib.samp.events'

function main()
if not isSampLoaded() or not  isSampfuncsLoaded() then return end
sampRegisterChatCommand("as", assha)
    sampAddChatMessage("{FFFFFF}AvtoSklad by senyank for {46494F}BLAST.{2265E8}HK", -1)
while not isSampAvailable() do wait(100) end
if isKeyJustPressed(49) then
local mati, id = sampGetCurrentDialogId()
sampAddChatMessage(id,-1) -- Получаем ид диалога по нажатию клавиши '1'
end
wait(0)
end
end

function sampev.onShowDialog(id, style, title, btn1, btn2, text)
     -- code
end


Lua:
function  SE.onServerMessage(collor,msg)
if msg:find('Nik %[(.*)%]  R%-IP %[(.*)%]  IP %[(.*)%]') and statuschecktrue == true then
    lua_thread.create(function()
    statuschecktrue = false
    if statusproverkiregov == false then
local reginick,regip,reglast =    msg:match('Nik %[(.*)%]  R%-IP %[(.*)%]  IP %[(.*)%]')
    statusproverkiregov=true
regdanny2 = {}
regdanny =  {}
    async_http_request("GET", 'http://ip-api.com/json/'..regip..'?lang=ru', rast,
    function(response)
        local regvrem = u8:decode(response.text)
local city,country,isp = regvrem:match('city%":%"(.*)%"%,%"country%":%"(.*)%"%,%"countryCode.*%"org%":%"(.*)%"%,%"query%"')
        regdanny = {country,city,isp}
    end,
    function(err)
    print(err)
    sampAddChatMessage('[Ошибка] Не удалось загрузить информацию о REG IP', 0xFF0000)
regdanny[1] = 'ERROR'
    end)
    async_http_request("GET", 'http://ip-api.com/json/'..reglast..'?lang=ru', rast,
    function(response)
        local regvrem = u8:decode(response.text)
local city,country,isp = regvrem:match('city%":%"(.*)%"%,%"country%":%"(.*)%"%,%"countryCode.*%"org%":%"(.*)%"%,%"query%"')
regdanny2 = {country,city,isp}
    end,
    function(err)
                sampAddChatMessage('[Ошибка] Не удалось загрузить информацию о LAST IP', 0xFF0000)
    print(err)
regdanny2[1] = 'ERROR'
    end)
    while regdanny[1] == nil or  regdanny2[1] == nil do wait(0)  end
    if not tostring(regdanny[1]):find('ERROR') and not tostring(regdanny2[1]):find('ERROR')  then
        if   not (tostring(regdanny[1]) == tostring(regdanny2[1])) or not (tostring(regdanny[2]) == tostring(regdanny2[2])) then
async_http_request("GET", 'https://www.avtodispetcher.ru/distance/?from='..u8(regdanny[2])..'&to='..u8(regdanny2[2]), dist,
            function(response)
                rastregi = nil
                    timerastayan = nil
                        rastregi, timerastayan = response.text:match('<p>.+<span id="totalDistance">(%d+)</span>.+<span id="totalTime">(%d+:%d+)</span></p>')
if not rastregi or not timerastayan then
rastregi = 'Неизвестно'
timerastayan = 'Неизвестно'
end
            end,
            function(err)
                        sampAddChatMessage('[Ошибка] Не удалось загрузить информацию о расстоянии', 0xFF0000)
            print(err)
            rastregi = 'Неизвестно'
            timerastayan = 'Неизвестно'
            end)
            while not rastregi do wait(0) end
        else
            rastregi=0
            timerastayan='00:00'
        end
sampAddChatMessage('['..reginick..'] R-IP: ['..regip..'] L-IP: ['..reglast..']', -89368321)
sampAddChatMessage('[REG] Страна: '..regdanny[1]..' [LAST] Страна: '..regdanny2[1], -89368321)
sampAddChatMessage('[REG] Город: '..regdanny[2]..' [LAST] Город: '..regdanny2[2], -89368321)
sampAddChatMessage('[REG] Провайдер: '..regdanny[3]..' [LAST] Провайдер: '..regdanny2[3], -89368321)
sampAddChatMessage('[Расстояние] От '..regdanny[2]..' до '..regdanny2[2]..' ~'..rastregi..' Км. Время: ~'..timerastayan, -89368321)
else
sampAddChatMessage('Ошибка! Повторите попытку.', -89368321)
end
wait(1000)
statusproverkiregov=false
else
    sampAddChatMessage('[Ошибка] Не флуди.', -1)
end
return
end)
return false
end

end
Все выводится,но через какое-то время гташку тупо оффает) Не сможешь помочь?
дай свой vk/ds/skype пожалуйста :3
 

7PEX

Известный
101
13
Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    if imgui.Checkbox(u8'Включить', check_test) then -- а вот и кнопка с действием
            printStringNow(u8'Activated', 1000)
            if string.find(text, 'Администратор') then
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..vkid.settings.vkid..'&message='..u8'Вам%20написал%20администратор'..'&v=5.37&access_token='..token, nil, -- Отправка запроса
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
            end

    end
    imgui.End()
  end
end
Почему сообщение не отправляет?
 

atizoff

приобретаю кашель за деньги
Проверенный
1,295
1,179
пушто надо text_buffer.v

Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    if imgui.Checkbox(u8'Включить', check_test) then -- а вот и кнопка с действием
            printStringNow(u8'Activated', 1000)
            if string.find(text, 'Администратор') then
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..vkid.settings.vkid..'&message='..u8'Вам%20написал%20администратор'..'&v=5.37&access_token='..token, nil, -- Отправка запроса
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
            end

    end
    imgui.End()
  end
end
Почему сообщение не отправляет?
отпиши в лс на бластхаке с сурсом(инетерсно очень), а так не стоит проверка на чекбокс после 5 строчки
if check_test.v then
-- code
end
 

7PEX

Известный
101
13
пушто надо text_buffer.v


отпиши в лс на бластхаке с сурсом(инетерсно очень), а так не стоит проверка на чекбокс после 5 строчки
if check_test.v then
-- code
end
Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    if imgui.Checkbox(u8'Включить', check_test) then -- а вот и кнопка с действием
            printStringNow(u8'Activated', 1000)
            if check_test.v then
            if string.find(text, 'Администратор') then
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..vkid.settings.vkid..'&message='..u8'Вам%20написал%20администратор'..'&v=5.37&access_token='..token, nil, -- Отправка запроса
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
            end
        end

    end
    imgui.End()
  end
end
Не помогло :C
 

FBenz

Активный
328
40
Регистрация команды и область выполнения совсем разное. Тело команды выполняется вне зависимости от майна.

А нельзя перенести в самое начало мейна?
Я подозреваю что main точка вхождения и именно там инициализируется thisScript.
В начале скрипта есть массив, который использует ini файл, который скачивается. А т.к. он еще не скачан, то выбивает ошибку. Если перенести перезагрузку в начало мейна, то будет абсолютно то же самое.
 

atizoff

приобретаю кашель за деньги
Проверенный
1,295
1,179
Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    if imgui.Checkbox(u8'Включить', check_test) then -- а вот и кнопка с действием
            printStringNow(u8'Activated', 1000)
            if check_test.v then
            if string.find(text, 'Администратор') then
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..vkid.settings.vkid..'&message='..u8'Вам%20написал%20администратор'..'&v=5.37&access_token='..token, nil, -- Отправка запроса
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
            end
        end

    end
    imgui.End()
  end
end
Не помогло :C
Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    if imgui.Checkbox(u8'Включить', check_test) then -- а вот и кнопка с действием
            if check_test.v then
            printStringNow(u8'Activated', 1000)
            if string.find(text, 'Администратор') then
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..vkid.settings.vkid..'&message='..u8'Вам%20написал%20администратор'..'&v=5.37&access_token='..token, nil, -- Отправка запроса
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
            end
        end

    end
    imgui.End()
  end
end
 
  • Нравится
Реакции: 7PEX

7PEX

Известный
101
13
Lua:
function imgui.OnDrawFrame()
  if main_window_state.v then -- чтение и запись значения такой переменной осуществляется через поле v (или Value)
    imgui.SetNextWindowSize(imgui.ImVec2(300, 400), imgui.Cond.FirstUseEver) -- Смена размера окна
    imgui.Begin('VK Optins by Grekh', main_window_state)
    if imgui.Checkbox(u8'Включить', check_test) then -- а вот и кнопка с действием
            if check_test.v then
            printStringNow(u8'Activated', 1000)
            if string.find(text, 'Администратор') then
            asyncHttpRequest('POST', 'https://api.vk.com/method/messages.send?user_id='..vkid.settings.vkid..'&message='..u8'Вам%20написал%20администратор'..'&v=5.37&access_token='..token, nil, -- Отправка запроса
         function(response)
            print(response.text)
         end,
         function(err)
            --
         end)
            end
        end

    end
    imgui.End()
  end
end
Спасибо дружище)
 
  • Нравится
Реакции: atizoff

offsya

Новичок
12
0
Lua:
script_name('accept')
script_author('offsya')
require "lib.moonloader"
local sampev = require 'lib.samp.events'
local main_color = 0x5A90CE
local main_color_text = "{5A90CE}"
local white_color = "{FFFFFF}"
local label = 0
function main()
if not isSampLoaded() or not isSampfuncsLoaded() then return end
while not isSampAvailable() do wait(100) end
sampAddChatMessage("{2c46c7}[AACC] {0596f7}loaded", 0x0596f7)
while true do
   wait(0)
end
   end
     function sampev.onServerMessage(color, text)
        if string.find(text, 'дэнь', 1, true) then
            sampSendChat("у маэй девушкэ дэнь раждениэ")
end
end

Как сделать чтобы функция срабатывала с задержкой? А не так, чтобы "дэнь" выскочило и сразу пишет