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

wulfandr

Известный
637
260
При изменении чего либо в ини файле через imgui, изменение начинает работать, только после перезагрузки скрипта. Как сделать так, что бы после изменения сразу все работало как надо без перезагрузок?
сохрани переменную на то, что ты изменил, а не только сохрани в ини
 

NOWLEX

Участник
41
3
сохрани переменную на то, что ты изменил, а не только сохрани в ини
я имею ввиду, что я сделал скрипт, который настраивается прямо в игре, и когда я что то настраиваю, то эта настройка начинает работать только после перезапуска скрипта
 

wulfandr

Известный
637
260
я имею ввиду, что я сделал скрипт, который настраивается прямо в игре, и когда я что то настраиваю, то эта настройка начинает работать только после перезапуска скрипта
блять я же сказал запиши новое значение в переменную которая используется в качестве настройки. понятно это будет работать только после перезагрузки, т.к. чтение идёт при запуске скрипта в твоём случае
 

NOWLEX

Участник
41
3
блять я же сказал запиши новое значение в переменную которая используется в качестве настройки. понятно это будет работать только после перезагрузки, т.к. чтение идёт при запуске скрипта в твоём случае
я на самом деле не особо понял, какую именно переменную нужно изменить и как, прошу прощения второй день только учу все это, можешь поподробнее объяснить?
 

f0rtrix

Известный
208
15
я на самом деле не особо понял, какую именно переменную нужно изменить и как, прошу прощения второй день только учу все это, можешь поподробнее объяснить?
Переменные в файле меняются при запуске скрипта либо при перезаписи в файл. Главное чтоб значение переменных изменялось
 

NOWLEX

Участник
41
3
Переменные в файле меняются при запуске скрипта либо при перезаписи в файл. Главное чтоб значение переменных изменялось
Поясните пж в коде, что нужно изменить, что бы когда меняешь значение, оно изменялось без перезагрузки скрипта.
Lua:
__name__    = "ghettohelper"
__version__ = "1.0"
__author__    = "nowlex"

require "lib.moonloader" -- подключение библиотеки moonloader
local samp = require 'samp.events'
local sampev = require 'lib.samp.events'
local keys = require "vkeys"
local wm = require 'lib.windows.message'
local mem = require "memory"
local inicfg = require 'inicfg'
local settingsFile = 'ghettohelper.ini'
local ini = inicfg.load({
    Deagle =
        {
            AmountPt=AmountPtInput
        },
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(ini, settingsFile) end
local rkeys = require 'rkeys'
local imgui = require "imgui"
local encoding = require "encoding"
encoding.default = "CP1251"
u8 = encoding.UTF8

local AmountPtInput = imgui.ImInt(ini.Deagle.AmountPt)
local show_amountpt_settings = imgui.ImBool(false)

__needmaterials__ = ini.Deagle.AmountPt

imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar


local main_window_state = imgui.ImBool(false)
local promo = "#nowlex"
check_status = imgui.ImBool(false)
check_status1 = imgui.ImBool(false)
check_status2 = imgui.ImBool(false)
check_status3 = imgui.ImBool(false)
check_status4 = imgui.ImBool(false)
local vkontakte = imgui.ImBool(false)

local dead = false

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('ghelper',ghelper)
    imgui.Process = false
    wait(2000)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Загружен!', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Автор: {FF5656}Nowlex', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}ВК: {FF5656}vk.com/nowl3x', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}YouTube: {FF5656}www.youtube.com/c/Nowlex', -1)
    while true do
        wait(0)

        if check_status.v then
            if isCharDead(PLAYER_PED) and not dead then
                sampSendChat('/fixcar')
                dead = true -- чтобы не флудило
            elseif not isCharDead(PLAYER_PED) and dead then
                dead = false
            end
        end

        if check_status1.v then
            if isKeyJustPressed(VK_MBUTTON) and not sampIsChatInputActive() and not sampIsDialogActive() then
                sampSendChat("/lock")
            end
        end

        if check_status2.v then
            if isSampAvailable() then
                mem.setint8(0xB7CEE4, 1)
            end
        end

        if check_status4.v then
            result, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            if isKeyDown(VK_MENU) and isKeyJustPressed(VK_3) then
                sampSendChat("/sellgun deagle " .. __needmaterials__ .. " 5 " .. id)
            end
        end


    end
end

