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

Di3

Участник
432
20
Код:
function getProcessorName()
    local handle = io.popen('reg.exe QUERY HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0 /v ProcessorNameString')
    local result = handle:read("*a")
    local processor_name = result:match('REG_SZ%s+(.+)'):gsub('%s+$', '')
    handle:close()
    return processor_name
end

Возможно ли избежать сворачивания игры от функции получения проца?
 

Petr_Sergeevich

Известный
Проверенный
707
296
Код:
function getProcessorName()
    local handle = io.popen('reg.exe QUERY HKLM\\HARDWARE\\DESCRIPTION\\System\\CentralProcessor\\0 /v ProcessorNameString')
    local result = handle:read("*a")
    local processor_name = result:match('REG_SZ%s+(.+)'):gsub('%s+$', '')
    handle:close()
    return processor_name
end

Возможно ли избежать сворачивания игры от функции получения проца?
Игра сворачивается из-за открытия командной строки в io.popen()
Используй другую функцию

Lua:
function getProcessorName()
    local qwords = ffi.typeof("uint64_t[?]")
    local dwords = ffi.typeof("uint32_t *")
    local cpuid_EAX_EDX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x5B\xC3")
    local cpuid_EBX_ECX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x91\x92\x93\x5B\xC3")
    local function cpuid(n)
        local arr = ffi.cast(dwords, qwords(2, cpuid_EAX_EDX(n), cpuid_EBX_ECX(n)))
        return ffi.string(arr, 4), ffi.string(arr + 2, 4), ffi.string(arr + 3, 4), ffi.string(arr + 1, 4)
    end
    local s1 = ""
    for n = 0x80000002, 0x80000004 do
        local eax, ebx, ecx, edx = cpuid(n)
        s1 = s1..eax..ebx..ecx..edx
    end
    s1 = s1:gsub("^%s+", ""):gsub("%z+$", "")
    local eax, ebx, ecx, edx = cpuid(0)
    local s2 = ebx..edx..ecx
    s2 = s2:gsub("^%s+", ""):gsub("%z+$", "")
    local result = ("%s, %s"):format(s1, s2)
    return result
end
 

Di3

Участник
432
20
Игра сворачивается из-за открытия командной строки в io.popen()
Используй другую функцию

Lua:
function getProcessorName()
    local qwords = ffi.typeof("uint64_t[?]")
    local dwords = ffi.typeof("uint32_t *")
    local cpuid_EAX_EDX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x5B\xC3")
    local cpuid_EBX_ECX = ffi.cast("__cdecl uint64_t (*)(uint32_t)", "\x53\x0F\xA2\x91\x92\x93\x5B\xC3")
    local function cpuid(n)
        local arr = ffi.cast(dwords, qwords(2, cpuid_EAX_EDX(n), cpuid_EBX_ECX(n)))
        return ffi.string(arr, 4), ffi.string(arr + 2, 4), ffi.string(arr + 3, 4), ffi.string(arr + 1, 4)
    end
    local s1 = ""
    for n = 0x80000002, 0x80000004 do
        local eax, ebx, ecx, edx = cpuid(n)
        s1 = s1..eax..ebx..ecx..edx
    end
    s1 = s1:gsub("^%s+", ""):gsub("%z+$", "")
    local eax, ebx, ecx, edx = cpuid(0)
    local s2 = ebx..edx..ecx
    s2 = s2:gsub("^%s+", ""):gsub("%z+$", "")
    local result = ("%s, %s"):format(s1, s2)
    return result
end
ага) другая крашит у каждого второго
 

Angr

Известный
291
97
Ну тогда нечего тебе получать информацию о системе, или сам придумывай
 

TRevrFra

Новичок
18
1
Ребят подскажите как убрать /o чат и /f чат с помощью этой строки (цвет строк знаю), чет не пойму что надо вставить вместо "????????"
Lua:
if ini.settings.MescoloroChat and color == coloroChat and text:find("????????") then return false end
45229
 

Warflex

