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

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,778
11,238
KFR.lua:78: 'end' expected (to close 'function' at line 53) near '<eof>'
еще 1 end добавь

1612273629006.png
 

P3rsik

Активный
213
32
s:
script_name("KFR")
script_author("Sevix")
script_version("0.1")

require ("lib.moonloader")
local memory = require ("memory")
local ev = require ("lib.samp.events")
local inicfg = require ('inicfg')
local imgui = require ("imgui")

kfr_menu = imgui.ImBool(false)

local ini = inicfg.load({
    Main =
    {
        nobat = false,
        longhpbar = false,
        rpkrava = false
    }
}, '..\\config\\[KFR menu] settings.ini')

--imgui
nobat = imgui.ImBool(ini.Main.nobat)
longhpbar = imgui.ImBool(ini.Main.longhpbar)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('kfr', function() kfr_menu.v = not kfr_menu.v end)
    while true do
        wait(0)
        imgui.Process = kfr_menu.v
        checkbox()
    end
end


function imgui.OnDrawFrame()
    if kfr_menu.v then
        imgui.Begin('KFR MENU 0.1', kfr_menu)
        imgui.Checkbox('NoBat', nobat)
        imgui.Checkbox('160hp bar', longhpbar)
        imgui.Checkbox('RpKrava', rpkrava)
    end
    imgui.End()
end

function checkbox()

-- hpbar  
    if longhpbar.v then
        memory.setfloat(0xB793E0, 910.4)
    else
        memory.setfloat(0xB793E0, 569.0)
    end

-- nobat  
    if nobat.v then
        if hasCharGotWeapon(PLAYER_PED, 5) then
            removeWeaponFromChar(PLAYER_PED, 5)
        end
    end
   
-- rpkrava
function ev.onServerMessage(color,text)
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("/")
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("s")
        end
    end
end

[15:49:35.768491] (error) KFR.lua: C:\sborkafull\moonloader\KFR.lua:78: 'end' expected (to close 'function' at line 53) near '<eof>'
[15:49:35.768491] (error) KFR.lua: Script died due to an error. (2229F03C)
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,778
11,238
s:
script_name("KFR")
script_author("Sevix")
script_version("0.1")

require ("lib.moonloader")
local memory = require ("memory")
local ev = require ("lib.samp.events")
local inicfg = require ('inicfg')
local imgui = require ("imgui")

kfr_menu = imgui.ImBool(false)

local ini = inicfg.load({
    Main =
    {
        nobat = false,
        longhpbar = false,
        rpkrava = false
    }
}, '..\\config\\[KFR menu] settings.ini')

--imgui
nobat = imgui.ImBool(ini.Main.nobat)
longhpbar = imgui.ImBool(ini.Main.longhpbar)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('kfr', function() kfr_menu.v = not kfr_menu.v end)
    while true do
        wait(0)
        imgui.Process = kfr_menu.v
        checkbox()
    end
end


function imgui.OnDrawFrame()
    if kfr_menu.v then
        imgui.Begin('KFR MENU 0.1', kfr_menu)
        imgui.Checkbox('NoBat', nobat)
        imgui.Checkbox('160hp bar', longhpbar)
        imgui.Checkbox('RpKrava', rpkrava)
    end
    imgui.End()
end

function checkbox()

-- hpbar
    if longhpbar.v then
        memory.setfloat(0xB793E0, 910.4)
    else
        memory.setfloat(0xB793E0, 569.0)
    end

-- nobat
    if nobat.v then
        if hasCharGotWeapon(PLAYER_PED, 5) then
            removeWeaponFromChar(PLAYER_PED, 5)
        end
    end
 
-- rpkrava
function ev.onServerMessage(color,text)
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("/")
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("s")
        end
    end
end

[15:49:35.768491] (error) KFR.lua: C:\sborkafull\moonloader\KFR.lua:78: 'end' expected (to close 'function' at line 53) near '<eof>'
[15:49:35.768491] (error) KFR.lua: Script died due to an error. (2229F03C)


Lua:
script_name("KFR")
script_author("Sevix")
script_version("0.1")

require ("lib.moonloader")
local memory = require ("memory")
local ev = require ("lib.samp.events")
local inicfg = require ('inicfg')
local imgui = require ("imgui")

kfr_menu = imgui.ImBool(false)

local ini = inicfg.load({
    Main =
    {
        nobat = false,
        longhpbar = false,
        rpkrava = false
    }
}, '..\\config\\[KFR menu] settings.ini')

--imgui
nobat = imgui.ImBool(ini.Main.nobat)
longhpbar = imgui.ImBool(ini.Main.longhpbar)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('kfr', function() kfr_menu.v = not kfr_menu.v end)
    while true do
        wait(0)
        imgui.Process = kfr_menu.v
        checkbox()
    end
end


