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

Double Tap Inside

Известный
Проверенный
1,899
1,246
Как сделать несколько imgui.InputText? Я сделал только 2 но ни в одном я не могу писать.

Lua:
text_buffer = imgui.ImBuffer(.....
text_buffer2 = imgui.ImBuffer(.....


imgui.InputText("## text_buffer", text_buffer)
imgui.SameLine()
imgui.InputText("## text_buffer2", text_buffer2)
 
  • Нравится
Реакции: BetDonneR

Fott

Простреленный
3,443
2,303
Привет. Помогите пожалуйста сделать так, чтобы данная функция повторялась раз в 5 секунд до того момента как я заново не пропишу команду /finv (для ее деактивации) даю 10 рублей на киви за корректный ответ
Код:
local mode = 0

function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
  sampRegisterChatCommand('finv', function()
      lua_thread.create(function()
        status = not status
        if status then
        if mode ~= 0 then mode = 0 return sampAddChatMessage('Выключен', -1) end
            for k,v in ipairs(getAllChars()) do
                local result, id = sampGetPlayerIdByCharHandle(v)
                local xM, yM, zM = getCharCoordinates(PLAYER_PED)
                local x, y, z = getCharCoordinates(v)
                if result and getDistanceBetweenCoords3d(xM, yM, zM, x, y, z) < 10 then
                    sampSendChat(string.format("/faminvite %d", id))
                    wait(1000)
                end
            end
        end
     
    end)
  end)
  while true do
    wait(0)
  end
end
Lua:
local mode = 0

function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
  sampRegisterChatCommand('finv', function() status = not status end)
  while true do
    wait(0)
    if status then
        if mode ~= 0 then mode = 0 return sampAddChatMessage('Выключен', -1) end
            for k,v in ipairs(getAllChars()) do
                local result, id = sampGetPlayerIdByCharHandle(v)
                local xM, yM, zM = getCharCoordinates(PLAYER_PED)
                local x, y, z = getCharCoordinates(v)
                if result and getDistanceBetweenCoords3d(xM, yM, zM, x, y, z) < 10 then
                    sampSendChat(string.format("/faminvite %d", id))
                    wait(5000)
                end
            end
        end
      end
   end
 

cran221

Новичок
14
2
Lua:
local mode = 0

function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
  sampRegisterChatCommand('finv', function() status = not status end)
  while true do
    wait(0)
    if status then
        if mode ~= 0 then mode = 0 return sampAddChatMessage('Выключен', -1) end
            for k,v in ipairs(getAllChars()) do
                local result, id = sampGetPlayerIdByCharHandle(v)
                local xM, yM, zM = getCharCoordinates(PLAYER_PED)
                local x, y, z = getCharCoordinates(v)
                if result and getDistanceBetweenCoords3d(xM, yM, zM, x, y, z) < 10 then
                    sampSendChat(string.format("/faminvite %d", id))
                    wait(5000)
                end
            end
        end
      end
   end
Брат как-то не так работает
 

Fott

Простреленный
3,443
2,303
Брат как-то не так работает
Это работает точно, проверил
Lua:
function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
  print('224')
  sampRegisterChatCommand('finv', finv)
  while true do
    wait(0)
    if active then
            for k,v in ipairs(getAllChars()) do
                local result, id = sampGetPlayerIdByCharHandle(v)
                local xM, yM, zM = getCharCoordinates(PLAYER_PED)
                local x, y, z = getCharCoordinates(v)
                if result and getDistanceBetweenCoords3d(xM, yM, zM, x, y, z) < 10 then
                    sampSendChat(string.format("/faminvite %d", id))
                    wait(5000)
                end
            end
        end
      end
end

function finv(arg)
    active = not active
    sampAddChatMessage(active and 'On' or 'Off', -1)
end
 

cran221

Новичок
14
2
Это работает точно, проверил
Lua:
function main()
  if not isSampLoaded() or not isSampfuncsLoaded() then return end
  while not isSampAvailable() do wait(100) end
  print('224')
  sampRegisterChatCommand('finv', finv)
  while true do
    wait(0)
    if active then
            for k,v in ipairs(getAllChars()) do
                local result, id = sampGetPlayerIdByCharHandle(v)
                local xM, yM, zM = getCharCoordinates(PLAYER_PED)
                local x, y, z = getCharCoordinates(v)
                if result and getDistanceBetweenCoords3d(xM, yM, zM, x, y, z) < 10 then
                    sampSendChat(string.format("/faminvite %d", id))
                    wait(5000)
                end
            end
        end
      end
end

function finv(arg)
    active = not active
    sampAddChatMessage(active and 'On' or 'Off', -1)
end
от души братан, давай киви
 

enyag

Известный
345
12
что не так?
Lua:
function makeScreenshot(disable) -- если передать true, интерфейс и чат будут скрыты
    if disable then displayHud(false) sampSetChatDisplayMode(0) end
    require('memory').setuint8(sampGetBase() + 0x119CBC, 1)
    if disable then displayHud(true) sampSetChatDisplayMode(2) end
end

--
makeScreenshot() end -- обычный скриншот игры
makeScreenshot(true) end -- скриншот без чата и HUD'a
Lua:
local sampev = require 'lib.samp.events'
local memory = require 'memory'

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

while true do
    wait(0)

    end
end

function makeScreenshot(disable) -- если передать true, интерфейс и чат будут скрыты
    if disable then displayHud(false) sampSetChatDisplayMode(0) end
    require('memory').setuint8(sampGetBase() + 0x119CBC, 1)
    if disable then displayHud(true) sampSetChatDisplayMode(2) end
end

--
makeScreenshot() end -- обычный скриншот игры

function sampev.onServerMessage(color, text)
    if text:find('123') then
        makeScreenshot()
    end
end
 

Fott

Простреленный
3,443
2,303
Lua:
local sampev = require 'lib.samp.events'
local memory = require 'memory'

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

while true do
    wait(0)

    end
end

function makeScreenshot(disable) -- если передать true, интерфейс и чат будут скрыты
    if disable then displayHud(false) sampSetChatDisplayMode(0) end
    require('memory').setuint8(sampGetBase() + 0x119CBC, 1)
    if disable then displayHud(true) sampSetChatDisplayMode(2) end
end

--
makeScreenshot() end -- обычный скриншот игры

function sampev.onServerMessage(color, text)
    if text:find('123') then
        makeScreenshot()
    end
end
Lua:
local sampev = require 'lib.samp.events'
local memory = require 'memory'

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

function makeScreenshot(disable) -- если передать true, интерфейс и чат будут скрыты
    if disable then displayHud(false) sampSetChatDisplayMode(0) end
    require('memory').setuint8(sampGetBase() + 0x119CBC, 1)
    if disable then displayHud(true) sampSetChatDisplayMode(2) end
end

function sampev.onServerMessage(color, text)
    if text:find('123') then
        makeScreenshot()
    end
end
 
  • Нравится
Реакции: enyag

BlackSnow

Новичок
15
1
Доброго времени суток. Вопрос такой. Как сделать автоматическое оповещение в чат при попадании игрока с конкретным скином в зону прорисовки. Чтобы оно обновлялось только при попадании в зону прорисовки, а не флудило в чат. Заранее спасибо.
 

samartinell1

Участник
98
14
Доброго времени суток. Вопрос такой. Как сделать автоматическое оповещение в чат при попадании игрока с конкретным скином в зону прорисовки. Чтобы оно обновлялось только при попадании в зону прорисовки, а не флудило в чат. Заранее спасибо.
в samp.events есть замечательная функция:
onPlayerStreamIn(playerid, team, char, pos, rot, color, style)
дальше делаешь проверку на скин игрока (в вики бластхака есть функция) через char и если совпадает - выводишь в чат
Такая же функция, только на выход из зоны стрима тоже есть:
onPlayerStreamOut(id)
 

WellShow

Известный
69
11
как добавить в этот код проверку на открытую консоль сампфункс, чтобы при открытой консоли сампфункс нажатие на кнопку t не открывало чат?

script_name('Input Helper')
script_version_number(1)
script_moonloader(020)
script_author('DonHomka')
script_description('Help to game in samp :)')

local ffi = require("ffi")
require 'lib.moonloader'
require 'lib.sampfuncs'
local mem = require "memory"
ffi.cdef[[
short GetKeyState(int nVirtKey);
bool GetKeyboardLayoutNameA(char* pwszKLID);
int GetLocaleInfoA(int Locale, int LCType, char* lpLCData, int cchData);
]]
local BuffSize = 32
local KeyboardLayoutName = ffi.new("char[?]", BuffSize)
local LocalInfo = ffi.new("char[?]", BuffSize)
chars = {
["й"] = "q", ["ц"] = "w", ["у"] = "e", ["к"] = "r", ["е"] = "t", ["н"] = "y", ["г"] = "u", ["ш"] = "i", ["щ"] = "o", ["з"] = "p", ["х"] = "[", ["ъ"] = "]", ["ф"] = "a",
["ы"] = "s", ["в"] = "d", ["а"] = "f", ["п"] = "g", ["р"] = "h", ["о"] = "j", ["л"] = "k", ["д"] = "l", ["ж"] = ";", ["э"] = "'", ["я"] = "z", ["ч"] = "x", ["с"] = "c", ["м"] = "v",
["и"] = "b", ["т"] = "n", ["ь"] = "m", ["б"] = ",", ["ю"] = ".", ["Й"] = "Q", ["Ц"] = "W", ["У"] = "E", ["К"] = "R", ["Е"] = "T", ["Н"] = "Y", ["Г"] = "U", ["Ш"] = "I",
["Щ"] = "O", ["З"] = "P", ["Х"] = "{", ["Ъ"] = "}", ["Ф"] = "A", ["Ы"] = "S", ["В"] = "D", ["А"] = "F", ["П"] = "G", ["Р"] = "H", ["О"] = "J", ["Л"] = "K", ["Д"] = "L",
["Ж"] = ":", ["Э"] = "\"", ["Я"] = "Z", ["Ч"] = "X", ["С"] = "C", ["М"] = "V", ["И"] = "B", ["Т"] = "N", ["Ь"] = "M", ["Б"] = "<", ["Ю"] = ">"
}


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

inputHelpText = renderCreateFont("Arial", 9, FCR_BORDER + FCR_BOLD)
lua_thread.create(inputChat)
lua_thread.create(showInputHelp)

while true do
wait(0)
if(isKeyDown(VK_T) and wasKeyPressed(VK_T))then
if(not sampIsChatInputActive() and not sampIsDialogActive())then
sampSetChatInputEnabled(true)
end
end
end
wait(-1)
end

function showInputHelp()
while true do
local chat = sampIsChatInputActive()
if chat == true then
local in1 = sampGetInputInfoPtr()
local in1 = getStructElement(in1, 0x8, 4)
local in2 = getStructElement(in1, 0x8, 4)
local in3 = getStructElement(in1, 0xC, 4)
fib = in3 + 41
fib2 = in2 + 10
local _, pID = sampGetPlayerIdByCharHandle(playerPed)
local name = sampGetPlayerNickname(pID)
local score = sampGetPlayerScore(pID)
local color = sampGetPlayerColor(pID)
local capsState = ffi.C.GetKeyState(20)
local success = ffi.C.GetKeyboardLayoutNameA(KeyboardLayoutName)
local errorCode = ffi.C.GetLocaleInfoA(tonumber(ffi.string(KeyboardLayoutName), 16), 0x00000002, LocalInfo, BuffSize)
local localName = ffi.string(LocalInfo)
local text = string.format(
"%s :: {%0.6x}%s[%d] {ffffff}:: Капс: %s {FFFFFF}:: Язык: {ffeeaa}%s{ffffff}",
os.date("%H:%M:%S"), bit.band(color,0xffffff), name, pID, getStrByState(capsState), string.match(localName, "([^%(]*)")
)
renderFontDrawText(inputHelpText, text, fib2, fib, 0xD7FFFFFF)
end
wait(0)
end
end
function getStrByState(keyState)
if keyState == 0 then
return "{ffeeaa}Выкл{ffffff}"
end
return "{9EC73D}Вкл{ffffff}"
end
function translite(text)
for k, v in pairs(chars) do
text = string.gsub(text, k, v)
end
return text
end

function inputChat()
while true do
if(sampIsChatInputActive())then
local getInput = sampGetChatInputText()
if(oldText ~= getInput and #getInput > 0)then
local firstChar = string.sub(getInput, 1, 1)
if(firstChar == "." or firstChar == "/")then
local cmd, text = string.match(getInput, "^([^ ]+)(.*)")
local nText = "/" .. translite(string.sub(cmd, 2)) .. text
local chatInfoPtr = sampGetInputInfoPtr()
local chatBoxInfo = getStructElement(chatInfoPtr, 0x8, 4)
local lastPos = mem.getint8(chatBoxInfo + 0x11E)
sampSetChatInputText(nText)
mem.setint8(chatBoxInfo + 0x11E, lastPos)
mem.setint8(chatBoxInfo + 0x119, lastPos)
oldText = nText
end
end
end
wait(0)
end
end