Участник
158
17
как создать команду с пробелом допустим sampRegisterChatCoomand("usedrugs 1" dr) что бы именно работала каманда с пробелом
 

sanders

Потрачен
253
126
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Ребят подскажите как убрать /o чат и /f чат с помощью этой строки (цвет строк знаю), чет не пойму что надо вставить вместо "????????"
Lua:
if ini.settings.MescoloroChat and color == coloroChat and text:find("????????") then return false end
Посмотреть вложение 45229
Почему так? Игнорировать можно по-другому
Код:
function hook.OnServerMesssage(text, color)
if text:find("{цвет} %.+") then
return false
end
end
Как-то так, но надо поработать над сортировкой через %.
как создать команду с пробелом допустим sampRegisterChatCoomand("usedrugs 1" dr) что бы именно работала каманда с пробелом
Никак, только usedrugs_1
 

Angr

Известный
291
97
Ребят подскажите как убрать /o чат и /f чат с помощью этой строки (цвет строк знаю), чет не пойму что надо вставить вместо "????????"
Lua:
if ini.settings.MescoloroChat and color == coloroChat and text:find("????????") then return false end
Посмотреть вложение 45229
Ну если цвет нигде не повторяется то без текста блокируй
как создать команду с пробелом допустим sampRegisterChatCoomand("usedrugs 1" dr) что бы именно работала каманда с пробелом
Можешь попробовать ее перехватить через samp.lua

Lua:
local sampev = require 'lib.samp.events'
function sampev.onSendCommand(cmd)
   if cmd:lower() == "/userdrugs 1" then
      -- code
      -- чтобы не отправило в чат usedrugs возвращай false( return false )
   end
end
 
Последнее редактирование:

Fabregoo

Известный
656
128
не хочет обновляться, просто не обновляется
Lua:
require "lib.moonloader"
script_version '1.2'
local samp = require('samp.events')
function samp.onSendPlayerSync()
    if teleport then return false end
end

local teleport = false

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

local carfortp = {
    478, 430, 446, 452, 453, 473, 472, 454, 484, 493, 595, 543, 605, 538, 433, 408, 601, 582, 546, 578, 554, 413, 422, 407, 456, 407, 570
}

function samp.onSendPlayerSync()
    if teleport then return false end
end


function tpc(arg)
 if teleport then return end

 local posX, posY, posZ = getCharCoordinates(PLAYER_PED)
 local res, x, y, z = SearchMarker(posX, posY, posZ)
 if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}соси член', -1) end

 arg = tonumber(arg)
 if arg ~= nil then
     requestCollision(x, y)
     loadScene(x, y, z)
     teleport = true
     lua_thread.create(tp_proccess_started, arg, x, y, z)
 
     return
 end

 local veh = FindVehicleForTp()
 if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end

 requestCollision(x, y)
 loadScene(x, y, z)

 teleport = true
 lua_thread.create(tp_proccess_started, veh, x, y, z)
end

function ttp(arg)
    if teleport then return end
 
 
    local res, x, y, z = getTargetBlipCoordinates()
    if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Метка не найдена', -1) end
 
    arg = tonumber(arg)
    if arg ~= nil then
        requestCollision(x, y)
        loadScene(x, y, z)
      
        teleport = true
        lua_thread.create(tp_proccess_started, arg, x, y, getGroundZFor3dCoord(x, y, 999.0))
      
        return
    end
 
    local veh = FindVehicleForTp()
    if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end
 
    requestCollision(x, y)
    loadScene(x, y, z)
 
    teleport = true
    lua_thread.create(tp_proccess_started, veh, x, y, getGroundZFor3dCoord(x, y, 999.0))
end