function sampev.onServerMessage(color,text)
    if check_status3.v then
        lua_thread.create(function()
            if text:find('склад с оружием') then
                if color == 0x57FF4FFF then
                    wait(500)
                    sampSendChat('/get guns')
                end
            end
        end)
    end
end



function sampev.onShowDialog(id, style, title, b1,b2,text)
    if title:find("По приглашению от") then
        sampSendDialogResponse(id, 1, 0, promo)
        return false
    end
end

function ghelper(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    
    if main_window_state.v == false then
        imgui.Process = false
    end

    local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(320, 180), imgui.Cond.FirstUseEver)

    imgui.Begin("Ghetto Helper", main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(260, 28))
    if imgui.Button('Settings', show_amountpt_settings) then
        imgui.OpenPopup('#Settings')
    end
    if imgui.BeginPopup('#Settings') then
        imgui.Text(u8'Кол-во патрон для крафта')
        if imgui.InputInt('##inputint0', AmountPtInput) then
            ini.Deagle.AmountPt = AmountPtInput.v
            inicfg.save(ini, settingsFile)
        end
        imgui.EndMenu()
    end

    imgui.Checkbox(u8"FIXCAR т/с после смерти", check_status)

    imgui.Checkbox(u8"Открыть/закрыть т/с на колесико мыши", check_status1)

    imgui.Checkbox(u8"Бесконечный бег", check_status2)

    imgui.Checkbox(u8"Авто взятие материалов", check_status3)

    imgui.Checkbox(u8"Крафт дигла на сочетание клавиш alt 3", check_status4)

    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(285, 155))
    imgui.TextDisabled('Info')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted('Author: '..__author__..'\nVersion: '..__version__)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
    imgui.End()
end
 

f0rtrix

Известный
208
15
Поясните пж в коде, что нужно изменить, что бы когда меняешь значение, оно изменялось без перезагрузки скрипта.
Lua:
__name__    = "ghettohelper"
__version__ = "1.0"
__author__    = "nowlex"

require "lib.moonloader" -- подключение библиотеки moonloader
local samp = require 'samp.events'
local sampev = require 'lib.samp.events'
local keys = require "vkeys"
local wm = require 'lib.windows.message'
local mem = require "memory"
local inicfg = require 'inicfg'
local settingsFile = 'ghettohelper.ini'
local ini = inicfg.load({
    Deagle =
        {
            AmountPt=AmountPtInput
        },
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(ini, settingsFile) end
local rkeys = require 'rkeys'
local imgui = require "imgui"
local encoding = require "encoding"
encoding.default = "CP1251"
u8 = encoding.UTF8

local AmountPtInput = imgui.ImInt(ini.Deagle.AmountPt)
local show_amountpt_settings = imgui.ImBool(false)

__needmaterials__ = ini.Deagle.AmountPt

imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar


local main_window_state = imgui.ImBool(false)
local promo = "#nowlex"
check_status = imgui.ImBool(false)
check_status1 = imgui.ImBool(false)
check_status2 = imgui.ImBool(false)
check_status3 = imgui.ImBool(false)
check_status4 = imgui.ImBool(false)
local vkontakte = imgui.ImBool(false)

local dead = false

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('ghelper',ghelper)
    imgui.Process = false
    wait(2000)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Загружен!', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Автор: {FF5656}Nowlex', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}ВК: {FF5656}vk.com/nowl3x', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}YouTube: {FF5656}www.youtube.com/c/Nowlex', -1)
    while true do
        wait(0)

        if check_status.v then
            if isCharDead(PLAYER_PED) and not dead then
                sampSendChat('/fixcar')
                dead = true -- чтобы не флудило
            elseif not isCharDead(PLAYER_PED) and dead then
                dead = false
            end
        end

        if check_status1.v then
            if isKeyJustPressed(VK_MBUTTON) and not sampIsChatInputActive() and not sampIsDialogActive() then
                sampSendChat("/lock")
            end
        end

        if check_status2.v then
            if isSampAvailable() then
                mem.setint8(0xB7CEE4, 1)
            end
        end

        if check_status4.v then
            result, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            if isKeyDown(VK_MENU) and isKeyJustPressed(VK_3) then
                sampSendChat("/sellgun deagle " .. __needmaterials__ .. " 5 " .. id)
            end
        end


    end
end

