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

СоМиК

Известный
457
310
Как на луа сделать так, чтобы телепортировало именно на поверхность (чтобы пиксель в пиксель к поверхности мира, если находишься под текстурами)
 

Sanchez.

Известный
704
187
Lua:
for k, v in pairs(getAllChars()) do
            local mindist = 390

            result, id = sampGetPlayerIdByCharHandle(v)
            pX, pY, pZ = getCharCoordinates(v)
            mX, mY, mZ = getCharCoordinates(PLAYER_PED)

            dist = getDistanceBetweenCoords3d(pX, pY, pZ, mX, mY, mZ)

            if result and dist < mindist then
                renderCreateFont(my_font, 'Дистанция между вами и ' ..sampGetPlayerNickname(id) .. ' составляет: '..dist, 10, k * 2, 0xFFFFFFFF)
            end
end
Поправьте кто может и шарит в этом. Прост второй раз такое делаю
 

Smeruxa

Известный
1,297
681
Lua:
for k, v in pairs(getAllChars()) do
            local mindist = 390

            result, id = sampGetPlayerIdByCharHandle(v)
            pX, pY, pZ = getCharCoordinates(v)
            mX, mY, mZ = getCharCoordinates(PLAYER_PED)

            dist = getDistanceBetweenCoords3d(pX, pY, pZ, mX, mY, mZ)

            if result then
                renderCreateFont(my_font, 'Дистанция между вами и ' ..sampGetPlayerNickname(id) .. ' составляет: '..dist, 10, k * 2, 0xFFFFFFFF)
            end
        end
Поправьте кто может и шарит в этом. Прост второй раз такое делаю
Lua:
for k,v in ipairs(getAllChars()) do
    local myPos = {getCharCoordinates(playerPed)}
    local pPos = {getCharCoordinates(v)}
    local result, id = sampGetPlayerIdByCharHandle(v)
    if result then
        local dist = getDistanceBetweenCoords3d(myPos[1], myPos[2], myPos[3], pPos[1], pPos[2], pPos[3])
        sampAddChatMessage("Дистанция между "..id.." и вами - "..dist)
    end
end
 
  • Нравится
Реакции: Sanchez.

Legion13

Участник
42
4
unknown.png




help me!
 

Loocking

Известный
1,372
468
Как же сложно
Lua:
if isCharInAnyCar(playerPed) then

end
а куда его ставить?(
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("" .. tag, main_color)
      while true do
      wait(0)

    if isKeyJustPressed(VK_L) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/lock") end

    if isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/key") end

    if isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/phone") end
       
        if isKeyJustPressed(VK_X) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/style") end
   

    if isKeyJustPressed(VK_Q) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/anims 5")  
    wait(15)
    setVirtualKeyDown(VK_RETURN, true)
    wait(0)
    setVirtualKeyDown(VK_RETURN, false)
end
end
Помогите, в луа не шарю ;(
 

Smeruxa

Известный
1,297
681
а куда его ставить?(
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("" .. tag, main_color)
      while true do
      wait(0)

    if isKeyJustPressed(VK_L) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/lock") end

    if isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/key") end

    if isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/phone") end
      
        if isKeyJustPressed(VK_X) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/style") end
  

    if isKeyJustPressed(VK_Q) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/anims 5") 
    wait(15)
    setVirtualKeyDown(VK_RETURN, true)
    wait(0)
    setVirtualKeyDown(VK_RETURN, false)
end
end
Помогите, в луа не шарю ;(
о бля, сэр, идите н
Lua:
function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
      while not isSampAvailable() do wait(100) end
      sampAddChatMessage("" .. tag, main_color)
      while true do
      wait(0)
if isCharInAnyCar(playerPed) then
    if isKeyJustPressed(VK_L) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/lock") end

    if isKeyJustPressed(VK_K) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/key") end

    if isKeyJustPressed(VK_P) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/phone") end
      
        if isKeyJustPressed(VK_X) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/style") end
  

    if isKeyJustPressed(VK_Q) and not sampIsChatInputActive() and not sampIsDialogActive() and not isPauseMenuActive() and not isSampfuncsConsoleActive() then sampSendChat("/anims 5") 
    wait(15)
    setVirtualKeyDown(VK_RETURN, true)
    wait(0)
    setVirtualKeyDown(VK_RETURN, false)
end
end
end
 
  • Ха-ха
Реакции: Loocking