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

copypaste_scripter

Известный
1,431
290
привет. у меня два вопроса
1. как можно в imgui сделать так, чтобы radio button стали меньше размером? мне пофиг каким образом будет это сделано, главное это достигнуть
push item width / set next item width не работают на такие виджеты, как ответил разработчик imgui ocornut на гитхабе. но я не верю, что, что нибудь не достигаемо в программировании. я думаю может задать фонт радио виджетам и потом на каждом вызове фонта задать там значение?

2. что можно придумать насчет вот такого выборочнога поля. ну типо человек в имгуи выбирает место с площади треугольница, а программа с имгуи достает из этой точки значении float/int
1726949843192.png


edit:
3. можно как то на каждом части скрипта задать отдельный стиль, цвета и т.д.
 
Последнее редактирование:

Willy4ka

вилличка
Модератор
723
1,092
Никак, это сервер

привет. у меня два вопроса
1. как можно в imgui сделать так, чтобы radio button стали меньше размером? мне пофиг каким образом будет это сделано, главное это достигнуть
push item width / set next item width не работают на такие виджеты, как ответил разработчик imgui ocornut на гитхабе. но я не верю, что, что нибудь не достигаемо в программировании. я думаю может задать фонт радио виджетам и потом на каждом вызове фонта задать там значение?

2. что можно придумать насчет вот такого выборочнога поля. ну типо человек в имгуи выбирает место с площади треугольница, а программа с имгуи достает из этой точки значении float/intПосмотреть вложение 252408

edit:
3. можно как то на каждом части скрипта задать отдельный стиль, цвета и т.д.
1.
можешь юзать эту функу

Lua:
local radio = imgui.new.bool(true)
imgui.customRadioButton(u8("radio"), radio, 15);
Lua:
function imgui.customRadioButton(str_id, value, radius)
    radius = radius or 10;
    local p = imgui.GetCursorScreenPos();
    local dl = imgui.GetWindowDrawList();
    local result = imgui.InvisibleButton(str_id, imgui.ImVec2((radius+radius/5)/2 + radius*1.5+imgui.CalcTextSize(str_id).x, radius*2));
    dl:AddCircleFilled(imgui.ImVec2(p.x+(radius+radius/5)/2, p.y+(radius+radius/5)/2), radius, 0xFF353535, radius > 16 and radius or 16);
    dl:AddCircleFilled(imgui.ImVec2(p.x+(radius+radius/5)/2, p.y+(radius+radius/5)/2), radius-radius/5, value[0] and 0xFFAAAAAA or 0xFF505050, radius > 16 and radius or 16);
    dl:AddText(imgui.ImVec2(p.x+(radius+radius/5)/2 + radius*1.5, p.y+(radius+radius/5)/2 - imgui.CalcTextSize(str_id).y/2), 0xFFFFFFFF, str_id);
    if result then value[0] = not value[0] end;
    return result;
end

3.

Lua:
imgui.PushStyleColor(imgui.Col.Button, imgui.ImVec4(1.00, 0.00, 0.00, 1.00))
imgui.PushStyleColor(imgui.Col.Text, imgui.ImVec4(1.00, 0.00, 1.00, 1.00))
imgui.PushStyleVarFloat(imgui.StyleVar.FrameRounding, 0.0)

imgui.Button('button')
imgui.Text(u8('дадада'))

imgui.PopStyleColor(1)
imgui.PopStyleVar(1)
 
Последнее редактирование:

Hange

Известный
2
0
Помогите написать цикл, который включается при вводе команды, так же выключается при вводе команды
В цикле: нажимается определенная кнопка, когда в чате появляется текст или определенное слово.
 

moreveal

Известный
969
702
Помогите написать цикл, который включается при вводе команды, так же выключается при вводе команды
В цикле: нажимается определенная кнопка, когда в чате появляется текст или определенное слово.
Lua:
local activate = false