function sampev.onServerMessage(color,text)
    if check_status3.v then
        lua_thread.create(function()
            if text:find('склад с оружием') then
                if color == 0x57FF4FFF then
                    wait(500)
                    sampSendChat('/get guns')
                end
            end
        end)
    end
end



function sampev.onShowDialog(id, style, title, b1,b2,text)
    if title:find("По приглашению от") then
        sampSendDialogResponse(id, 1, 0, promo)
        return false
    end
end

function ghelper(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
   
    if main_window_state.v == false then
        imgui.Process = false
    end

    local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(320, 180), imgui.Cond.FirstUseEver)

    imgui.Begin("Ghetto Helper", main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(260, 28))
    if imgui.Button('Settings', show_amountpt_settings) then
        imgui.OpenPopup('#Settings')
    end
    if imgui.BeginPopup('#Settings') then
        imgui.Text(u8'Кол-во патрон для крафта')
        if imgui.InputInt('##inputint0', AmountPtInput) then
            ini.Deagle.AmountPt = AmountPtInput.v
            inicfg.save(ini, settingsFile)
        end
        imgui.EndMenu()
    end

    imgui.Checkbox(u8"FIXCAR т/с после смерти", check_status)

    imgui.Checkbox(u8"Открыть/закрыть т/с на колесико мыши", check_status1)

    imgui.Checkbox(u8"Бесконечный бег", check_status2)

    imgui.Checkbox(u8"Авто взятие материалов", check_status3)

    imgui.Checkbox(u8"Крафт дигла на сочетание клавиш alt 3", check_status4)

    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(285, 155))
    imgui.TextDisabled('Info')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted('Author: '..__author__..'\nVersion: '..__version__)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
    imgui.End()
end
В каком именно моменте и что именно должно сохраняться?
 

NOWLEX

Участник
41
3
В каком именно моменте и что именно должно сохраняться?
Здесь прямо в игре меняешь значение и должно крафтить пушку с количеством патрон, которым ты поставил. А скрипт начинает работать с новым значением только после перезагрузки (Ctrl R)
Lua:
    if imgui.BeginPopup('#Settings') then
        imgui.Text(u8'Кол-во патрон для крафта')
        if imgui.InputInt('##inputint0', AmountPtInput) then
            ini.Deagle.AmountPt = AmountPtInput.v
            inicfg.save(ini, settingsFile)
        end
        imgui.EndMenu()
    end
 

Tol4ek

Активный
217
56
Lua:
local imgui = require "imgui"
local encoding = require "encoding"
encoding.default = 'CP1251'
u8 = encoding.UTF8
local buff = imgui.ImBuffer(1024)
local rx, ry = getScreenResolution()
local main_window_state = imgui.ImBool(false)

function main()
    while not isSampAvailable() do
        wait(0)
    end
    file = io.open(getGameDirectory().."//moonloader//otveti.txt", "r")
    buff.v= file:read('*a')
    file:close()
    sampRegisterChatCommand('hcbot', cmd_hcbot)

    while true do
        wait(0)
        if main_window_state.v == false then
        imgui.Process = false
        end   
