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

Мира

Участник
455
9
есть код/скрипт для перебора аргументов с определённой задержкой?
мол я прописываю /showpass 1 2 3 и паспорт показывается через сек. игрокам с ИД 1 2 и 3
 

Morse

Потрачен
436
70
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Как получить цвет гетто тереторий?
 

Andrinall

Известный
680
532
Как получить цвет гетто тереторий?
Или через Samp.Events ( ev.onCreateGangZone(zoneId, squareStart, squareEnd, color) )
Или получать инфу о всех гангзонах через эту функцию. ( в цикле, понятное дело c; )
Lua:
local ffi = require 'ffi'

ffi.cdef[[
struct stGangzone
{
    float    fPosition[4];
    uint32_t    dwColor;
    uint32_t    dwAltColor;
};
struct stGangzonePool
{
    struct stGangzone    *pGangzone[1024];
    int iIsListed[1024];
};
]]

function getAllGangZones()
    local gz_tbl = {}
    local gz_pool = ffi.cast('struct stGangzonePool*', sampGetGangzonePoolPtr())
  
    for i = 0, 1023 do
        if gz_pool.iIsListed[i] ~= 0 and gz_pool.pGangzone[i] ~= nil then
            table.insert(gz_tbl, { id = i, pos = gz_pool.pGangzone[i].fPosition, color = gz_pool.pGangzone[i].dwColor, altcolor = gz_pool.pGangzone[i].dwAltColor } )
        end
    end
  
    return gz_tbl
end
 

P!NK.

Участник
68
54
Как внести в imgui.InputText изначальный параметр, который пользовать может менять в последствии?
 

Driht

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

qwеty

Известный
484
156
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

Известный
484
156
В чём проблема? При нажатии на 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.

https://t.me/riceoff
Модератор
1,690
1,439
[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