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

Driht

Участник
53
2
Как сделать так чтобы например вводила в чат команду например
local ya dalbaeb = "Privet pidr"
И типо чтобы команда вводила это /ebat Privet pidr
 

qwеty

Известный
490
158
jopa:
require 'lib.moonloader'

local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local inicfg = require 'inicfg'

local window_menu = imgui.ImBool(false)
local sw, sh = getScreenResolution()

local directIni = 'moonloader/config/imguihui.ini'
local mainIni = inicfg.load({
    config = {
            func = false,
            func1 = false
        }
}, directIni)

local func = imgui.ImBool(mainIni.config.func)
local textbutton = imgui.ImBool(mainIni.config.func)

function main()
    while not isSampAvailable() do wait(100) end
        if not doesFileExist('moonloader/config/imguihui.ini') then inicfg.save(mainIni, 'imguihui.ini') end
        sampRegisterChatCommand('window', windowmenu)
        while true do
            wait(0)
        end
end

function windowmenu()
    window_menu.v = not window_menu.v
    imgui.Process = window_menu.v
end

function imgui.TextColoredRGB(text)
    local style = imgui.GetStyle()
    local colors = style.Colors
    local ImVec4 = imgui.ImVec4

    local explode_argb = function(argb)
        local a = bit.band(bit.rshift(argb, 24), 0xFF)
        local r = bit.band(bit.rshift(argb, 16), 0xFF)
        local g = bit.band(bit.rshift(argb, 8), 0xFF)
        local b = bit.band(argb, 0xFF)
        return a, r, g, b
    end

    local getcolor = function(color)
        if color:sub(1, 6):upper() == 'SSSSSS' then
            local r, g, b = colors[1].x, colors[1].y, colors[1].z
            local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
            return ImVec4(r, g, b, a / 255)
        end
        local color = type(color) == 'string' and tonumber(color, 16) or color
        if type(color) ~= 'number' then return end
        local r, g, b, a = explode_argb(color)
        return imgui.ImColor(r, g, b, a):GetVec4()
    end

    local render_text = function(text_)
        for w in text_:gmatch('[^\r\n]+') do
            local text, colors_, m = {}, {}, 1
            w = w:gsub('{(......)}', '{%1FF}')
            while w:find('{........}') do
                local n, k = w:find('{........}')
                local color = getcolor(w:sub(n + 1, k - 1))
                if color then
                    text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                    colors_[#colors_ + 1] = color
                    m = n
                end
                w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
            end
            if text[0] then
                for i = 0, #text do
                    imgui.TextColored(colors_[i] or colors[1], u8(text[i]))
                    imgui.SameLine(nil, 0)
                end
                imgui.NewLine()
            else imgui.Text(u8(w)) end
        end
    end
        render_text(text)
end

function imgui.TextButton(text, bool)
    imgui.TextColoredRGB(string.format('[    %s', bool.v and '{00ff00}ON' or '{ff0000}OFF'))
    if imgui.IsItemClicked() then bool.v = not bool.v end
    imgui.SameLine()
    imgui.Text('  ]  '..text)
    return bool.v
end

function imgui.OnDrawFrame()
        if window_menu.v then
            imgui.SetNextWindowSize(imgui.ImVec2(180, 320), imgui.Cond.FirstUseEver)
            imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.ShowCursor = true
            imgui.Begin('Window')
            if imgui.TextButton('gmcar1', func1) then
                textbutton = not textbutton
                mainIni.config.func1 = textbutton
                inicfg.save(mainIni, 'imguihui.ini')
            end
            if imgui.Checkbox('gmcar', func) then
                mainIni.config.func = func.v
                inicfg.save(mainIni, 'imguihui.ini')
            end
        else
            imgui.ShowCursor = false
        end
        imgui.End()
end

:89: attempt to index local 'bool' (a nil value)
да и вообще, хуйню ты написал.
чё за хуйня у тебя с переменной bool?
сорян, но хуйня, реально
а так спасибо, что попытался помочь.
 
Последнее редактирование:

qwеty

Известный
490
158
В чём проблема? При нажатии на imgui.TextButton в конфиг сохраняется значение true, нажимаю ещё раз и значение в конфиге должно было бы измениться на false, но оно не изменяется, а остается положительным, то есть true (после нажатия всё время возвращается true). В свою очередь, с imgui.Checkbox всё нормально работает, значения сохраняються как и должны сохраняться.
jopa:
require 'lib.moonloader'

local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8
local inicfg = require 'inicfg'

local window_menu = imgui.ImBool(false)
local sw, sh = getScreenResolution()

local directIni = 'moonloader/config/imguihui.ini'
local mainIni = inicfg.load({
    config = {
            func = false,
            func1 = false
        }
}, directIni)

local func = imgui.ImBool(mainIni.config.func)
local func1 = imgui.ImBool(mainIni.config.func1)

function main()
    while not isSampAvailable() do wait(100) end
        if not doesFileExist('moonloader/config/imguihui.ini') then inicfg.save(mainIni, 'imguihui.ini') end
        sampRegisterChatCommand('window', windowmenu)
        while true do
            wait(0)
        end
end

function windowmenu()
    window_menu.v = not window_menu.v
    imgui.Process = window_menu.v
end

function imgui.TextColoredRGB(text)
    local style = imgui.GetStyle()
    local colors = style.Colors
    local ImVec4 = imgui.ImVec4

    local explode_argb = function(argb)
        local a = bit.band(bit.rshift(argb, 24), 0xFF)
        local r = bit.band(bit.rshift(argb, 16), 0xFF)
        local g = bit.band(bit.rshift(argb, 8), 0xFF)
        local b = bit.band(argb, 0xFF)
        return a, r, g, b
    end

    local getcolor = function(color)
        if color:sub(1, 6):upper() == 'SSSSSS' then
            local r, g, b = colors[1].x, colors[1].y, colors[1].z
            local a = tonumber(color:sub(7, 8), 16) or colors[1].w * 255
            return ImVec4(r, g, b, a / 255)
        end
        local color = type(color) == 'string' and tonumber(color, 16) or color
        if type(color) ~= 'number' then return end
        local r, g, b, a = explode_argb(color)
        return imgui.ImColor(r, g, b, a):GetVec4()
    end

    local render_text = function(text_)
        for w in text_:gmatch('[^\r\n]+') do
            local text, colors_, m = {}, {}, 1
            w = w:gsub('{(......)}', '{%1FF}')
            while w:find('{........}') do
                local n, k = w:find('{........}')
                local color = getcolor(w:sub(n + 1, k - 1))
                if color then
                    text[#text], text[#text + 1] = w:sub(m, n - 1), w:sub(k + 1, #w)
                    colors_[#colors_ + 1] = color
                    m = n
                end
                w = w:sub(1, n - 1) .. w:sub(k + 1, #w)
            end
            if text[0] then
                for i = 0, #text do
                    imgui.TextColored(colors_[i] or colors[1], u8(text[i]))
                    imgui.SameLine(nil, 0)
                end
                imgui.NewLine()
            else imgui.Text(u8(w)) end
        end
    end
        render_text(text)
end

function imgui.TextButton(text, bool)
    imgui.TextColoredRGB(string.format('[    %s', bool.v and '{00ff00}ON' or '{ff0000}OFF'))
    if imgui.IsItemClicked() then bool.v = not bool.v end
    imgui.SameLine()
    imgui.Text('  ]  '..text)
    return bool.v
end

function imgui.OnDrawFrame()
        if window_menu.v then
            imgui.SetNextWindowSize(imgui.ImVec2(180, 320), imgui.Cond.FirstUseEver)
            imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
            imgui.ShowCursor = true
            imgui.Begin('Window')
            if imgui.TextButton('gmcar1', func1) then
                mainIni.config.func1 = func1.v
                inicfg.save(mainIni, 'imguihui.ini')
            end
            if imgui.Checkbox('gmcar', func) then
                mainIni.config.func = func.v
                inicfg.save(mainIni, 'imguihui.ini')
            end
        else
            imgui.ShowCursor = false
        end
        imgui.End()
end
up
@PanSeek
 
Последнее редактирование:

Rice.

Известный
Модератор
1,758
1,714
[ML] (error) gettohelp.lua: ...iles (x86)\DARK AUTUMN GTA SAMP\moonloader\gettohelp.lua:27: sol: no matching function call takes this number of arguments and the specified types
stack traceback:
[C]: in function 'ImBuffer'
...iles (x86)\DARK AUTUMN GTA SAMP\moonloader\gettohelp.lua:27: in main chunk
Lua:
local buffer = imgui.ImBuffer('Text', 256)
 
  • Ха-ха
Реакции: madrasso

taygahack

Новичок
6
1
Как мне подключить к кнопке в imgui допустим изменение времени на ночь?
 

Driht

Участник
53
2
Как сделать так чтобы например переменная
peremennaia = "{[1986, -1561, 210] и еще какойто корд }"
и написала команду например /setmarker 1986, -1561, 210 там чтобы много точек чекало
 

Мира

Известный
456
9
0 реакции при проверке на нажатие. без проверки скрипт выводит ид игрока, за которым я в реконе
Lua:
function sampev.onTogglePlayerSpectating(state)

    spectat = state

end

function sampev.onSpectatePlayer(playerId, camType)

    if isKeyJustPressed(VK_LSHIFT)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
    then
        if spectat then
            sampAddChatMessage(playerId, -1)
        end
    end

end
и как сделать закрытие imgui окна при отсутствии рекона?
Lua:
if spectat then
sampAddChatMessage(playerId, -1)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
else--не правильно
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end
 

Rice.

Известный
Модератор
1,758
1,714
0 реакции при проверке на нажатие. без проверки скрипт выводит ид игрока, за которым я в реконе
Lua:
function sampev.onTogglePlayerSpectating(state)

    spectat = state

end

function sampev.onSpectatePlayer(playerId, camType)

    if isKeyJustPressed(VK_LSHIFT)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
    then
        if spectat then
            sampAddChatMessage(playerId, -1)
        end
    end

end
и как сделать закрытие imgui окна при отсутствии рекона?
Lua:
if spectat then
sampAddChatMessage(playerId, -1)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
else--не правильно
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end
Lua:
-- wait (0)

if spectat then
    sampAddChatMessage(playerId, -1)
    main_window_state.v = true
    imgui.Process = main_window_state.v
else
    main_window_state.v = false
    imgui.Process = main_window_state.v
end

0 реакции при проверке на нажатие. без проверки скрипт выводит ид игрока, за которым я в реконе
Lua:
function sampev.onTogglePlayerSpectating(state)

    spectat = state

end

function sampev.onSpectatePlayer(playerId, camType)

    if isKeyJustPressed(VK_LSHIFT)
        and not sampIsChatInputActive()
        and not sampIsDialogActive()
    then
        if spectat then
            sampAddChatMessage(playerId, -1)
        end
    end

end
и как сделать закрытие imgui окна при отсутствии рекона?
Lua:
if spectat then
sampAddChatMessage(playerId, -1)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
else--не правильно
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end
Lua:
-- wait(0)
if isKeyJustPressed(VK_LSHIFT) and not sampIsChatInputActive() and not sampIsDialogActive() then
    if spectat then
        sampAddChatMessage(specid, -1)
    end
end

function sampev.onSpectatePlayer(playerId, camType)   
    specid = playerId
end
 
  • Нравится
Реакции: Мира