end
function cmd_hcbot(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(480,250), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((rx /2 ), ry / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(u8"Okno", main_window_state)
    imgui.PushItemWidth(400)
    imgui.InputTextMultiline(u8'##bufftext', buff)
    imgui.End()
end
Как сделать так, чтобы текст, выводимый из ini файла был в адекватной кодировке?
 

Next..

Известный
343
135
Поясните пж в коде, что нужно изменить, что бы когда меняешь значение, оно изменялось без перезагрузки скрипта.
Lua:
__name__    = "ghettohelper"
__version__ = "1.0"
__author__    = "nowlex"

require "lib.moonloader" -- подключение библиотеки moonloader
local samp = require 'samp.events'
local sampev = require 'lib.samp.events'
local keys = require "vkeys"
local wm = require 'lib.windows.message'
local mem = require "memory"
local inicfg = require 'inicfg'
local settingsFile = 'ghettohelper.ini'
local ini = inicfg.load({
    Deagle =
        {
            AmountPt=AmountPtInput
        },
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(ini, settingsFile) end
local rkeys = require 'rkeys'
local imgui = require "imgui"
local encoding = require "encoding"
encoding.default = "CP1251"
u8 = encoding.UTF8

local AmountPtInput = imgui.ImInt(ini.Deagle.AmountPt)
local show_amountpt_settings = imgui.ImBool(false)

__needmaterials__ = ini.Deagle.AmountPt

imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar


local main_window_state = imgui.ImBool(false)
local promo = "#nowlex"
check_status = imgui.ImBool(false)
check_status1 = imgui.ImBool(false)
check_status2 = imgui.ImBool(false)
check_status3 = imgui.ImBool(false)
check_status4 = imgui.ImBool(false)
local vkontakte = imgui.ImBool(false)

local dead = false

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('ghelper',ghelper)
    imgui.Process = false
    wait(2000)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Загружен!', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Автор: {FF5656}Nowlex', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}ВК: {FF5656}vk.com/nowl3x', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}YouTube: {FF5656}www.youtube.com/c/Nowlex', -1)
    while true do
        wait(0)

        if check_status.v then
            if isCharDead(PLAYER_PED) and not dead then
                sampSendChat('/fixcar')
                dead = true -- чтобы не флудило
            elseif not isCharDead(PLAYER_PED) and dead then
                dead = false
            end
        end

        if check_status1.v then
            if isKeyJustPressed(VK_MBUTTON) and not sampIsChatInputActive() and not sampIsDialogActive() then
                sampSendChat("/lock")
            end
        end

        if check_status2.v then
            if isSampAvailable() then
                mem.setint8(0xB7CEE4, 1)
            end
        end

        if check_status4.v then
            result, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            if isKeyDown(VK_MENU) and isKeyJustPressed(VK_3) then
                sampSendChat("/sellgun deagle " .. __needmaterials__ .. " 5 " .. id)
            end
        end


    end
end

function sampev.onServerMessage(color,text)
    if check_status3.v then
        lua_thread.create(function()
            if text:find('склад с оружием') then
                if color == 0x57FF4FFF then
                    wait(500)
                    sampSendChat('/get guns')
                end
            end
        end)
    end
end



function sampev.onShowDialog(id, style, title, b1,b2,text)
    if title:find("По приглашению от") then
        sampSendDialogResponse(id, 1, 0, promo)
        return false
    end
end

function ghelper(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
   
    if main_window_state.v == false then
        imgui.Process = false
    end

    local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(320, 180), imgui.Cond.FirstUseEver)

    imgui.Begin("Ghetto Helper", main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(260, 28))
    if imgui.Button('Settings', show_amountpt_settings) then
        imgui.OpenPopup('#Settings')
    end
    if imgui.BeginPopup('#Settings') then
        imgui.Text(u8'Кол-во патрон для крафта')
        if imgui.InputInt('##inputint0', AmountPtInput) then
            ini.Deagle.AmountPt = AmountPtInput.v
            inicfg.save(ini, settingsFile)
        end
        imgui.EndMenu()
    end

    imgui.Checkbox(u8"FIXCAR т/с после смерти", check_status)

    imgui.Checkbox(u8"Открыть/закрыть т/с на колесико мыши", check_status1)

    imgui.Checkbox(u8"Бесконечный бег", check_status2)

    imgui.Checkbox(u8"Авто взятие материалов", check_status3)

    imgui.Checkbox(u8"Крафт дигла на сочетание клавиш alt 3", check_status4)

    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(285, 155))
    imgui.TextDisabled('Info')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted('Author: '..__author__..'\nVersion: '..__version__)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
    imgui.End()
end
Lua:
__name__    = "ghettohelper"
__version__ = "1.0"
__author__    = "nowlex"

require "lib.moonloader" -- подключение библиотеки moonloader
local samp = require 'samp.events'
local sampev = require 'lib.samp.events'
local keys = require "vkeys"
local wm = require 'lib.windows.message'
local mem = require "memory"
local inicfg = require 'inicfg'
local settingsFile = 'ghettohelper.ini'
local ini = inicfg.load({
    Deagle =
        {
            AmountPt=AmountPtInput
        },
}, settingsFile)
if not doesFileExist('moonloader/config/'..settingsFile) then inicfg.save(ini, settingsFile) end
local rkeys = require 'rkeys'
local imgui = require "imgui"
local encoding = require "encoding"
encoding.default = "CP1251"
u8 = encoding.UTF8

local AmountPtInput = imgui.ImInt(ini.Deagle.AmountPt)
local show_amountpt_settings = imgui.ImBool(false)

imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar


local main_window_state = imgui.ImBool(false)
local promo = "#nowlex"
check_status = imgui.ImBool(false)
check_status1 = imgui.ImBool(false)
check_status2 = imgui.ImBool(false)
check_status3 = imgui.ImBool(false)
check_status4 = imgui.ImBool(false)
local vkontakte = imgui.ImBool(false)

local dead = false

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampRegisterChatCommand('ghelper',ghelper)
    imgui.Process = false
    wait(2000)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Загружен!', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}Автор: {FF5656}Nowlex', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}ВК: {FF5656}vk.com/nowl3x', -1)
    sampAddChatMessage('{FF5656}[GhettoHelper]: {FFFFFF}YouTube: {FF5656}www.youtube.com/c/Nowlex', -1)
    while true do
        wait(0)

        if check_status.v then
            if isCharDead(PLAYER_PED) and not dead then
                sampSendChat('/fixcar')
                dead = true -- чтобы не флудило
            elseif not isCharDead(PLAYER_PED) and dead then
                dead = false
            end
        end

        if check_status1.v then
            if isKeyJustPressed(VK_MBUTTON) and not sampIsChatInputActive() and not sampIsDialogActive() then
                sampSendChat("/lock")
            end
        end

        if check_status2.v then
            if isSampAvailable() then
                mem.setint8(0xB7CEE4, 1)
            end
        end

        if check_status4.v then
            result, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
            if isKeyDown(VK_MENU) and isKeyJustPressed(VK_3) then
                sampSendChat("/sellgun deagle " .. ini.Deagle.AmountPt .. " 5 " .. id)
            end
        end


    end