sampRegisterChatCommand("test", function() activate = not activate end)

-- беск. цикл
while true do wait(0)
    if activate then
        --[[ твои действия ]]
    end
end

но это если с циклом, в твоем то случае вообще лучш:

Lua:
local sampev = require 'samp.events'

local activate = false

sampRegisterChatCommand("test", function() activate = not activate end)

function sampev.onServerMessage(color, text)
    if activate then
        if text:find("твоя строка") then
            --[[ твои действия ]]
        end
    end
end
 
  • Нравится
Реакции: Hange

moreveal

Известный
969
702
Lua:
local filepath = "path/to/file.json"

function sampev.onShowDialog(dialogid, style, title, b1, b2, text)
    local f = io.open(filepath, 'w+')
    if f then
        f:write(encodeJson({dialogid = dialogid, style = style, title = title, b1 = b1, b2 = b2, text = text}))
        f:close()
    end
end

sampRegisterChatCommand("test", function()
    local f = io.open(filepath, 'r')
    if f then
        local data = decodeJson(f:read("*a"))
        print(data.dialogid, data.style, data.title, data.b1, data.b2, data.text)
       
        f:close()
    end
end)
 
  • Нравится
Реакции: Макс | Lycorn

Макс | Lycorn

Участник
166
13
Lua:
local filepath = "path/to/file.json"

function sampev.onShowDialog(dialogid, style, title, b1, b2, text)
    local f = io.open(filepath, 'w+')
    if f then
        f:write(encodeJson({dialogid = dialogid, style = style, title = title, b1 = b1, b2 = b2, text = text}))
        f:close()
    end
end

sampRegisterChatCommand("test", function()
    local f = io.open(filepath, 'r')
    if f then
        local data = decodeJson(f:read("*a"))
        print(data.dialogid, data.style, data.title, data.b1, data.b2, data.text)
      
        f:close()
    end
end)
это ты для имгуи написал?) или нет? просто на мимгуи не робит
 
  • Эм
Реакции: chromiusj

chromiusj

модерирую шмодерирую
Модератор
5,955
4,285
это ты для имгуи написал?) или нет? просто на мимгуи не робит
Может лучше написать конкретно на какую платформу тебе надо,а не писать имгуи/мимгуи
Судя по такому ответу,кажется,что тебе надо на монетлоадер,где таких функций работ с жсон нет
 

Макс | Lycorn

Участник
166
13
Может лучше написать конкретно на какую платформу тебе надо,а не писать имгуи/мимгуи
Судя по такому ответу,кажется,что тебе надо на монетлоадер,где таких функций работ с жсон нет
Извиняюсь, просто в последнее время все пишут на мимгуи, вот и подумал что подумает что для мимгуи
 

chromiusj

модерирую шмодерирую
Модератор
5,955
4,285
Извиняюсь, просто в последнее время все пишут на мимгуи, вот и подумал что подумает что для мимгуи
Можно допустим так:
Lua:
local imgui = require 'mimgui'
local sampev = require 'lib.samp.events'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local renderWindow = imgui.new.bool(true)
local filepath = getWorkingDirectory().."\\file.json"
local dialogList = {}
local selectedDialog = imgui.new.int(0)

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

local function dialogExists(dialogid)
    for _, dialog in ipairs(dialogList) do
        if dialog.dialogid == dialogid then
            return true
        end
    end
    return false
end

local function saveDialogs()
    local f = io.open(filepath, 'w+')
    if f then
        f:write(encodeJson(dialogList))
        f:close()
    end
end

local function loadDialogs()
    local f = io.open(filepath, 'r')
    if f then
        local content = f:read("*a")
        if content ~= "" then
            dialogList = decodeJson(content)
        end
        f:close()
    end
end

