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

EclipsedFlow

Известный
Проверенный
1,040
464
Она возвращает x2, y2, z2 или все 6 значений?
подскажите пожайлуста

Код:
function getVelocity(x, y, z, x1, y1, z1, speed)
    local x2, y2, z2 = x1 - x, y1 - y, z1 - z
    local dist = math.sqrt(math.pow(x1 - x, 2.0) + math.pow(y1 - y, 2.0) + math.pow(z1 - z, 2.0))
    return x2 / dist * speed, y2 / dist * speed, z2 / dist * speed
end
 

Мурпху

Активный
211
39
Она возвращает x2, y2, z2 или все 6 значений?
подскажите пожайлуста

Код:
function getVelocity(x, y, z, x1, y1, z1, speed)
    local x2, y2, z2 = x1 - x, y1 - y, z1 - z
    local dist = math.sqrt(math.pow(x1 - x, 2.0) + math.pow(y1 - y, 2.0) + math.pow(z1 - z, 2.0))
    return x2 / dist * speed, y2 / dist * speed, z2 / dist * speed
end
x2,y2,z2 вроде
 

earthlord

Известный
135
34
изображение_2020-12-09_164028.png

можно как-нибудь говно это хукнуть? onDisplayGameText молчит

в павно это функция GameTextForPlayer
 
Последнее редактирование:

donaks.

Активный
101
67
Посмотреть вложение 78733
можно как-нибудь говно это хукнуть? onDisplayGameText молчит
Скорее всего текстдрав. Можешь вот этим скриптом воспользоваться, там вводишь showtdid в консоль сампфункса и показываются id текстдравов на экране. Ну или же onShowTextDraw

Lua:
function main() --main function must be in every script
    if not isSampfuncsLoaded() or not isSampLoaded() then return end --if no sampfuncs and samp loaded to game, close (or not lol)
    while not isSampAvailable() do wait(100) end --waiting for samp loaded
    local font = renderCreateFont("Arial", 8, 5) --creating font
    sampfuncsRegisterConsoleCommand("deletetd", del)    --registering command to sampfuncs console, this will call delete function
    sampfuncsRegisterConsoleCommand("showtdid", show)   --registering command to sampfuncs console, this will call function that shows textdraw id's
    sampfuncsRegisterConsoleCommand("ttext", function(id)
        sampfuncsLog(sampTextdrawGetString(id))
    end)   --registering command to sampfuncs console, this will call function that shows textdraw id's
    while true do --inf loop
    wait(0) --this shit is important
        if toggle then --params that not declared has a nil value that same as false
            for a = 0, 2304    do --cycle trough all textdeaw id
                if sampTextdrawIsExists(a) then --if textdeaw exists then
                    x, y = sampTextdrawGetPos(a) --we get it's position. value returns in game coords
                    x1, y1 = convertGameScreenCoordsToWindowScreenCoords(x, y) --so we convert it to screen cuz render needs screen coords
                    renderFontDrawText(font, a, x1, y1, 0xFFBEBEBE) --and then we draw it's id on textdeaw position
                end
            end
        end
    end
end

--functions can be declared at any part of code unlike it usually works in lua

function del(n) --this function simly delete textdeaw with a number that we give with command
sampTextdrawDelete(n)
end

function show() --this function sets toggle param from false to true and vise versa
toggle = not toggle
end
 

earthlord

Известный
135
34
Скорее всего текстдрав. Можешь вот этим скриптом воспользоваться, там вводишь showtdid в консоль сампфункса и показываются id текстдравов на экране. Ну или же onShowTextDraw

Lua:
function main() --main function must be in every script
    if not isSampfuncsLoaded() or not isSampLoaded() then return end --if no sampfuncs and samp loaded to game, close (or not lol)
    while not isSampAvailable() do wait(100) end --waiting for samp loaded
    local font = renderCreateFont("Arial", 8, 5) --creating font
    sampfuncsRegisterConsoleCommand("deletetd", del)    --registering command to sampfuncs console, this will call delete function
    sampfuncsRegisterConsoleCommand("showtdid", show)   --registering command to sampfuncs console, this will call function that shows textdraw id's
    sampfuncsRegisterConsoleCommand("ttext", function(id)
        sampfuncsLog(sampTextdrawGetString(id))
    end)   --registering command to sampfuncs console, this will call function that shows textdraw id's
    while true do --inf loop
    wait(0) --this shit is important
        if toggle then --params that not declared has a nil value that same as false
            for a = 0, 2304    do --cycle trough all textdeaw id
                if sampTextdrawIsExists(a) then --if textdeaw exists then
                    x, y = sampTextdrawGetPos(a) --we get it's position. value returns in game coords
                    x1, y1 = convertGameScreenCoordsToWindowScreenCoords(x, y) --so we convert it to screen cuz render needs screen coords
                    renderFontDrawText(font, a, x1, y1, 0xFFBEBEBE) --and then we draw it's id on textdeaw position
                end
            end
        end
    end
end

--functions can be declared at any part of code unlike it usually works in lua

function del(n) --this function simly delete textdeaw with a number that we give with command
sampTextdrawDelete(n)
end