function tp_proccess_started(veh, x, y, z)
    local res, hand = sampGetCarHandleBySampVehicleId(veh)
    if not res then
        teleport = false
      
        sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Телепорт отменён', -1)
      
        return
    end

    lockPlayerControl(true)

    local cx, cy, cz = getCharCoordinates(PLAYER_PED)
 
    wait(200)
 
    sendOnfootSync(cx, cy, cz, veh)
    setCharCoordinates(PLAYER_PED, x, y, z)
    sampForceOnfootSync()
    sendOnfootSync(x, y, z, veh)
    wait(1500)
    --sendPassengerSync(x, y, z)
    sendOnfootSync(x, y, z, 0)
 
    teleport = false
    sampAddChatMessage('{FF0000}[TP] {FFFFFF}Успешный телепорт', -1)
    lockPlayerControl(false)
end

function FindVehicleForTp()
    local x, y, z = getCharCoordinates(PLAYER_PED)
    for i = 0, 2000 do
        local res, veh = sampGetCarHandleBySampVehicleId(i)
        if res then
            local cx, cy, cz = getCarCoordinates(veh)
            if getDistanceBetweenCoords3d(x, y, z, cx, cy, cz) < 200.0 then
                 for j = 1, #carfortp do
                     if isCarModel(veh, carfortp[j]) then
                        return i
                     end
                 end
            end
        end
    end
    return -1
end

function sendPassengerSync(x, y, z)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(63)
    sampStorePlayerPassengerData(myId, data)
    setStructFloatElement(data, 12, x, false)
    setStructFloatElement(data, 16, y, false)
    setStructFloatElement(data, 20, z, false)
    setStructElement(data, 2, 1, 1, false)
    sampSendPassengerData(data)
    freeMemory(data)
end

function sendOnfootSync(x, y, z, veh)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(68)
    sampStorePlayerOnfootData(myId, data)
    setStructElement(data, 37, 1, 3, false)
    setStructFloatElement(data, 6, x, false)
    setStructFloatElement(data, 10, y, false)
    setStructFloatElement(data, 14, z, false)
    setStructElement(data, 62, 2, veh, false)
    sampSendOnfootData(data)
    freeMemory(data)
end

function SearchMarker(posX, posY, posZ)
  local ret_posX = 0.0
  local ret_posY = 0.0
  local ret_posZ = 0.0
  local isFind = false
  for id = 0, 31 do
      local MarkerStruct = 0
      MarkerStruct = 0xC7F168 + id * 56
      local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
      local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
      local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))
      if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
              ret_posX = MarkerPosX
              ret_posY = MarkerPosY
              ret_posZ = MarkerPosZ
              isFind = true
      end
  end
  return isFind, ret_posX, ret_posY, ret_posZ
end

function update()
    local updatePath = os.getenv('TEMP')..'\\Update.json'
    -- Проверка новой версии
    downloadUrlToFile("https://www.dropbox.com/s/05o5m89zdio4qmi/Update.json?dl=0", updatePath, function(id, status, p1, p2)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            local file = io.open(updatePath, 'r')
            if file and doesFileExist(updatePath) then
                local info = decodeJson(file:read("*a"))
                file:close(); os.remove(updatePath)
                if info.version ~= thisScript().version then
                    lua_thread.create(function()
                        wait(2000)
                        -- Загрузка скрипта, если версия изменилась
                        downloadUrlToFile("https://www.dropbox.com/s/c681n9rkv1rw2hq/FindS.lua?dl=0", thisScript().path, function(id, status, p1, p2)
                            if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                                ftext('Обновление до актуальной версии '..info.version..' обнаружено.')
                                thisScript():reload()
                            end
                        end)
                    end)
                else
                    ftext('Обновление не обнаружено. Актуальная версия '..info.version..'.', -1)
                end
            end
        end
    end)
end
 

BARRY BRADLEY

Известный
711
176
Здравствуйте, перейду сразу к делу:
Есть массив с информацией, пример:
mass = {"Бар GreenBitch", "Отель SanMorti", "Отель Veronika"}

Нужно реализовать поиск по массиву.
Тип ввожу в imgui.InputText текст и он ищит по массиву строки которые совпадают хотя бы на символ.
Пробовал так:
Lua:
imgui.InputText("##search", input_text)
for v = 1, #mass do
   if string.find(mass[v], input_text.v) then
      imgui.Text(input_text.v)
   end
