Вопросы по 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,044
490
Почему не вносит в переменную?

Lua:
Строка - [1245.1967773438]:[-1140.326171875]:[23.372161865234]

local posX, posY, posZ = value:match('[(.*)]:[(.*)]:[(.*)]')
 

chapo

tg/inst: @moujeek
Всефорумный модератор
9,233
12,659
Почему громкость звука, радио и некоторые другие настройки не меняются?
Lua:
local game_settings = {
    --SCREEN
    {
        brightness = imgui.ImInt(50), -- min 10, max 100
        map_desc = imgui.ImBool(false),
        radar_mode = imgui.ImInt(0), --[[ 0 - off, 1 - map and marks, 2 - marks ]]
        show_hud = imgui.ImBool(false),
        subtitle = imgui.ImBool(false),
        save_photos = imgui.ImBool(false),

        --ADVANCED
        distance = imgui.ImInt(50),
        framelimit = imgui.ImBool(false),
        widescreen = imgui.ImBool(false),
        quality = imgui.ImInt(0), -- max - 4
        aa = imgui.ImInt(0), -- 0 - 3
    },
    --SOUND
    {
        radio = imgui.ImInt(0),
        sounds = imgui.ImInt(0),
        car = imgui.ImBool(false),
        autoradio = imgui.ImBool(false),

    },
}


function getSoundSettings()
    game_settings[2].radio.v = memory.getint8(0xBA6798, false)
    game_settings[2].sounds.v = memory.getint8(0xBA6797 , false)
end

function applySoundSettings()
    memory.setint8(0xBA6798, game_settings[2].radio.v)
    memory.setint8(0xBA6797, game_settings[2].sounds.v)
end

function applyScreenSettings()
    memory.setint8(0xBA6784, game_settings[1].brightness.v)
    memory.setint8(0xBA6792, boolToInt(game_settings[1].map_desc.v))
    memory.setint8(0xBA676C, game_settings[1].radar_mode.v)
    memory.setint8(0xBA6769, boolToInt(game_settings[1].show_hud.v))
    memory.setint8(0xBA678C, boolToInt(game_settings[1].subtitle.v))
    memory.setint8(0xBA6830, boolToInt(game_settings[1].save_photos.v))
    memory.setint8(0xBA6788, game_settings[1].distance.v)
    memory.setint8(0xBA6794, boolToInt(game_settings[1].framelimit.v))
    memory.setint8(0xBA6793, boolToInt(game_settings[1].widescreen.v))
    memory.setint8(0xA9AE54, game_settings[1].quality.v)
    memory.setint8(0xBA6814, game_settings[1].aa.v)
end

function getScreenSettings()
    game_settings[1].brightness.v = memory.getint8(0xBA6784, false)
    game_settings[1].map_desc.v = intToBool(memory.getint8(0xBA6792, false)) -- bool
    game_settings[1].radar_mode.v = memory.getint8(0xBA676C, false)
    game_settings[1].show_hud.v = intToBool(memory.getint8(0xBA6769, false)) -- bool
    game_settings[1].subtitle.v = intToBool(memory.getint8(0xBA678C, false)) -- bool
    game_settings[1].save_photos.v = intToBool(memory.getint8(0xBA6830, false)) -- bool
    game_settings[1].distance.v = memory.getint8(0xBA6788, false)
    game_settings[1].framelimit.v = intToBool(memory.getint8(0xBA6794, false)) -- bool
    game_settings[1].widescreen.v = intToBool(memory.getint8(0xBA6793, false)) -- bool
    game_settings[1].quality.v = memory.getint8(0xA9AE54, false)
    game_settings[1].aa.v = memory.getint8(0xBA6814, false)
end

function intToBool(int)
    if int == 0 then
        return false
    elseif int == 1 then
        return true
    end
end

function boolToInt(bool)
    if bool then
        return 1
    else
        return 0
    end
end