function show() --this function sets toggle param from false to true and vise versa
toggle = not toggle
end
не текстдрав. актуально.
Посмотреть вложение 78733
можно как-нибудь говно это хукнуть? onDisplayGameText молчит
 
Последнее редактирование:

thedqrkway

Участник
247
11
Кинь фулл код, это может быть в другом месте
Lua:
require "lib.moonloader"
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local tag = "[My first imgui]:"
local label = 0
local main_color = 0xFFA500
local main_color_text = "{FFA500}"
local ic_chat = 0x34C924
local ic_chat_text = "{34C924}"
local white_color = "{FFFFFF}"

local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

local checked_radio =imgui.ImInt(1)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand('imgui', cmd_imgui)

_, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
nick = sampGetPlayerNickname(id)

imgui.Process = false



while true do
    wait(0)

    if main_window_state.v == false then
        imgui.Process = false
    end

    if isKeyJustPressed(VK_F3) then
        sampAddChatMessage("Вы нажали клавишу {FFFFFF}F3. " .. main_color_text .. "Ваш ник: {FFFFFF}" .. nick .. ", " .. main_color_text .. "Ваш ID: {FFFFFF}" .. id, main_color)
    end


  end
end

function cmd_imgui(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    imgui.Begin(u8"Отправлялка", main_window_state)
    imgui.InputText(u8'Впишите сюда ваше сообщение.', text_buffer)
    imgui.Text(u8'Отправить сообщение ' .. text_buffer.v .. '?')
    if imgui.Button(u8'Отправить') then
        sampSendChat(u8:decode(text_buffer.v))
    end
    if imgui.Button(u8'Вывести сообщение "' .. text_buffer.v .. u8'" визуально ?') then
   sampAddChatMessage(nick .. ' сказал: ' .. u8:decode(text_buffer.v), ic_chat)
end
imgui.RadioButton("IC", checked_radio, 2)
imgui.RadioButton("OOC", checked_radio, 3)
imgui.RadioButton("ME", checked_radio, 4)
        end
                if imgui.Button("button1") and checked_radio.v == 2 then
                    sampAddChatMessage('qq', main_color)
                elseif checked_radio.v == 3 then
                    sampAddChatMessage('qqq', main_color)
                elseif checked_radio.v == 4 then
                    sampAddChatMessage('qqqq', main_color)
                end
    imgui.End()
end
 

kizn

О КУ)))
Всефорумный модератор
2,405
2,060
Lua:
require "lib.moonloader"
local keys = require "vkeys"
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local tag = "[My first imgui]:"
local label = 0
local main_color = 0xFFA500
local main_color_text = "{FFA500}"
local ic_chat = 0x34C924
local ic_chat_text = "{34C924}"
local white_color = "{FFFFFF}"

local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

local checked_radio =imgui.ImInt(1)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end

    sampRegisterChatCommand('imgui', cmd_imgui)

_, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
nick = sampGetPlayerNickname(id)

imgui.Process = false



while true do
    wait(0)

    if main_window_state.v == false then
        imgui.Process = false
    end

    if isKeyJustPressed(VK_F3) then
        sampAddChatMessage("Вы нажали клавишу {FFFFFF}F3. " .. main_color_text .. "Ваш ник: {FFFFFF}" .. nick .. ", " .. main_color_text .. "Ваш ID: {FFFFFF}" .. id, main_color)
    end


  end
end

function cmd_imgui(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    imgui.Begin(u8"Отправлялка", main_window_state)
    imgui.InputText(u8'Впишите сюда ваше сообщение.', text_buffer)
    imgui.Text(u8'Отправить сообщение ' .. text_buffer.v .. '?')
    if imgui.Button(u8'Отправить') then
        sampSendChat(u8:decode(text_buffer.v))
    end
    if imgui.Button(u8'Вывести сообщение "' .. text_buffer.v .. u8'" визуально ?') then
   sampAddChatMessage(nick .. ' сказал: ' .. u8:decode(text_buffer.v), ic_chat)
end
imgui.RadioButton("IC", checked_radio, 2)
imgui.RadioButton("OOC", checked_radio, 3)
imgui.RadioButton("ME", checked_radio, 4)
        end
                if imgui.Button("button1") and checked_radio.v == 2 then
                    sampAddChatMessage('qq', main_color)
                elseif checked_radio.v == 3 then
                    sampAddChatMessage('qqq', main_color)
                elseif checked_radio.v == 4 then
                    sampAddChatMessage('qqqq', main_color)
                end
    imgui.End()
end
убери энд на 67 строке
 
  • Нравится
Реакции: thedqrkway

Мурпху

Активный
211
39
Как можно сделать отгрузку скрипта с полностью его удалением из папки?
 

thedqrkway

Участник
247
11
Lua:
                if imgui.Button("button1") and checked_radio.v == 2 then
                    sampAddChatMessage('qq', main_color)
                elseif checked_radio.v == 3 then
                    sampAddChatMessage('qqq', main_color)
                elseif checked_radio.v == 4 then
                    sampAddChatMessage('qqqq', main_color)
почему флудит в чат, когда выбрана 3 и 4 радио кнопка? скорее всего понимаю почему, но я хочу сделать чтобы действие происходило когда активна одна из трех радио кнопок, и когда нажата обычная, помогите, как сделать так?
 

earthlord

Известный
135
34