end
Потом понял что оно не ищит русские символы по массиву и не ищет нормально по англ символам, как сделать этот поиск по массиву?
Нужно сделать что при вводе "Оте" искало все варианты с массива
 

Angr

Известный
291
97
Здравствуйте, перейду сразу к делу:
Есть массив с информацией, пример:
mass = {"Бар GreenBitch", "Отель SanMorti", "Отель Veronika"}

Нужно реализовать поиск по массиву.
Тип ввожу в imgui.InputText текст и он ищит по массиву строки которые совпадают хотя бы на символ.
Пробовал так:
Lua:
imgui.InputText("##search", input_text)
for v = 1, #mass do
   if string.find(mass[v], input_text.v) then
      imgui.Text(input_text.v)
   end
end
Потом понял что оно не ищит русские символы по массиву и не ищет нормально по англ символам, как сделать этот поиск по массиву?
Нужно сделать что при вводе "Оте" искало все варианты с массива
Посмотри тут > https://blast.hk/threads/13380/
Там есть работа с русским текстом, переводи таблицу и свой текст в нижний/вернхий регистр, чтоб лучше искало
не хочет обновляться, просто не обновляется
Lua:
require "lib.moonloader"
script_version '1.2'
local samp = require('samp.events')
function samp.onSendPlayerSync()
    if teleport then return false end
end

local teleport = false

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

local carfortp = {
    478, 430, 446, 452, 453, 473, 472, 454, 484, 493, 595, 543, 605, 538, 433, 408, 601, 582, 546, 578, 554, 413, 422, 407, 456, 407, 570
}

function samp.onSendPlayerSync()
    if teleport then return false end
end


function tpc(arg)
if teleport then return end

local posX, posY, posZ = getCharCoordinates(PLAYER_PED)
local res, x, y, z = SearchMarker(posX, posY, posZ)
if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}соси член', -1) end

arg = tonumber(arg)
if arg ~= nil then
     requestCollision(x, y)
     loadScene(x, y, z)
     teleport = true
     lua_thread.create(tp_proccess_started, arg, x, y, z)

     return
end

local veh = FindVehicleForTp()
if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end

requestCollision(x, y)
loadScene(x, y, z)

teleport = true
lua_thread.create(tp_proccess_started, veh, x, y, z)
end

function ttp(arg)
    if teleport then return end


    local res, x, y, z = getTargetBlipCoordinates()
    if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Метка не найдена', -1) end

    arg = tonumber(arg)
    if arg ~= nil then
        requestCollision(x, y)
        loadScene(x, y, z)
     
        teleport = true
        lua_thread.create(tp_proccess_started, arg, x, y, getGroundZFor3dCoord(x, y, 999.0))
     
        return
    end

    local veh = FindVehicleForTp()
    if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end

    requestCollision(x, y)
    loadScene(x, y, z)

    teleport = true
    lua_thread.create(tp_proccess_started, veh, x, y, getGroundZFor3dCoord(x, y, 999.0))
end

function tp_proccess_started(veh, x, y, z)
    local res, hand = sampGetCarHandleBySampVehicleId(veh)
    if not res then
        teleport = false
     
        sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Телепорт отменён', -1)
     
        return
    end

    lockPlayerControl(true)

    local cx, cy, cz = getCharCoordinates(PLAYER_PED)

    wait(200)

    sendOnfootSync(cx, cy, cz, veh)
    setCharCoordinates(PLAYER_PED, x, y, z)
    sampForceOnfootSync()
    sendOnfootSync(x, y, z, veh)
    wait(1500)
    --sendPassengerSync(x, y, z)
    sendOnfootSync(x, y, z, 0)

    teleport = false
    sampAddChatMessage('{FF0000}[TP] {FFFFFF}Успешный телепорт', -1)
    lockPlayerControl(false)
end