if settings_page == 1 then
                imgui.SetCursorPosY(resY / 5)
                imgui.PushFont(font90)
                imgui.CenterTextColoredRGB(text[lang].settings)
                imgui.PopFont()
                imgui.PushFont(font45)
                imgui.CenterTextColoredRGB(text[lang].gs.screen)
                imgui.PopFont()

                
                imgui.PushItemWidth(button.x)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Brightness', game_settings[1].brightness, 0, 100) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Map description', game_settings[1].map_desc) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Combo('Radar mode', game_settings[1].radar_mode, {'Maps & Blips', 'Blips', 'off'}, -1) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Widescreen', game_settings[1].widescreen) then applyScreenSettings() end


                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Show HUD', game_settings[1].show_hud) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Subtitles', game_settings[1].subtitle) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Save photos', game_settings[1].save_photos) then applyScreenSettings() end

                imgui.Separator()

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Combo('Effects quality', game_settings[1].quality, {'Low', 'Medium', 'High', u8'АХУЕННО'}, -1) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Anti-Aliasing', game_settings[1].aa, 1, 4) then applyScreenSettings() end
                imgui.PopItemWidth()

                

                imgui.SetCursorPosY(resY / 2 + 200)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Button(text[lang].goback, imgui.ImVec2(button.x, button.y)) then main_page = 2 settings_page = 0 end
            elseif settings_page == 2 then
                imgui.SetCursorPosY(resY / 5)
                imgui.PushFont(font90)
                imgui.CenterTextColoredRGB(text[lang].settings)
                imgui.PopFont()
                imgui.PushFont(font45)
                imgui.CenterTextColoredRGB(text[lang].gs.sound)
                imgui.PopFont()

                
                imgui.PushItemWidth(button.x)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Radio', game_settings[2].radio, 10, 100) then applySoundSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Sounds', game_settings[2].sounds, 10, 100) then applySoundSettings() end

                --imgui.SetCursorPosX(buttonPos.x)
                --imgui.Checkbox('Car bass', game_settings[2].car)

                --imgui.SetCursorPosX(buttonPos.x)
                --imgui.Checkbox('Auto radio', game_settings[2].autoradio)

                imgui.PopItemWidth()

                
                imgui.SetCursorPosY(resY / 2 + 200)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Button(text[lang].goback, imgui.ImVec2(button.x, button.y)) then main_page = 2 settings_page = 0 end
                
            end
 

Gorskin

t.me/gorskintgk
Проверенный
1,421
1,267
Почему громкость звука, радио и некоторые другие настройки не меняются?
Lua:
local game_settings = {
    --SCREEN
    {
        brightness = imgui.ImInt(50), -- min 10, max 100
        map_desc = imgui.ImBool(false),
        radar_mode = imgui.ImInt(0), --[[ 0 - off, 1 - map and marks, 2 - marks ]]
        show_hud = imgui.ImBool(false),
        subtitle = imgui.ImBool(false),
        save_photos = imgui.ImBool(false),

        --ADVANCED
        distance = imgui.ImInt(50),
        framelimit = imgui.ImBool(false),
        widescreen = imgui.ImBool(false),
        quality = imgui.ImInt(0), -- max - 4
        aa = imgui.ImInt(0), -- 0 - 3
    },
    --SOUND
    {
        radio = imgui.ImInt(0),
        sounds = imgui.ImInt(0),
        car = imgui.ImBool(false),
        autoradio = imgui.ImBool(false),

    },
}


function getSoundSettings()
    game_settings[2].radio.v = memory.getint8(0xBA6798, false)
    game_settings[2].sounds.v = memory.getint8(0xBA6797 , false)
end

function applySoundSettings()
    memory.setint8(0xBA6798, game_settings[2].radio.v)
    memory.setint8(0xBA6797, game_settings[2].sounds.v)
end

function applyScreenSettings()
    memory.setint8(0xBA6784, game_settings[1].brightness.v)
    memory.setint8(0xBA6792, boolToInt(game_settings[1].map_desc.v))
    memory.setint8(0xBA676C, game_settings[1].radar_mode.v)
    memory.setint8(0xBA6769, boolToInt(game_settings[1].show_hud.v))
    memory.setint8(0xBA678C, boolToInt(game_settings[1].subtitle.v))
    memory.setint8(0xBA6830, boolToInt(game_settings[1].save_photos.v))
    memory.setint8(0xBA6788, game_settings[1].distance.v)
    memory.setint8(0xBA6794, boolToInt(game_settings[1].framelimit.v))
    memory.setint8(0xBA6793, boolToInt(game_settings[1].widescreen.v))
    memory.setint8(0xA9AE54, game_settings[1].quality.v)
    memory.setint8(0xBA6814, game_settings[1].aa.v)
end

function getScreenSettings()
    game_settings[1].brightness.v = memory.getint8(0xBA6784, false)
    game_settings[1].map_desc.v = intToBool(memory.getint8(0xBA6792, false)) -- bool
    game_settings[1].radar_mode.v = memory.getint8(0xBA676C, false)
    game_settings[1].show_hud.v = intToBool(memory.getint8(0xBA6769, false)) -- bool
    game_settings[1].subtitle.v = intToBool(memory.getint8(0xBA678C, false)) -- bool
    game_settings[1].save_photos.v = intToBool(memory.getint8(0xBA6830, false)) -- bool
    game_settings[1].distance.v = memory.getint8(0xBA6788, false)
    game_settings[1].framelimit.v = intToBool(memory.getint8(0xBA6794, false)) -- bool
    game_settings[1].widescreen.v = intToBool(memory.getint8(0xBA6793, false)) -- bool
    game_settings[1].quality.v = memory.getint8(0xA9AE54, false)
    game_settings[1].aa.v = memory.getint8(0xBA6814, false)