function sampev.onShowDialog(dialogid, style, title, b1, b2, text)
    loadDialogs()

    if not dialogExists(dialogid) then
        table.insert(dialogList, {dialogid = dialogid, style = style, title = title, b1 = b1, b2 = b2, text = text})
        saveDialogs()
    end
end

function main()
    while not isSampAvailable() do wait(0) end
    loadDialogs()
    sampRegisterChatCommand('mimgui', function()
        renderWindow[0] = not renderWindow[0]
    end)
    wait(-1)
end

imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 300
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)

        if imgui.Begin('Main Window', renderWindow) then
            if #dialogList > 0 then
                local titles = {}
                for i, dialog in ipairs(dialogList) do
                    table.insert(titles, u8(dialog.title))
                end

                local comboItems = imgui.new['const char*'][#titles](titles)

                if imgui.Combo(u8'', selectedDialog, comboItems, #titles) then
                    selectedDialog[0] = selectedDialog[0]
                end

                local selectedText = dialogList[selectedDialog[0] + 1].text
                imgui.TextColoredRGB((selectedText))
            else
                imgui.Text(u8"Нет доступных диалогов")
            end
            imgui.End()
        end
    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.ImVec4(r/255, g/255, b/255, a/255)
    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
 
  • Нравится
Реакции: Макс | Lycorn

Макс | Lycorn

Участник
166
13
Можно допустим так:
Lua:
local imgui = require 'mimgui'
local sampev = require 'lib.samp.events'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local renderWindow = imgui.new.bool(true)
local filepath = getWorkingDirectory().."\\file.json"
local dialogList = {}
local selectedDialog = imgui.new.int(0)

imgui.OnInitialize(function()
    imgui.GetIO().IniFilename = nil
end)

local function dialogExists(dialogid)
    for _, dialog in ipairs(dialogList) do
        if dialog.dialogid == dialogid then
            return true
        end
    end
    return false
end

local function saveDialogs()
    local f = io.open(filepath, 'w+')
    if f then
        f:write(encodeJson(dialogList))
        f:close()
    end
end

local function loadDialogs()
    local f = io.open(filepath, 'r')
    if f then
        local content = f:read("*a")
        if content ~= "" then
            dialogList = decodeJson(content)
        end
        f:close()
    end
end

function sampev.onShowDialog(dialogid, style, title, b1, b2, text)
    loadDialogs()

    if not dialogExists(dialogid) then
        table.insert(dialogList, {dialogid = dialogid, style = style, title = title, b1 = b1, b2 = b2, text = text})
        saveDialogs()
    end
end

function main()
    while not isSampAvailable() do wait(0) end
    loadDialogs()
    sampRegisterChatCommand('mimgui', function()
        renderWindow[0] = not renderWindow[0]
    end)
    wait(-1)
end

imgui.OnFrame(
    function() return renderWindow[0] end,
    function(player)
        local resX, resY = getScreenResolution()
        local sizeX, sizeY = 300, 300
        imgui.SetNextWindowPos(imgui.ImVec2(resX / 2, resY / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
        imgui.SetNextWindowSize(imgui.ImVec2(sizeX, sizeY), imgui.Cond.FirstUseEver)

        if imgui.Begin('Main Window', renderWindow) then
            if #dialogList > 0 then
                local titles = {}
                for i, dialog in ipairs(dialogList) do
                    table.insert(titles, u8(dialog.title))
                end

                local comboItems = imgui.new['const char*'][#titles](titles)

                if imgui.Combo(u8'', selectedDialog, comboItems, #titles) then
                    selectedDialog[0] = selectedDialog[0]
                end

                local selectedText = dialogList[selectedDialog[0] + 1].text
                imgui.TextColoredRGB((selectedText))
            else
                imgui.Text(u8"Нет доступных диалогов")
            end
            imgui.End()
        end
    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.ImVec4(r/255, g/255, b/255, a/255)
    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
Спасибо огромное, но можно узнать, как тут изменить текст который нужно будет брать с диалога и сохранять в json?