function FindVehicleForTp()
    local x, y, z = getCharCoordinates(PLAYER_PED)
    for i = 0, 2000 do
        local res, veh = sampGetCarHandleBySampVehicleId(i)
        if res then
            local cx, cy, cz = getCarCoordinates(veh)
            if getDistanceBetweenCoords3d(x, y, z, cx, cy, cz) < 200.0 then
                 for j = 1, #carfortp do
                     if isCarModel(veh, carfortp[j]) then
                        return i
                     end
                 end
            end
        end
    end
    return -1
end

function sendPassengerSync(x, y, z)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(63)
    sampStorePlayerPassengerData(myId, data)
    setStructFloatElement(data, 12, x, false)
    setStructFloatElement(data, 16, y, false)
    setStructFloatElement(data, 20, z, false)
    setStructElement(data, 2, 1, 1, false)
    sampSendPassengerData(data)
    freeMemory(data)
end

function sendOnfootSync(x, y, z, veh)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(68)
    sampStorePlayerOnfootData(myId, data)
    setStructElement(data, 37, 1, 3, false)
    setStructFloatElement(data, 6, x, false)
    setStructFloatElement(data, 10, y, false)
    setStructFloatElement(data, 14, z, false)
    setStructElement(data, 62, 2, veh, false)
    sampSendOnfootData(data)
    freeMemory(data)
end

function SearchMarker(posX, posY, posZ)
  local ret_posX = 0.0
  local ret_posY = 0.0
  local ret_posZ = 0.0
  local isFind = false
  for id = 0, 31 do
      local MarkerStruct = 0
      MarkerStruct = 0xC7F168 + id * 56
      local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
      local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
      local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))
      if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
              ret_posX = MarkerPosX
              ret_posY = MarkerPosY
              ret_posZ = MarkerPosZ
              isFind = true
      end
  end
  return isFind, ret_posX, ret_posY, ret_posZ
end

function update()
    local updatePath = os.getenv('TEMP')..'\\Update.json'
    -- Проверка новой версии
    downloadUrlToFile("https://www.dropbox.com/s/05o5m89zdio4qmi/Update.json?dl=0", updatePath, function(id, status, p1, p2)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            local file = io.open(updatePath, 'r')
            if file and doesFileExist(updatePath) then
                local info = decodeJson(file:read("*a"))
                file:close(); os.remove(updatePath)
                if info.version ~= thisScript().version then
                    lua_thread.create(function()
                        wait(2000)
                        -- Загрузка скрипта, если версия изменилась
                        downloadUrlToFile("https://www.dropbox.com/s/c681n9rkv1rw2hq/FindS.lua?dl=0", thisScript().path, function(id, status, p1, p2)
                            if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                                ftext('Обновление до актуальной версии '..info.version..' обнаружено.')
                                thisScript():reload()
                            end
                        end)
                    end)
                else
                    ftext('Обновление не обнаружено. Актуальная версия '..info.version..'.', -1)
                end
            end
        end
    end)
end
ссылка плохая скорее всего
 
Последнее редактирование:

TRevrFra

Новичок
18
1
Актуально, не могу решить проблему:
Ребят подскажите как убрать /o чат и /f чат с помощью этой строки (цвет строк знаю), чет не пойму что надо вставить вместо "????????"
Lua:
if ini.settings.MescoloroChat and color == coloroChat and text:find("????????") then return false end
Lua:
if ini.settings.MescoloroChat and color == 520093782 then return false end
- не работает)
Посмотреть вложение 45229
 

Fabregoo

Известный
656
128
не хочет обновляться, просто не обновляется
Lua:
require "lib.moonloader"
script_version '1.2'
local samp = require('samp.events')
function samp.onSendPlayerSync()
    if teleport then return false end
end

local teleport = false

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

local carfortp = {
    478, 430, 446, 452, 453, 473, 472, 454, 484, 493, 595, 543, 605, 538, 433, 408, 601, 582, 546, 578, 554, 413, 422, 407, 456, 407, 570
}

function samp.onSendPlayerSync()
    if teleport then return false end
end