end

function intToBool(int)
    if int == 0 then
        return false
    elseif int == 1 then
        return true
    end
end

function boolToInt(bool)
    if bool then
        return 1
    else
        return 0
    end
end




if settings_page == 1 then
                imgui.SetCursorPosY(resY / 5)
                imgui.PushFont(font90)
                imgui.CenterTextColoredRGB(text[lang].settings)
                imgui.PopFont()
                imgui.PushFont(font45)
                imgui.CenterTextColoredRGB(text[lang].gs.screen)
                imgui.PopFont()

               
                imgui.PushItemWidth(button.x)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Brightness', game_settings[1].brightness, 0, 100) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Map description', game_settings[1].map_desc) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Combo('Radar mode', game_settings[1].radar_mode, {'Maps & Blips', 'Blips', 'off'}, -1) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Widescreen', game_settings[1].widescreen) then applyScreenSettings() end


                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Show HUD', game_settings[1].show_hud) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Subtitles', game_settings[1].subtitle) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Checkbox('Save photos', game_settings[1].save_photos) then applyScreenSettings() end

                imgui.Separator()

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Combo('Effects quality', game_settings[1].quality, {'Low', 'Medium', 'High', u8'АХУЕННО'}, -1) then applyScreenSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Anti-Aliasing', game_settings[1].aa, 1, 4) then applyScreenSettings() end
                imgui.PopItemWidth()

               

                imgui.SetCursorPosY(resY / 2 + 200)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Button(text[lang].goback, imgui.ImVec2(button.x, button.y)) then main_page = 2 settings_page = 0 end
            elseif settings_page == 2 then
                imgui.SetCursorPosY(resY / 5)
                imgui.PushFont(font90)
                imgui.CenterTextColoredRGB(text[lang].settings)
                imgui.PopFont()
                imgui.PushFont(font45)
                imgui.CenterTextColoredRGB(text[lang].gs.sound)
                imgui.PopFont()

               
                imgui.PushItemWidth(button.x)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Radio', game_settings[2].radio, 10, 100) then applySoundSettings() end

                imgui.SetCursorPosX(buttonPos.x)
                if imgui.SliderInt('Sounds', game_settings[2].sounds, 10, 100) then applySoundSettings() end

                --imgui.SetCursorPosX(buttonPos.x)
                --imgui.Checkbox('Car bass', game_settings[2].car)

                --imgui.SetCursorPosX(buttonPos.x)
                --imgui.Checkbox('Auto radio', game_settings[2].autoradio)

                imgui.PopItemWidth()

               
                imgui.SetCursorPosY(resY / 2 + 200)
                imgui.SetCursorPosX(buttonPos.x)
                if imgui.Button(text[lang].goback, imgui.ImVec2(button.x, button.y)) then main_page = 2 settings_page = 0 end
               
            end
Наверное нужно использовать
memory.setfloat
 

#SameLine

Известный
422
39
Как сделать что бы в скрипте курсор был как в сампе, а не курсор с рабочего стола
 

MAHEKEH

Известный
2,002
503
как правильно задать чтение с ini ? т.е по плану он должен считывать задержки с иника, в идеале в реальном времени

Код:
require "lib.moonloader"

local inicfg = require 'inicfg'

