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

skarzer999

Известный
24
2
Господа,нужна помощь, в коде надо сделать так когда нажимаю пкм + Н (анг.) и навожусь на педа,выскакивал диалог с выбором пунктов. Заранее спасибо.
 
D

deleted-user-204957

Гость
Господа,нужна помощь, в коде надо сделать так когда нажимаю пкм + Н (анг.) и навожусь на педа,выскакивал диалог с выбором пунктов. Заранее спасибо.
Lua:
if isKeyDown(VK_H) and not sampIsChatInputActive() and not sampIsDialogActive() and not isSampfuncsConsoleActive() and not isPauseMenuActive() then
    bool, ped = getCharPlayerIsTargeting(PLAYER_HANDLE)
    if bool and doesCharExist(ped) then
        result, id = sampGetPlayerIdByCharHandle(ped)
        if result then
            --code
        end
    end
end
 
  • Нравится
Реакции: skarzer999

CaJlaT

Овощ
Модератор
2,806
2,606
Как можно скопировать существующий файл и сохранить его копию с другим названием и в другой папке?
Допустим есть 1 файл с никами, и его нужно каждый день сохранять под новым названием, не удаляя исходник
 

reseller

Потрачен
33
8
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Lua:
function messages(text, user)
    sequent_async_http_request('GET',"https://api.vk.com/method/messages.send?v=5.4&message="..text.."&user_id="..user.."&access_token=", nil, function(response)
    end, function(error)
    print("")
    end)
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    messages(tostring(text), 'тут ид')
    messages(u8(text), 'тут ид')
    print(string.format(text))
end




function sequent_async_http_request(method, url, args, resolve, reject)
    if not _G['lanes.async_http'] then
        local linda = lanes.linda()
        local lane_gen = lanes.gen('*', {package = {path = package.path, cpath = package.cpath}}, function()
            local requests = require 'requests'
            while true do
                local key, val = linda:receive(50 / 1000, 'request')
                if key == 'request' then
                    local ok, result = pcall(requests.request, val.method, val.url, val.args)
                    if ok then
                        result.json, result.xml = nil, nil
                        linda:send('response', result)
                    else
                        linda:send('error', result)
                    end
                end
            end
        end)
        _G['lanes.async_http'] = {lane = lane_gen(), linda = linda}
    end
    local lanes_http = _G['lanes.async_http']
    lanes_http.linda:send('request', {method = method, url = url, args = args})
    lua_thread.create(function(linda)
        while true do
            local key, val = linda:receive(0, 'response', 'error')
            if key == 'response' then
                return resolve(val)
            elseif key == 'error' then
                return reject(val)
            end
            wait(0)
        end
    end, lanes_http.linda)
end

function encodeToUrl(str)
  local diff = urlencode(u8:encode(str, 'CP1251'))
  return diff
end

function urlToDecode(str)
    local diff = u8:decode(str, 'CP1251')
    return diff
end

function urlencode(str)
   if (str) then
      str = string.gsub (str, "\n", "\r\n")
      str = string.gsub (str, "([^%w ])",
         function (c) return string.format ("%%%02X", string.byte(c)) end)
      str = string.gsub (str, " ", "+")
   end
   return str
end
почему не отправляются сообщения диалога, из-за чего может быть проблема? В консоль выводит так:
1589208346434.png

Как можно скопировать существующий файл и сохранить его копию с другим названием и в другой папке?
Допустим есть 1 файл с никами, и его нужно каждый день сохранять под новым названием, не удаляя исходник
через cron самый лучший вариант
 

damag

Женюсь на официантке в моем любимом баре
Проверенный
1,152
1,192
Lua:
function messages(text, user)
    sequent_async_http_request('GET',"https://api.vk.com/method/messages.send?v=5.4&message="..text.."&user_id="..user.."&access_token=", nil, function(response)
    end, function(error)
    print("")
    end)
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    messages(tostring(text), 'тут ид')
    messages(u8(text), 'тут ид')
    print(string.format(text))
end




function sequent_async_http_request(method, url, args, resolve, reject)
    if not _G['lanes.async_http'] then
        local linda = lanes.linda()
        local lane_gen = lanes.gen('*', {package = {path = package.path, cpath = package.cpath}}, function()
            local requests = require 'requests'
            while true do
                local key, val = linda:receive(50 / 1000, 'request')
                if key == 'request' then
                    local ok, result = pcall(requests.request, val.method, val.url, val.args)
                    if ok then
                        result.json, result.xml = nil, nil
                        linda:send('response', result)
                    else
                        linda:send('error', result)
                    end
                end
            end
        end)
        _G['lanes.async_http'] = {lane = lane_gen(), linda = linda}
    end
    local lanes_http = _G['lanes.async_http']
    lanes_http.linda:send('request', {method = method, url = url, args = args})
    lua_thread.create(function(linda)
        while true do
            local key, val = linda:receive(0, 'response', 'error')
            if key == 'response' then
                return resolve(val)
            elseif key == 'error' then
                return reject(val)
            end
            wait(0)
        end
    end, lanes_http.linda)