function tpc(arg)
 if teleport then return end

 local posX, posY, posZ = getCharCoordinates(PLAYER_PED)
 local res, x, y, z = SearchMarker(posX, posY, posZ)
 if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}соси член', -1) end

 arg = tonumber(arg)
 if arg ~= nil then
     requestCollision(x, y)
     loadScene(x, y, z)
     teleport = true
     lua_thread.create(tp_proccess_started, arg, x, y, z)
 
     return
 end

 local veh = FindVehicleForTp()
 if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end

 requestCollision(x, y)
 loadScene(x, y, z)

 teleport = true
 lua_thread.create(tp_proccess_started, veh, x, y, z)
end

function ttp(arg)
    if teleport then return end
 
 
    local res, x, y, z = getTargetBlipCoordinates()
    if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Метка не найдена', -1) end
 
    arg = tonumber(arg)
    if arg ~= nil then
        requestCollision(x, y)
        loadScene(x, y, z)
      
        teleport = true
        lua_thread.create(tp_proccess_started, arg, x, y, getGroundZFor3dCoord(x, y, 999.0))
      
        return
    end
 
    local veh = FindVehicleForTp()
    if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end
 
    requestCollision(x, y)
    loadScene(x, y, z)
 
    teleport = true
    lua_thread.create(tp_proccess_started, veh, x, y, getGroundZFor3dCoord(x, y, 999.0))
end

function tp_proccess_started(veh, x, y, z)
    local res, hand = sampGetCarHandleBySampVehicleId(veh)
    if not res then
        teleport = false
      
        sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Телепорт отменён', -1)
      
        return
    end

    lockPlayerControl(true)

    local cx, cy, cz = getCharCoordinates(PLAYER_PED)
 
    wait(200)
 
    sendOnfootSync(cx, cy, cz, veh)
    setCharCoordinates(PLAYER_PED, x, y, z)
    sampForceOnfootSync()
    sendOnfootSync(x, y, z, veh)
    wait(1500)
    --sendPassengerSync(x, y, z)
    sendOnfootSync(x, y, z, 0)
 
    teleport = false
    sampAddChatMessage('{FF0000}[TP] {FFFFFF}Успешный телепорт', -1)
    lockPlayerControl(false)
end

function FindVehicleForTp()
    local x, y, z = getCharCoordinates(PLAYER_PED)
    for i = 0, 2000 do
        local res, veh = sampGetCarHandleBySampVehicleId(i)
        if res then
            local cx, cy, cz = getCarCoordinates(veh)
            if getDistanceBetweenCoords3d(x, y, z, cx, cy, cz) < 200.0 then
                 for j = 1, #carfortp do
                     if isCarModel(veh, carfortp[j]) then
                        return i
                     end
                 end
            end
        end
    end
    return -1
end

function sendPassengerSync(x, y, z)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(63)
    sampStorePlayerPassengerData(myId, data)
    setStructFloatElement(data, 12, x, false)
    setStructFloatElement(data, 16, y, false)
    setStructFloatElement(data, 20, z, false)
    setStructElement(data, 2, 1, 1, false)
    sampSendPassengerData(data)
    freeMemory(data)
end

function sendOnfootSync(x, y, z, veh)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(68)
    sampStorePlayerOnfootData(myId, data)
    setStructElement(data, 37, 1, 3, false)
    setStructFloatElement(data, 6, x, false)
    setStructFloatElement(data, 10, y, false)
    setStructFloatElement(data, 14, z, false)
    setStructElement(data, 62, 2, veh, false)
    sampSendOnfootData(data)
    freeMemory(data)
end

function SearchMarker(posX, posY, posZ)
  local ret_posX = 0.0
  local ret_posY = 0.0
  local ret_posZ = 0.0
  local isFind = false
  for id = 0, 31 do
      local MarkerStruct = 0
      MarkerStruct = 0xC7F168 + id * 56
      local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
      local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
      local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))
      if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
              ret_posX = MarkerPosX
              ret_posY = MarkerPosY
              ret_posZ = MarkerPosZ
              isFind = true
      end
  end
  return isFind, ret_posX, ret_posY, ret_posZ