function imgui.OnDrawFrame()
    if kfr_menu.v then
        imgui.Begin('KFR MENU 0.1', kfr_menu)
        imgui.Checkbox('NoBat', nobat)
        imgui.Checkbox('160hp bar', longhpbar)
        imgui.Checkbox('RpKrava', rpkrava)
    end
    imgui.End()
end

function checkbox()
-- hpbar  
    if longhpbar.v then
        memory.setfloat(0xB793E0, 910.4)
    else
        memory.setfloat(0xB793E0, 569.0)
    end
-- nobat  
    if nobat.v then
        if hasCharGotWeapon(PLAYER_PED, 5) then
            removeWeaponFromChar(PLAYER_PED, 5)
        end
    end
end

-- rpkrava
function ev.onServerMessage(color,text)
    if string.find(text, "^") and rpkrava.v then
        sampSendChat("/")
    if string.find(text, "^") and rpkrava.v then
        sampSendChat("s")
    end
end
 

CaJlaT

Овощ
Модератор
2,808
2,617
s:
script_name("KFR")
script_author("Sevix")
script_version("0.1")

require ("lib.moonloader")
local memory = require ("memory")
local ev = require ("lib.samp.events")
local inicfg = require ('inicfg')
local imgui = require ("imgui")

kfr_menu = imgui.ImBool(false)

local ini = inicfg.load({
    Main =
    {
        nobat = false,
        longhpbar = false,
        rpkrava = false
    }
}, '..\\config\\[KFR menu] settings.ini')

--imgui
nobat = imgui.ImBool(ini.Main.nobat)
longhpbar = imgui.ImBool(ini.Main.longhpbar)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('kfr', function() kfr_menu.v = not kfr_menu.v end)
    while true do
        wait(0)
        imgui.Process = kfr_menu.v
        checkbox()
    end
end


function imgui.OnDrawFrame()
    if kfr_menu.v then
        imgui.Begin('KFR MENU 0.1', kfr_menu)
        imgui.Checkbox('NoBat', nobat)
        imgui.Checkbox('160hp bar', longhpbar)
        imgui.Checkbox('RpKrava', rpkrava)
    end
    imgui.End()
end

function checkbox()

-- hpbar  
    if longhpbar.v then
        memory.setfloat(0xB793E0, 910.4)
    else
        memory.setfloat(0xB793E0, 569.0)
    end

-- nobat  
    if nobat.v then
        if hasCharGotWeapon(PLAYER_PED, 5) then
            removeWeaponFromChar(PLAYER_PED, 5)
        end
    end
   
-- rpkrava
function ev.onServerMessage(color,text)
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("/")
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("s")
        end
    end
end

[15:49:35.768491] (error) KFR.lua: C:\sborkafull\moonloader\KFR.lua:78: 'end' expected (to close 'function' at line 53) near '<eof>'
[15:49:35.768491] (error) KFR.lua: Script died due to an error. (2229F03C)
Lua:
script_name("KFR")
script_author("Sevix")
script_version("0.1")

require ("lib.moonloader")
local memory = require ("memory")
local ev = require ("lib.samp.events")
local inicfg = require ('inicfg')
local imgui = require ("imgui")

kfr_menu = imgui.ImBool(false)

local ini = inicfg.load({
    Main =
    {
        nobat = false,
        longhpbar = false,
        rpkrava = false
    }
}, '..\\config\\[KFR menu] settings.ini')

--imgui
nobat = imgui.ImBool(ini.Main.nobat)
longhpbar = imgui.ImBool(ini.Main.longhpbar)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('kfr', function() kfr_menu.v = not kfr_menu.v end)
    while true do
        wait(0)
        imgui.Process = kfr_menu.v
        checkbox()
    end
end


function imgui.OnDrawFrame()
    if kfr_menu.v then
        imgui.Begin('KFR MENU 0.1', kfr_menu)
        imgui.Checkbox('NoBat', nobat)
        imgui.Checkbox('160hp bar', longhpbar)
        imgui.Checkbox('RpKrava', rpkrava)
    end
    imgui.End()
end

function checkbox()
-- hpbar   
    if longhpbar.v then
        memory.setfloat(0xB793E0, 910.4)
    else
        memory.setfloat(0xB793E0, 569.0)
    end
-- nobat   
    if nobat.v then
        if hasCharGotWeapon(PLAYER_PED, 5) then
            removeWeaponFromChar(PLAYER_PED, 5)
        end
    end
end
-- rpkrava
function ev.onServerMessage(color,text)
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("/")
        end
        if string.find(text, "^") and rpkrava.v then
            sampSendChat("s")
        end
    end
end
 

P3rsik

Активный
213
32
Lua:
script_name("KFR")
script_author("Sevix")
script_version("0.1")