local settingsFile = 'WOW.ini'
local INI = inicfg.load({
        TEST =
            {
                DELAY = 500,
                DELAY_DELAY = 1000
            }
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(mainIni, settingsFile) end

local wow = false

function main()
sampRegisterChatCommand('asd', function()
wow = not wow end)

while true do
wait(DELAY)
if wow then sampAddChatMessage('{ffff00}Hi! Задержка: ' ..DELAY, -1)
wait(DELAY_DELAY)
sampAddChatMessage('{ff0000}Bie! Задержка: ' .. DELAY_DELAY, -1)
end
end
end
 

Gorskin

t.me/gorskintgk
Проверенный
1,421
1,267
как правильно задать чтение с ini ? т.е по плану он должен считывать задержки с иника, в идеале в реальном времени

Код:
require "lib.moonloader"

local inicfg = require 'inicfg'

local settingsFile = 'WOW.ini'
local INI = inicfg.load({
        TEST =
            {
                DELAY = 500,
                DELAY_DELAY = 1000
            }
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(mainIni, settingsFile) end

local wow = false

function main()
sampRegisterChatCommand('asd', function()
wow = not wow end)

while true do
wait(DELAY)
if wow then sampAddChatMessage('{ffff00}Hi! Задержка: ' ..DELAY, -1)
wait(DELAY_DELAY)
sampAddChatMessage('{ff0000}Bie! Задержка: ' .. DELAY_DELAY, -1)
end
end
end
Поменяй DELAY и т.д на INI.TEST.DELAY и если DELAY это число то лучше написать например wait(tonumber(INI.TEST.DELAY))
 
  • Нравится
Реакции: MAHEKEH

MAHEKEH

Известный
2,002
503
Поменяй DELAY и т.д на INI.TEST.DELAY и если DELAY это число то лучше написать например wait(tonumber(INI.TEST.DELAY))

да, я пробовал так, хз, где то чето проглядел

Код:
require "lib.moonloader"
local inicfg = require 'inicfg'

local settingsFile = 'NULL.ini'
local cfg = inicfg.load({
        Settings =
            {
                One = 555,
                Two = 1111
            }
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(cfg, settingsFile) end

local wow = false

function main()
sampRegisterChatCommand('asd', function()
wow = not wow end)

while true do
wait(tonumber(cfg.Settings.One))
if wow then sampAddChatMessage('{ffff00}Hi! Задержка: ' ..One, -1)
wait(tonumber(cfg.Settings.Two))
sampAddChatMessage('{ff0000}Bie! Задержка: ' .. Two, -1)
end
end
end

ни в какую
 

abnomegd

Известный
367
42
Как сделать например(хз как обьеснить)чтобы в автологине например чтобы для ника: andrey_pupkin пароль 123123 (чтобы этот пароль срабатывал только для этого ника)

lua:
require 'lib.moonloader'
local lsampev, sp = pcall(require, 'lib.samp.events')
local inicfg = require 'inicfg'

local directini = "moonloader\\config\\AdvanceConnect.ini"
local mainini = inicfg.load(nil, directini)

local parol = (mainini.config.parol)
local pinkod = (mainini.config.pinkod)
    
function main()
    repeat wait(0) until isSampAvailable()
    sampAddChatMessage("[AdvanceConnect]: {FFFFFF}Скрипт загружен.", 0x5CBCFF)
    sampRegisterChatCommand("rec", function(arg)
        if arg ~= nil then
            time = tonumber(arg)
            res = true
        end
    end)
    while true do
        wait(0)
        local chatstring = sampGetChatString(99)
        if chatstring == "Server closed the connection." or chatstring == "You are banned from this server." then
            sampDisconnectWithReason(false)
            sampAddChatMessage("Wait reconnecting...", 0xa9c4e4)
            wait(5000)
            sampSetGamestate(1)
        end

        if res and time ~= nil then
            sampDisconnectWithReason(quit)
            wait(time*1000)
            sampSetGamestate(1)
            res = false
        elseif res and time == nil then
            sampDisconnectWithReason(quit)
            wait(15500)
            sampSetGamestate(1)
            res = false
        end
    end
end

function sp.onShowDialog(id, style, title, button1, button2, text)
    if id == 2 or id == 1 or id == 10 then
        sampSendDialogResponse(id, 1, _, parol)
        return false
    end
    if id == 199 then
        sampSendDialogResponse(id, 1, _, pinkod)
        return false
    end
end
 

Gorskin

t.me/gorskintgk
Проверенный
1,421
1,267
да, я пробовал так, хз, где то чето проглядел

Код:
require "lib.moonloader"
local inicfg = require 'inicfg'

local settingsFile = 'NULL.ini'
local cfg = inicfg.load({
        Settings =
            {
                One = 555,
                Two = 1111
            }
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(cfg, settingsFile) end

local wow = false

function main()
sampRegisterChatCommand('asd', function()
wow = not wow end)

while true do
wait(tonumber(cfg.Settings.One))
if wow then sampAddChatMessage('{ffff00}Hi! Задержка: ' ..One, -1)
wait(tonumber(cfg.Settings.Two))
sampAddChatMessage('{ff0000}Bie! Задержка: ' .. Two, -1)
end
end
end

ни в какую
У тебя в sampAddChatMessage остались one и two, допиши ini.Settings. перед ними

Разобрался вроде, стоило добавить пару переменных перед циклом
local One = (cfg.Settings.One)
local Two = (cfg.Settings.Two)
А, ну можно и так даже.