end

function update()
    local updatePath = os.getenv('TEMP')..'\\Update.json'
    -- Проверка новой версии
    downloadUrlToFile("https://www.dropbox.com/s/05o5m89zdio4qmi/Update.json?dl=0", updatePath, function(id, status, p1, p2)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            local file = io.open(updatePath, 'r')
            if file and doesFileExist(updatePath) then
                local info = decodeJson(file:read("*a"))
                file:close(); os.remove(updatePath)
                if info.version ~= thisScript().version then
                    lua_thread.create(function()
                        wait(2000)
                        -- Загрузка скрипта, если версия изменилась
                        downloadUrlToFile("https://www.dropbox.com/s/c681n9rkv1rw2hq/FindS.lua?dl=0", thisScript().path, function(id, status, p1, p2)
                            if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                                ftext('Обновление до актуальной версии '..info.version..' обнаружено.')
                                thisScript():reload()
                            end
                        end)
                    end)
                else
                    ftext('Обновление не обнаружено. Актуальная версия '..info.version..'.', -1)
                end
            end
        end
    end)
end
 

sanders

Потрачен
253
126
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
не хочет обновляться, просто не обновляется
Lua:
require "lib.moonloader"
script_version '1.2'
local samp = require('samp.events')
function samp.onSendPlayerSync()
    if teleport then return false end
end

local teleport = false

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

local carfortp = {
    478, 430, 446, 452, 453, 473, 472, 454, 484, 493, 595, 543, 605, 538, 433, 408, 601, 582, 546, 578, 554, 413, 422, 407, 456, 407, 570
}

function samp.onSendPlayerSync()
    if teleport then return false end
end


function tpc(arg)
if teleport then return end

local posX, posY, posZ = getCharCoordinates(PLAYER_PED)
local res, x, y, z = SearchMarker(posX, posY, posZ)
if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}соси член', -1) end

arg = tonumber(arg)
if arg ~= nil then
     requestCollision(x, y)
     loadScene(x, y, z)
     teleport = true
     lua_thread.create(tp_proccess_started, arg, x, y, z)

     return
end

local veh = FindVehicleForTp()
if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end

requestCollision(x, y)
loadScene(x, y, z)

teleport = true
lua_thread.create(tp_proccess_started, veh, x, y, z)
end

function ttp(arg)
    if teleport then return end


    local res, x, y, z = getTargetBlipCoordinates()
    if not res then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Метка не найдена', -1) end

    arg = tonumber(arg)
    if arg ~= nil then
        requestCollision(x, y)
        loadScene(x, y, z)
    
        teleport = true
        lua_thread.create(tp_proccess_started, arg, x, y, getGroundZFor3dCoord(x, y, 999.0))
    
        return
    end

    local veh = FindVehicleForTp()
    if veh == -1 then return sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Машина не найдена', -1) end

    requestCollision(x, y)
    loadScene(x, y, z)

    teleport = true
    lua_thread.create(tp_proccess_started, veh, x, y, getGroundZFor3dCoord(x, y, 999.0))
end

function tp_proccess_started(veh, x, y, z)
    local res, hand = sampGetCarHandleBySampVehicleId(veh)
    if not res then
        teleport = false
    
        sampAddChatMessage('{FF0000}[Ошибка] {FFFFFF}Телепорт отменён', -1)
    
        return
    end

    lockPlayerControl(true)

    local cx, cy, cz = getCharCoordinates(PLAYER_PED)

    wait(200)

    sendOnfootSync(cx, cy, cz, veh)
    setCharCoordinates(PLAYER_PED, x, y, z)
    sampForceOnfootSync()
    sendOnfootSync(x, y, z, veh)
    wait(1500)
    --sendPassengerSync(x, y, z)
    sendOnfootSync(x, y, z, 0)

    teleport = false
    sampAddChatMessage('{FF0000}[TP] {FFFFFF}Успешный телепорт', -1)
    lockPlayerControl(false)
end