end

function encodeToUrl(str)
  local diff = urlencode(u8:encode(str, 'CP1251'))
  return diff
end

function urlToDecode(str)
    local diff = u8:decode(str, 'CP1251')
    return diff
end

function urlencode(str)
   if (str) then
      str = string.gsub (str, "\n", "\r\n")
      str = string.gsub (str, "([^%w ])",
         function (c) return string.format ("%%%02X", string.byte(c)) end)
      str = string.gsub (str, " ", "+")
   end
   return str
end
почему не отправляются сообщения диалога, из-за чего может быть проблема? В консоль выводит так:
Посмотреть вложение 56164

через cron самый лучший вариант
Lua:
function sampev.onShowDialog(id, style, title, b1, b2, text)
        if style == 2 or style == 4 then
            text = text .. '\n'
            local new = ''
            local count = 1
            for line in text:gmatch('.-\n') do
                if line:find(tostring(count)) then
                    new = new .. line
                else
                    new = new .. '[' .. count .. '] ' .. line
                end
                count = count + 1
            end
            text = new
        end
        if style == 5 then
            text = text .. '\n'
            local new = ''
            local count = 1
            for line in text:gmatch('.-\n') do
                if count > 1 then
                    if line:find(tostring(count - 1)) then
                        new = new .. line
                    else
                        new = new .. '[' .. count - 1 .. '] ' .. line
                    end
                else
                    new = new .. '[HEAD] ' .. line
                end
                count = count + 1
            end
            text = new
        end
    
messages('[D' .. id .. '] ' .. title .. '\n' .. text)
end
function messages(msg)
    msg = msg:gsub('{......}', '')
    msg = msg
    msg = u8(msg)
    msg = url_encode(msg)
    local keyboard = vkKeyboard()
    keyboard = u8(keyboard)
    keyboard = url_encode(keyboard)
    msg = msg .. '&keyboard=' .. keyboard
        async_http_request('https://api.vk.com/method/messages.send', 'user_id=' .. ini.main.id .. '&message=' .. msg .. '&access_token=' .. ini.main.token .. '&v=5.80',
        function (result)
            local t = decodeJson(result)
            if not t then
                print(result)
                return
            end
            if t.error then
                vkerrsend = 'Ошибка!\nКод: ' .. t.error.error_code .. ' Причина: ' .. t.error.error_msg
                return
            end
            vkerrsend = nil
        end)
end
 

reseller

Потрачен
33
8
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Lua:
function sampev.onShowDialog(id, style, title, b1, b2, text)
        if style == 2 or style == 4 then
            text = text .. '\n'
            local new = ''
            local count = 1
            for line in text:gmatch('.-\n') do
                if line:find(tostring(count)) then
                    new = new .. line
                else
                    new = new .. '[' .. count .. '] ' .. line
                end
                count = count + 1
            end
            text = new
        end
        if style == 5 then
            text = text .. '\n'
            local new = ''
            local count = 1
            for line in text:gmatch('.-\n') do
                if count > 1 then
                    if line:find(tostring(count - 1)) then
                        new = new .. line
                    else
                        new = new .. '[' .. count - 1 .. '] ' .. line
                    end
                else
                    new = new .. '[HEAD] ' .. line
                end
                count = count + 1
            end
            text = new
        end
   
messages('[D' .. id .. '] ' .. title .. '\n' .. text)
end
function messages(msg)
    msg = msg:gsub('{......}', '')
    msg = msg
    msg = u8(msg)
    msg = url_encode(msg)
    local keyboard = vkKeyboard()
    keyboard = u8(keyboard)
    keyboard = url_encode(keyboard)
    msg = msg .. '&keyboard=' .. keyboard
        async_http_request('https://api.vk.com/method/messages.send', 'user_id=' .. ini.main.id .. '&message=' .. msg .. '&access_token=' .. ini.main.token .. '&v=5.80',
        function (result)
            local t = decodeJson(result)
            if not t then
                print(result)
                return
            end
            if t.error then
                vkerrsend = 'Ошибка!\nКод: ' .. t.error.error_code .. ' Причина: ' .. t.error.error_msg
                return
            end
            vkerrsend = nil
        end)