require ("lib.moonloader")
local memory = require ("memory")
local ev = require ("lib.samp.events")
local inicfg = require ('inicfg')
local imgui = require ("imgui")

kfr_menu = imgui.ImBool(false)

local ini = inicfg.load({
    Main =
    {
        nobat = false,
        longhpbar = false,
        rpkrava = false
    }
}, '..\\config\\[KFR menu] settings.ini')

--imgui
nobat = imgui.ImBool(ini.Main.nobat)
longhpbar = imgui.ImBool(ini.Main.longhpbar)

function main()
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('kfr', function() kfr_menu.v = not kfr_menu.v end)
    while true do
        wait(0)
        imgui.Process = kfr_menu.v
        checkbox()
    end
end


function imgui.OnDrawFrame()
    if kfr_menu.v then
        imgui.Begin('KFR MENU 0.1', kfr_menu)
        imgui.Checkbox('NoBat', nobat)
        imgui.Checkbox('160hp bar', longhpbar)
        imgui.Checkbox('RpKrava', rpkrava)
    end
    imgui.End()
end

function checkbox()
-- hpbar 
    if longhpbar.v then
        memory.setfloat(0xB793E0, 910.4)
    else
        memory.setfloat(0xB793E0, 569.0)
    end
-- nobat 
    if nobat.v then
        if hasCharGotWeapon(PLAYER_PED, 5) then
            removeWeaponFromChar(PLAYER_PED, 5)
        end
    end
end

-- rpkrava
function ev.onServerMessage(color,text)
    if string.find(text, "^") and rpkrava.v then
        sampSendChat("/")
    if string.find(text, "^") and rpkrava.v then
        sampSendChat("s")
    end
end
Thank you i forgot put
rpkrava = imgui.ImBool(ini.Main.rpkrava)
 

HpP

Известный
368
118
У меня есть цикл, который создает 10 кнопок:
Lua:
                        for i = 1, 10 do
                            if imgui.Button(u8'1', imgui.ImVec2(96.5, 70)) then
                                
                            end
                            imgui.SameLine()
                        end
так вот, мне надо чтобы на каждую кнопку открывалось свое ImGui окно. Как это сделать?
 

D.Makarov

Участник
146
3
Lua:
function main()
sampRegisterChatCommand('ncheck')
        ncheck = not ncheck
        if ncheck then
            sampAddChatMessage("vkl", -1)
        end
        if not ncheck then
            sampAddChatMessage("vukl", -1)
            end
        end)
        lua_thread.create(function()
        for i = 0, 999 do
   local PlayerName = sampGetPlayerNickname(i)
   if PlayerName == Argumnets then
        print("Игрок с ником "..Arguments.." найден! Его ид "..i)
    end
end
    end
помогите, не работает
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,778
11,238
Lua:
function main()
sampRegisterChatCommand('ncheck')
        ncheck = not ncheck
        if ncheck then
            sampAddChatMessage("vkl", -1)
        end
        if not ncheck then
            sampAddChatMessage("vukl", -1)
            end
        end)
        lua_thread.create(function()
        for i = 0, 999 do
   local PlayerName = sampGetPlayerNickname(i)
   if PlayerName == Argumnets then
        print("Игрок с ником "..Arguments.." найден! Его ид "..i)
    end
end
    end
помогите, не работает
что скрипт должен делать? у тебя все не правильно
 

chapo

🫡 В армии с 17.10.2023. В ЛС НЕ ОТВЕЧАЮ
Друг
8,778
11,238
ну искать игрока в табе, но что-то пошло не так
попробуй это:

Lua:
local active = false
local searching_name = ''

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('ncheck', cmd)
    while true do
        wait(0)
        if active then
            for i = 0, sampGetMaxPlayerId(false) do
                local name = sampGetPlayerNickname(i)
                if name == searching_name then
                    print("Игрок с ником "..searching_name.." найден! Его ид "..i)
                end
            end
        end
    end
end


function cmd(arg)
    if active then
        active = false
        sampAddChatMessage('Выключено', -1)
    else
        searching_name = arg
        active = true
        sampAddChatMessage('Включено', -1)
    end
end
 

D.Makarov

Участник
146
3
попробуй это:

Lua:
local active = false
local searching_name = ''

function main()
    while not isSampAvailable() do wait(0) end
    sampRegisterChatCommand('ncheck', cmd)
    while true do
        wait(0)
        if active then
            for i = 0, sampGetMaxPlayerId(false) do
                local name = sampGetPlayerNickname(i)
                if name == searching_name then
                    print("Игрок с ником "..searching_name.." найден! Его ид "..i)
                end
            end
        end
    end
end


function cmd(arg)
    if active then
        active = false
        sampAddChatMessage('Выключено', -1)
    else
        searching_name = arg
        active = true
        sampAddChatMessage('Включено', -1)
    end
end
не работает