function FindVehicleForTp()
    local x, y, z = getCharCoordinates(PLAYER_PED)
    for i = 0, 2000 do
        local res, veh = sampGetCarHandleBySampVehicleId(i)
        if res then
            local cx, cy, cz = getCarCoordinates(veh)
            if getDistanceBetweenCoords3d(x, y, z, cx, cy, cz) < 200.0 then
                 for j = 1, #carfortp do
                     if isCarModel(veh, carfortp[j]) then
                        return i
                     end
                 end
            end
        end
    end
    return -1
end

function sendPassengerSync(x, y, z)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(63)
    sampStorePlayerPassengerData(myId, data)
    setStructFloatElement(data, 12, x, false)
    setStructFloatElement(data, 16, y, false)
    setStructFloatElement(data, 20, z, false)
    setStructElement(data, 2, 1, 1, false)
    sampSendPassengerData(data)
    freeMemory(data)
end

function sendOnfootSync(x, y, z, veh)
    local _, myId = sampGetPlayerIdByCharHandle(PLAYER_PED)
    local data = allocateMemory(68)
    sampStorePlayerOnfootData(myId, data)
    setStructElement(data, 37, 1, 3, false)
    setStructFloatElement(data, 6, x, false)
    setStructFloatElement(data, 10, y, false)
    setStructFloatElement(data, 14, z, false)
    setStructElement(data, 62, 2, veh, false)
    sampSendOnfootData(data)
    freeMemory(data)
end

function SearchMarker(posX, posY, posZ)
  local ret_posX = 0.0
  local ret_posY = 0.0
  local ret_posZ = 0.0
  local isFind = false
  for id = 0, 31 do
      local MarkerStruct = 0
      MarkerStruct = 0xC7F168 + id * 56
      local MarkerPosX = representIntAsFloat(readMemory(MarkerStruct + 0, 4, false))
      local MarkerPosY = representIntAsFloat(readMemory(MarkerStruct + 4, 4, false))
      local MarkerPosZ = representIntAsFloat(readMemory(MarkerStruct + 8, 4, false))
      if MarkerPosX ~= 0.0 or MarkerPosY ~= 0.0 or MarkerPosZ ~= 0.0 then
              ret_posX = MarkerPosX
              ret_posY = MarkerPosY
              ret_posZ = MarkerPosZ
              isFind = true
      end
  end
  return isFind, ret_posX, ret_posY, ret_posZ
end

function update()
    local updatePath = os.getenv('TEMP')..'\\Update.json'
    -- Проверка новой версии
    downloadUrlToFile("https://www.dropbox.com/s/05o5m89zdio4qmi/Update.json?dl=0", updatePath, function(id, status, p1, p2)
        if status == dlstatus.STATUS_ENDDOWNLOADDATA then
            local file = io.open(updatePath, 'r')
            if file and doesFileExist(updatePath) then
                local info = decodeJson(file:read("*a"))
                file:close(); os.remove(updatePath)
                if info.version ~= thisScript().version then
                    lua_thread.create(function()
                        wait(2000)
                        -- Загрузка скрипта, если версия изменилась
                        downloadUrlToFile("https://www.dropbox.com/s/c681n9rkv1rw2hq/FindS.lua?dl=0", thisScript().path, function(id, status, p1, p2)
                            if status == dlstatus.STATUS_ENDDOWNLOADDATA then
                                ftext('Обновление до актуальной версии '..info.version..' обнаружено.')
                                thisScript():reload()
                            end
                        end)
                    end)
                else
                    ftext('Обновление не обнаружено. Актуальная версия '..info.version..'.', -1)
                end
            end
        end
    end)
end
downloadUrlToFile("https://www.dropbox.com/s/05o5m89zdio4qmi/Update.json?dl=0", updatePath, function(id, status, p1, p2)
dl - 1, а не 0
downloadUrlToFile("https://www.dropbox.com/s/05o5m89zdio4qmi/Update.json?dl=1", updatePath, function(id, status, p1, p2)
 
  • Нравится
Реакции: Fabregoo