end

function sampev.onServerMessage(color,text)
    if check_status3.v then
        lua_thread.create(function()
            if text:find('склад с оружием') then
                if color == 0x57FF4FFF then
                    wait(500)
                    sampSendChat('/get guns')
                end
            end
        end)
    end
end



function sampev.onShowDialog(id, style, title, b1,b2,text)
    if title:find("По приглашению от") then
        sampSendDialogResponse(id, 1, 0, promo)
        return false
    end
end

function ghelper(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    
    if main_window_state.v == false then
        imgui.Process = false
    end

    local sw, sh = getScreenResolution()
    imgui.SetNextWindowPos(imgui.ImVec2(sw / 2, sh / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.SetNextWindowSize(imgui.ImVec2(320, 180), imgui.Cond.FirstUseEver)

    imgui.Begin("Ghetto Helper", main_window_state, imgui.WindowFlags.NoResize + imgui.WindowFlags.NoCollapse)
    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(260, 28))
    if imgui.Button('Settings', show_amountpt_settings) then
        imgui.OpenPopup('#Settings')
    end
    if imgui.BeginPopup('#Settings') then
        imgui.Text(u8'Кол-во патрон для крафта')
        if imgui.InputInt('##inputint0', AmountPtInput) then
            ini.Deagle.AmountPt = AmountPtInput.v
            inicfg.save(ini, settingsFile)
        end
        imgui.EndMenu()
    end

    imgui.Checkbox(u8"FIXCAR т/с после смерти", check_status)

    imgui.Checkbox(u8"Открыть/закрыть т/с на колесико мыши", check_status1)

    imgui.Checkbox(u8"Бесконечный бег", check_status2)

    imgui.Checkbox(u8"Авто взятие материалов", check_status3)

    imgui.Checkbox(u8"Крафт дигла на сочетание клавиш alt 3", check_status4)

    imgui.SameLine()
    imgui.SetCursorPos(imgui.ImVec2(285, 155))
    imgui.TextDisabled('Info')
    if imgui.IsItemHovered() then
        imgui.BeginTooltip()
        imgui.PushTextWrapPos(450)
        imgui.TextUnformatted('Author: '..__author__..'\nVersion: '..__version__)
        imgui.PopTextWrapPos()
        imgui.EndTooltip()
    end
    imgui.End()
end
Сделай так
 

f0rtrix

Известный
208
15
Lua::
local imgui = require "imgui"
local encoding = require "encoding"
encoding.default = 'CP1251'
u8 = encoding.UTF8
local buff = imgui.ImBuffer(1024)
local rx, ry = getScreenResolution()
local main_window_state = imgui.ImBool(false)

function main()
    while not isSampAvailable() do
        wait(0)
    end
    file = io.open(getGameDirectory().."//moonloader//otveti.txt", "r")
    buff.v= file:read('*a')
    file:close()
    sampRegisterChatCommand('hcbot', cmd_hcbot)

    while true do
        wait(0)
        if main_window_state.v == false then
        imgui.Process = false
        end  
end
function cmd_hcbot(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v
end

function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(480,250), imgui.Cond.FirstUseEver)
    imgui.SetNextWindowPos(imgui.ImVec2((rx /2 ), ry / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
    imgui.Begin(u8"Okno", main_window_state)
    imgui.PushItemWidth(400)
    imgui.InputTextMultiline(u8'##bufftext', buff)
    imgui.End()
end
Как сделать так, чтобы текст, выводимый из ini файла был в адекватной кодировке?
Использовать перед переменной или строкой u8, либо же ud8:decode(переменная)
 
  • Нравится
Реакции: Tol4ek

Tol4ek

Активный
217
56
Использовать перед переменной или строкой u8, либо же ud8:decode(переменная)
Я чёт рукажоп, переменную вставил и вообще весь скрипт крашится :/
Lua:
function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(480,250), imgui.Cond.FirstUseEver)--установка размера окна
    imgui.SetNextWindowPos(imgui.ImVec2((rx /2 ), ry / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))--установка позиции окна
    imgui.Begin(u8" Bot", main_window_state) -- создание окна и его заголовок
    imgui.PushItemWidth(400)
    imgui.InputTextMultiline(ud8:decode('##bufftext', buff))
    imgui.End()
end
[20:44:12.186124] (error) Bot: C:\games\GTA San Andreas\moonloader\lib\encoding.lua:38: bad argument #1 to 'gsub' (string expected, got userdata)
stack traceback:
[C]: in function 'gsub'
C:\games\GTA San Andreas\moonloader\lib\encoding.lua:38: in function 'normalize_encoding_name'
C:\games\GTA San Andreas\moonloader\lib\encoding.lua:68: in function 'decode'
C:\games\GTA San Andreas\moonloader\Bot.lua:174: in function 'OnDrawFrame'
C:\games\GTA San Andreas\moonloader\lib\imgui.lua:1378: in function <C:\games\GTA San Andreas\moonloader\lib\imgui.lua:1367>
[20:44:12.187123] (error) Bot: Script died due to an error. (0D09175C)
 

f0rtrix

Известный
208
15
Я чёт рукажоп, переменную вставил и вообще весь скрипт крашится :/
Lua:
function imgui.OnDrawFrame()
    imgui.SetNextWindowSize(imgui.ImVec2(480,250), imgui.Cond.FirstUseEver)--установка размера окна
    imgui.SetNextWindowPos(imgui.ImVec2((rx /2 ), ry / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))--установка позиции окна
    imgui.Begin(u8" Bot", main_window_state) -- создание окна и его заголовок
    imgui.PushItemWidth(400)
    imgui.InputTextMultiline(ud8:decode('##bufftext', buff))
    imgui.End()
end
[20:44:12.186124] (error) Bot: C:\games\GTA San Andreas\moonloader\lib\encoding.lua:38: bad argument #1 to 'gsub' (string expected, got userdata)
stack traceback:
[C]: in function 'gsub'
C:\games\GTA San Andreas\moonloader\lib\encoding.lua:38: in function 'normalize_encoding_name'
C:\games\GTA San Andreas\moonloader\lib\encoding.lua:68: in function 'decode'
C:\games\GTA San Andreas\moonloader\Bot.lua:174: in function 'OnDrawFrame'
C:\games\GTA San Andreas\moonloader\lib\imgui.lua:1378: in function <C:\games\GTA San Andreas\moonloader\lib\imgui.lua:1367>
[20:44:12.187123] (error) Bot: Script died due to an error. (0D09175C)
Опечатался, извини, не ud8:decode, а просто u8:decode()
Сделай лучше вот так:
Lua:
imgui.InputTextMultiline(('##bufftext', u8(buff))
 
  • Нравится
Реакции: Tol4ek

Tol4ek

Активный
217
56
Опечатался, извини, не ud8:decode, а просто u8:decode()
Сделай лучше вот так:
Lua:
imgui.InputTextMultiline(('##bufftext', u8(buff))
173 - строка как раз с этим
[21:13:19.628569] (error) Bot.lua: C:\games\GTA San Andreas\moonloader\Bot.lua:173: ')' expected near ','
[21:13:19.628569] (error) Bot.lua: Script died due to an error. (2DBD18AC)