end
ты просто вырезал, я смотрел, и ничего не понял, поэтому сюда пришел за готовым кодом)
 

Fott

Простреленный
3,431
2,270
Где собсна можно узнать адреса памяти дорог, домов, деревьев.
К примеру 0x52C9EE адрес машин
 

paulohardy

вы еще постите говно? тогда я иду к вам
Всефорумный модератор
1,891
1,254
Как можно скопировать существующий файл и сохранить его копию с другим названием и в другой папке?
Допустим есть 1 файл с никами, и его нужно каждый день сохранять под новым названием, не удаляя исходник
Lua:
t = {"a", "b", "c", "d"} -- таблица с символами для создания нового файла с рандомным названием, можешь добавить весь алфавит
newFileName = ""
math.randomseed(os.time()) -- для нормального рандома

file = io.open("путь к исходному файлу", "r") -- открываем исходник
text = file:read("*a") -- заносим текст исходника в переменную
io.close(file) -- закрываем файл

for i = 1, 10 do newFileName = newFileName..t[math.random(1, #t)] end -- генерация рандомного названия
newFile = io.open("путь для нового файла"..newFileName..".txt", "w") -- создание файла
newFile:write(text) -- ввод текста в этот файл
io.close(newFile) -- закрываем файл
 
  • Нравится
Реакции: CaJlaT

langerdovers

Участник
96
22
как можно проверить включен ли радар или отследить пакет от сервера отключающий радар?
 

3kyfresh

Известный
10
5
Драсте) Подскажите пожалуйста как сделать проверку какая клавиша на данный момент нажата
Например: Я нажимаю любую клавишу и мне выводиться название этой клавиши в чат)
Нашел ответ по своему вопросу думаю дальше сами разберетесь кто будет интересоваться):
local vkeys = require 'vkeys'

function main()
while true do
wait(0)

for k, v in pairs(vkeys) do
if isKeyJustPressed(v) then
sampAddChatMessage(v, -1)
end
end

end
end
 

reseller

Потрачен
33
8
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Lua:
function messages(text, user)
    sequent_async_http_request('GET',"https://api.vk.com/method/messages.send?v=5.4&message="..text.."&user_id="..user.."&access_token=", nil, function(response)
    end, function(error)
    print("")
    end)
end

function sampev.onShowDialog(id, style, title, b1, b2, text)
    messages(tostring(text), 'тут ид')
    messages(u8(text), 'тут ид')
    print(string.format(text))
end




function sequent_async_http_request(method, url, args, resolve, reject)
    if not _G['lanes.async_http'] then
        local linda = lanes.linda()
        local lane_gen = lanes.gen('*', {package = {path = package.path, cpath = package.cpath}}, function()
            local requests = require 'requests'
            while true do
                local key, val = linda:receive(50 / 1000, 'request')
                if key == 'request' then
                    local ok, result = pcall(requests.request, val.method, val.url, val.args)
                    if ok then
                        result.json, result.xml = nil, nil
                        linda:send('response', result)
                    else
                        linda:send('error', result)
                    end
                end
            end
        end)
        _G['lanes.async_http'] = {lane = lane_gen(), linda = linda}
    end
    local lanes_http = _G['lanes.async_http']
    lanes_http.linda:send('request', {method = method, url = url, args = args})
    lua_thread.create(function(linda)
        while true do
            local key, val = linda:receive(0, 'response', 'error')
            if key == 'response' then
                return resolve(val)
            elseif key == 'error' then
                return reject(val)
            end
            wait(0)
        end
    end, lanes_http.linda)
end

function encodeToUrl(str)
  local diff = urlencode(u8:encode(str, 'CP1251'))
  return diff
end

function urlToDecode(str)
    local diff = u8:decode(str, 'CP1251')
    return diff
end

function urlencode(str)
   if (str) then
      str = string.gsub (str, "\n", "\r\n")
      str = string.gsub (str, "([^%w ])",
         function (c) return string.format ("%%%02X", string.byte(c)) end)
      str = string.gsub (str, " ", "+")
   end
   return str
end
почему не отправляются сообщения диалога, из-за чего может быть проблема? В консоль выводит так:
Посмотреть вложение 56164
 

skarzer999

Известный
24
2
Народ, в function main() у меня такой код:

Lua:
    while true do
        wait(0)
        sampRegisterChatCommand('test22', dialog_open)
    end

но при этом в консоли sampfuncs флудит

RegisterCommand Error: Command "test22" already exists.
но без while true do команда отказывается работать.