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

WebDim

Участник
59
3
Помогите пожалуйста как связывать lua imgui с с софтом
То есть как сделать так когда я нажимаю на ползунок активировался скрипт по команде /afk
???
Lua:
local imadd = require 'imgui_addons'

---
if imadd.ToggleButton("AFK", ImBool) then
        isAfk = ImBool.v
end
 
  • Нравится
Реакции: vova2999

Wisadop

Потрачен
145
49
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.

Wisadop

Потрачен
145
49
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
За чем запускать другой скрипт, не проще в свой вставить?
Я в свой скрипт вставляю, imgui перестаёт работать, а анти афк работает

За чем запускать другой скрипт, не проще в свой вставить?
Помоги пожалуйста сделать что бы на ползунок (работа в свёрнутом режиме) анти афк включался
t1_bb там имгуай
в тесте анти афк
 

Вложения

  • t1_bb.lua
    6.1 KB · Просмотры: 9
  • test.lua
    1.3 KB · Просмотры: 10

madrasso

Потрачен
883
324
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Я в свой скрипт вставляю, imgui перестаёт работать, а анти афк работает


Помоги пожалуйста сделать что бы на ползунок (работа в свёрнутом режиме) анти афк включался
t1_bb там имгуай
в тесте анти афк
Не знаю на счет модуля этого, но с обычным чекбоксом делается так.
 

Вложения

  • t1_bb.lua
    6.7 KB · Просмотры: 12
  • Нравится
Реакции: Wisadop

AnWu

Guardian of Order
Всефорумный модератор
4,690
5,202
Как из луа потока передать переменную в основной код?
Сделать переменную глобальной или объявить локальной в глобальной области.
Lua:
local var = 1
function main()
    whie true do
        var = 322
        wait(0)
    end
end
function callbackCmd(param)
print(var)
end
 

Wisadop

Потрачен
145
49
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
Сделать переменную глобальной или объявить локальной в глобальной области.
Lua:
local var = 1
function main()
    whie true do
        var = 322
        wait(0)
    end
end
function callbackCmd(param)
print(var)
end
Уже помогли

Код:
local vkeys = require 'vkeys'
local wm = require 'lib.windows.message'
local imgui = require 'imgui'
local encoding = require 'encoding'
require 'lib.sampfuncs'
local inicfg = require 'inicfg'
local bNotf, notf = pcall(import, "imgui_notf.lua")
local hook = require 'samp.events'
local rkeys = require 'rkeys'
imgui.ToggleButton = require('imgui_addons').ToggleButton
imgui.HotKey = require('imgui_addons').HotKey
imgui.Spinner = require('imgui_addons').Spinner
imgui.BufferingBar = require('imgui_addons').BufferingBar
encoding.default = 'CP1251'
u8 = encoding.UTF8
local imadd = require 'imgui_addons'

local window = imgui.ImBool(false)
local ActiveMenu = {
    v = {vkeys.VK_F2}
}
local bindID = 0

function main()
   if not isSampLoaded() then
      return
   end
   while not isSampAvailable() do
      wait(0)
    end
    sampRegisterChatCommand("test", function ()
        window.v = not window.v
    end)
    bindID = rkeys.registerHotKey(ActiveMenu.v, true, function ()
        window.v = not window.v
    end)
    while true do
        wait(0)
        imgui.Process = window.v
    end
end

function apply_custom_style()
    local style = imgui.GetStyle()
    local colors = style.Colors
    local clr = imgui.Col
    local ImVec4 = imgui.ImVec4
    style.WindowRounding = 1.5
    style.WindowTitleAlign = imgui.ImVec2(0.5, 0.5)
    style.ChildWindowRounding = 1.5
    style.FrameRounding = 1.0
    style.ItemSpacing = imgui.ImVec2(5.0, 4.0)
    style.ScrollbarSize = 13.0
    style.ScrollbarRounding = 0
    style.GrabMinSize = 8.0
    style.GrabRounding = 1.0
    -- style.Alpha =
    style.WindowPadding = imgui.ImVec2(4.0, 4.0)
    -- style.WindowMinSize =
    style.FramePadding = imgui.ImVec2(2.5, 3.5)
    -- style.ItemInnerSpacing =
    -- style.TouchExtraPadding =
    -- style.IndentSpacing =
    -- style.ColumnsMinSpacing = ?
    style.ButtonTextAlign = imgui.ImVec2(0.02, 0.4)
    -- style.DisplayWindowPadding =
    -- style.DisplaySafeAreaPadding =
    -- style.AntiAliasedLines =
    -- style.AntiAliasedShapes =
    -- style.CurveTessellationTol =
    colors[clr.Text]                   = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.TextDisabled]           = ImVec4(0.50, 0.50, 0.50, 1.00)
    colors[clr.WindowBg]               = imgui.ImColor(20, 20, 20, 255):GetVec4()
    colors[clr.ChildWindowBg]          = ImVec4(1.00, 1.00, 1.00, 0.00)
    colors[clr.PopupBg]                = ImVec4(0.08, 0.08, 0.08, 0.94)
    colors[clr.ComboBg]                = colors[clr.PopupBg]
    colors[clr.Border]                 = imgui.ImColor(40, 142, 110, 90):GetVec4()
    colors[clr.BorderShadow]           = ImVec4(0.00, 0.00, 0.00, 0.00)
    colors[clr.FrameBg]                = imgui.ImColor(40, 142, 110, 113):GetVec4()
    colors[clr.FrameBgHovered]         = imgui.ImColor(40, 142, 110, 164):GetVec4()
    colors[clr.FrameBgActive]          = imgui.ImColor(40, 142, 110, 255):GetVec4()
    colors[clr.TitleBg]                = imgui.ImColor(40, 142, 110, 236):GetVec4()
    colors[clr.TitleBgActive]          = imgui.ImColor(40, 142, 110, 236):GetVec4()
    colors[clr.TitleBgCollapsed]       = ImVec4(0.05, 0.05, 0.05, 0.79)
    colors[clr.MenuBarBg]              = ImVec4(0.14, 0.14, 0.14, 1.00)
    colors[clr.ScrollbarBg]            = ImVec4(0.02, 0.02, 0.02, 0.53)
    colors[clr.ScrollbarGrab]          = imgui.ImColor(40, 142, 110, 236):GetVec4()
    colors[clr.ScrollbarGrabHovered]   = ImVec4(0.41, 0.41, 0.41, 1.00)
    colors[clr.ScrollbarGrabActive]    = ImVec4(0.51, 0.51, 0.51, 1.00)
    colors[clr.CheckMark]              = ImVec4(1.00, 1.00, 1.00, 1.00)
    colors[clr.SliderGrab]             = ImVec4(0.28, 0.28, 0.28, 1.00)
    colors[clr.SliderGrabActive]       = ImVec4(0.35, 0.35, 0.35, 1.00)
    colors[clr.Button]                 = imgui.ImColor(35, 35, 35, 255):GetVec4()
    colors[clr.ButtonHovered]          = imgui.ImColor(35, 121, 93, 174):GetVec4()
    colors[clr.ButtonActive]           = imgui.ImColor(44, 154, 119, 255):GetVec4()
    colors[clr.Header]                 = imgui.ImColor(40, 142, 110, 255):GetVec4()
    colors[clr.HeaderHovered]          = ImVec4(0.34, 0.34, 0.35, 0.89)
    colors[clr.HeaderActive]           = ImVec4(0.12, 0.12, 0.12, 0.94)
    colors[clr.Separator]              = colors[clr.Border]
    colors[clr.SeparatorHovered]       = ImVec4(0.26, 0.59, 0.98, 0.78)
    colors[clr.SeparatorActive]        = ImVec4(0.26, 0.59, 0.98, 1.00)
    colors[clr.ResizeGrip]             = imgui.ImColor(40, 142, 110, 255):GetVec4()
    colors[clr.ResizeGripHovered]      = imgui.ImColor(35, 121, 93, 174):GetVec4()
    colors[clr.ResizeGripActive]       = imgui.ImColor(44, 154, 119, 255):GetVec4()
    colors[clr.CloseButton]            = ImVec4(0.41, 0.41, 0.41, 0.50)
    colors[clr.CloseButtonHovered]     = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.CloseButtonActive]      = ImVec4(0.98, 0.39, 0.36, 1.00)
    colors[clr.PlotLines]              = ImVec4(0.61, 0.61, 0.61, 1.00)
    colors[clr.PlotLinesHovered]       = ImVec4(1.00, 0.43, 0.35, 1.00)
    colors[clr.PlotHistogram]          = ImVec4(0.90, 0.70, 0.00, 1.00)
    colors[clr.PlotHistogramHovered]   = ImVec4(1.00, 0.60, 0.00, 1.00)
    colors[clr.TextSelectedBg]         = ImVec4(0.26, 0.59, 0.98, 0.35)
    colors[clr.ModalWindowDarkening]   = ImVec4(0.10, 0.10, 0.10, 0.35)
end
apply_custom_style()

local imBool = imgui.ImBool(false)
local imBool2 = imgui.ImBool(false)
local imBool3 = imgui.ImBool(false)
local imBool4 = imgui.ImBool(false)

function imgui.OnDrawFrame()
    local iScreenWidth, iScreenHeight = getScreenResolution()
    local tLastKeys = {}
 
   imgui.SetNextWindowPos(imgui.ImVec2(iScreenWidth / 2, iScreenHeight / 2), imgui.Cond.FirstUseEver, imgui.ImVec2(0.5, 0.5))
   imgui.SetNextWindowSize(imgui.ImVec2(400, 200), imgui.Cond.FirstUseEver)
 
   imgui.Begin("Test Window", window)

    imgui.Text(u8("BOT"))
    imgui.SameLine(365)
    if imgui.ToggleButton("Test##1", imBool) then
        sampAddChatMessage("You change status, new status: " .. tostring(imBool.v), -1)
    end
    imgui.Text(u8("выход из игры если написал артурчик"))
    imgui.SameLine(365)
    if imgui.ToggleButton("Test2##2", imBool2) then zvuk(imBool2.v) end
    imgui.Text(u8("работа в свёрнутом режиме"))
    imgui.SameLine(365)
    if imgui.ToggleButton("Test2##3", imBool3) then aafk(imBool3.v) end
    imgui.Text(u8("ДИМОООН если написал одмен"))
    imgui.SameLine(365)
    imgui.ToggleButton("Test2##4", imBool4)

   imgui.End()
 
end

function aafk(check)
    local memory = require "memory"
    if check then
        writeMemory(7634870, 1, 1, 1)
        writeMemory(7635034, 1, 1, 1)
        memory.fill(7623723, 144, 8)
        memory.fill(5499528, 144, 6)
        sampAddChatMessage('{1E90FF}[AntiAFK]: {FFFFFF}Включен!', 0xFF5000)
        addOneOffSound(0, 0, 0, 1058)
    else
        writeMemory(7634870, 1, 0, 0)
        writeMemory(7635034, 1, 0, 0)
        memory.hex2bin('5051FF1500838500', 7623723, 8)
        memory.hex2bin('0F847B010000', 5499528, 6)
        sampAddChatMessage('{1E90FF}[AntiAFK]: {FFFFFF}Отключен!', 0xFF5000)
    end
end

function zvuk(check)
            if text:find("Вы тут?") or text:find("Вы тут") or text:find("Вы здесь") or text:find("Вы здесь?") or text:find("вы тут?") or text:find("вы тут") or text:find("вы здесь") or text:find("вы здесь?") or text:find("в ы з д е с ь?") or text:find("вы бот?")  or text:find("вы бот") or text:find("Вы бот?") then
            if not doesFileExist("moonloader/sound.mp3") then
            notf.addNotification("Ошибка! Вы не установили звук sound.mp3!", 8, 1)
            addOneOffSound(0.0, 0.0, 0.0, 1138)
            zvuk.v = false
        else
      local pusk = loadAudioStream("moonloader/sound.mp3")
      setAudioStreamVolume(pusk, 80)
  setAudioStreamState(pusk, 1)
    end
end
Помогите сделать звуковое оповещание когда написал админ. Конец когда в чём то ошибка
 

Вложения

  • testing (1).lua
    7.4 KB · Просмотры: 5
Последнее редактирование:

ensam

Новичок
6
0
Всем привет. Есть вопрос, как реализовать передвижение сиджея (нормальное) ?
Много гуглил, но так и не справился с задачей. BeginToPoint у меня не работает, мб потому что я не импортировал какую то библиотеку, или просто не обьявил эту функцию.Вставил ее с бот мейкера, да, она работает, но камера дергается в направлении, да и разве она должна дергатся?
Есть такая функция
Lua:
taskCharSlideToCoord(ped, toX, toY, toZ, angle, withinRadius)
Она работает замечательно, сиджей разворачивается, не дергаясь идет по координатам. Но он идет бесконечно, и идет (не спринт, не бег), так вот, есть что-то похожее только с более обширным функционалом? (Задать спринт хотя бы)
 

Wisadop

Потрачен
145
49
Обратите внимание, пользователь заблокирован на форуме. Не рекомендуется проводить сделки.
как получить координаты хп/армор бара?
Вот тебе код
Код:
require "lib.moonloader"
requests = require('requests')

local city = {
    [0] = "Village",
    [1] = "Los-Santos",
    [2] = "San-Fierro",
    [3] = "Las-Venturas"
}
local sampev = require 'lib.samp.events'
local active = true
local mem = require 'memory'
local main_color = 0xFFFFFF
local tag = "{FFD700}[INFOBAR]:"
local keys = require 'vkeys'
local playsec = 0
local playmin = 0
local playhours = 0
local tables
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage(tag .. " {00FF00}Успешно Загружен!", 0xFFD700)
    sampAddChatMessage(tag .. " Разработчик: {00FF00}NoNameCoder, {FFD700}он же - {00FF00}NNC.", 0xFFD700)
    sampAddChatMessage(tag .. " {00FF00}NoNameCoder {FFD700}на {A9A9A9}Blast{1E90FF}Hack: {00FF00}blast.hk/members/173523/", 0xFFD700)
    imgui.ShowCursor = false
    imgui.SetMouseCursor(-1)

    while true do
        wait(1000)
            playsec = playsec + 1
            if playsec == 60 and playmin then
                playmin = playmin + 1
                playsec = 0
            end
            if playmin == 60 then
                playhours = playhours + 1
                playmin = 0
            end
        if main_window_state.v == false then
        imgui.Process = true
        end
    end
end

function cmd_imgui(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v or show_2_window.v
end

function imgui.OnDrawFrame()
    if not isCharInAnyCar(PLAYER_PED) then
        imgui.SetNextWindowPos(imgui.ImVec2(430, 824), imgui.Cond.FirstUseEver)
        imgui.ShowCursor = false
        imgui.SetMouseCursor(-1)
        _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        server = sampGetCurrentServerName(PLAYER_HANDLE)
        ip = sampGetCurrentServerAddress(PLAYER_PED)
        weap = getCurrentCharWeapon(PLAYER_PED)
        weaponid = getWeapontypeModel(weap)
        ammo = getAmmoInCharWeapon(PLAYER_PED, weap)
        nick = sampGetPlayerNickname(id)
        fFps = mem.getfloat(0xB7CB50, 4, false)   
        ping = sampGetPlayerPing(id)
        time = (os.date("%H",os.time())..':'..os.date("%M",os.time())..':'..os.date("%S",os.time()))
        date = (os.date("%d",os.time())..'/'..os.date("%m",os.time())..'/'..os.date("%Y",os.time()))
        Health = getCharHealth(PLAYER_PED)
        Armor = getCharArmour(PLAYER_PED)
        Level = sampGetPlayerScore(id)
        pspeed = getCharSpeed(PLAYER_PED)
        x,y,z = getCharCoordinates(PLAYER_PED)
        Hours = (os.date("%H", os.time()))
        Minuts = (os.date("%M", os.time()))
        Seconds = (os.date("%S", os.time()))
        imgui.Begin("INFOBAR | Coded by NNC.", window, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.ShowBorders)
        imgui.Text("Server: " .. server, main_color)
        imgui.Text("NickName: " .. nick ..  " | ID: " .. id, main_color)
        imgui.Text("Ping: " .. ping .. " | Level: " .. Level .. " | FPS: " .. math.floor(fFps), main_color)
        imgui.Text("Time: " .. time .. " | Date: " .. date, main_color)
        imgui.Text("City: " .. city[getCityPlayerIsIn(PLAYER_HANDLE)] .. " | PlayerTime: " .. playhours .. ":" .. playmin .. ":" .. playsec, main_color)
        imgui.Text("Health: " .. Health .. " | Armour: " .. Armor .. " | Speed: " .. math.floor(pspeed), main_color)
        imgui.Text("Weapon: " .. weap.. " | Ammo: " .. ammo, main_color)
        imgui.Text("X: " .. math.floor(x) .. " | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z), main_color)
        imgui.End()
    else
        imgui.SetNextWindowPos(imgui.ImVec2(430, 824), imgui.Cond.FirstUseEver)
        imgui.ShowCursor = false
        imgui.SetMouseCursor(-1)
        _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        car = storeCarCharIsInNoSave(playerPed)
        carmodel = getCarModel(car)
        carname = getGxtText(getNameOfVehicleModel(carmodel))
        _, cid = sampGetVehicleIdByCarHandle(car)
        carhp = getCarHealth(car)
        cspeed = getCarSpeed(car)
        server = sampGetCurrentServerName(PLAYER_HANDLE)
        ip = sampGetCurrentServerAddress(PLAYER_PED)
        nick = sampGetPlayerNickname(id)
        fFps = mem.getfloat(0xB7CB50, 4, false)   
        ping = sampGetPlayerPing(id)
        time = (os.date("%H",os.time())..':'..os.date("%M",os.time())..':'..os.date("%S",os.time()))
        date = (os.date("%d",os.time())..'/'..os.date("%m",os.time())..'/'..os.date("%Y",os.time()))
        Health = getCharHealth(PLAYER_PED)
        Armor = getCharArmour(PLAYER_PED)
        Hours = (os.date("%H", os.time()))
        Minuts = (os.date("%M", os.time()))
        Seconds = (os.date("%S", os.time()))
        Level = sampGetPlayerScore(id)
        x,y,z = getCharCoordinates(PLAYER_PED)
        imgui.Begin("INFOBAR | Coded by NNC.", window, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.ShowBorders)
        imgui.Text("Server: " .. server, main_color)
        imgui.Text("NickName: " .. nick ..  " | ID: " .. id, main_color)
        imgui.Text("Ping: " .. ping .. " | Level: " .. Level .. " | FPS: " .. math.floor(fFps), main_color)
        imgui.Text("Time: " .. time .. " | Date: " .. date, main_color)
        imgui.Text("City: " .. city[getCityPlayerIsIn(PLAYER_HANDLE)] .. " | PlayerTime: " .. playhours .. ":" .. playmin .. ":" .. playsec, main_color)
        imgui.Text("Health: " .. Health .. " | Armour: " .. Armor .. " | Speed: " .. math.floor(cspeed * 2.5), main_color)
        imgui.Text("CarHP: " .. carhp .. " | CarID: " .. cid .. " | CarType: " .. carmodel, main_color)
        imgui.Text("X: " .. math.floor(x) .. " | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z), main_color)
        imgui.End()   
    end
end
 

trefa

Известный
Всефорумный модератор
2,097
1,231
Вот тебе код
Код:
require "lib.moonloader"
requests = require('requests')

local city = {
    [0] = "Village",
    [1] = "Los-Santos",
    [2] = "San-Fierro",
    [3] = "Las-Venturas"
}
local sampev = require 'lib.samp.events'
local active = true
local mem = require 'memory'
local main_color = 0xFFFFFF
local tag = "{FFD700}[INFOBAR]:"
local keys = require 'vkeys'
local playsec = 0
local playmin = 0
local playhours = 0
local tables
local imgui = require 'imgui'
local encoding = require 'encoding'
encoding.default = 'CP1251'
u8 = encoding.UTF8

local main_window_state = imgui.ImBool(false)
local text_buffer = imgui.ImBuffer(256)

function main()
    if not isSampLoaded() or not isSampfuncsLoaded() then return end
    while not isSampAvailable() do wait(100) end
    sampAddChatMessage(tag .. " {00FF00}Успешно Загружен!", 0xFFD700)
    sampAddChatMessage(tag .. " Разработчик: {00FF00}NoNameCoder, {FFD700}он же - {00FF00}NNC.", 0xFFD700)
    sampAddChatMessage(tag .. " {00FF00}NoNameCoder {FFD700}на {A9A9A9}Blast{1E90FF}Hack: {00FF00}blast.hk/members/173523/", 0xFFD700)
    imgui.ShowCursor = false
    imgui.SetMouseCursor(-1)

    while true do
        wait(1000)
            playsec = playsec + 1
            if playsec == 60 and playmin then
                playmin = playmin + 1
                playsec = 0
            end
            if playmin == 60 then
                playhours = playhours + 1
                playmin = 0
            end
        if main_window_state.v == false then
        imgui.Process = true
        end
    end
end

function cmd_imgui(arg)
    main_window_state.v = not main_window_state.v
    imgui.Process = main_window_state.v or show_2_window.v
end

function imgui.OnDrawFrame()
    if not isCharInAnyCar(PLAYER_PED) then
        imgui.SetNextWindowPos(imgui.ImVec2(430, 824), imgui.Cond.FirstUseEver)
        imgui.ShowCursor = false
        imgui.SetMouseCursor(-1)
        _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        server = sampGetCurrentServerName(PLAYER_HANDLE)
        ip = sampGetCurrentServerAddress(PLAYER_PED)
        weap = getCurrentCharWeapon(PLAYER_PED)
        weaponid = getWeapontypeModel(weap)
        ammo = getAmmoInCharWeapon(PLAYER_PED, weap)
        nick = sampGetPlayerNickname(id)
        fFps = mem.getfloat(0xB7CB50, 4, false)  
        ping = sampGetPlayerPing(id)
        time = (os.date("%H",os.time())..':'..os.date("%M",os.time())..':'..os.date("%S",os.time()))
        date = (os.date("%d",os.time())..'/'..os.date("%m",os.time())..'/'..os.date("%Y",os.time()))
        Health = getCharHealth(PLAYER_PED)
        Armor = getCharArmour(PLAYER_PED)
        Level = sampGetPlayerScore(id)
        pspeed = getCharSpeed(PLAYER_PED)
        x,y,z = getCharCoordinates(PLAYER_PED)
        Hours = (os.date("%H", os.time()))
        Minuts = (os.date("%M", os.time()))
        Seconds = (os.date("%S", os.time()))
        imgui.Begin("INFOBAR | Coded by NNC.", window, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.ShowBorders)
        imgui.Text("Server: " .. server, main_color)
        imgui.Text("NickName: " .. nick ..  " | ID: " .. id, main_color)
        imgui.Text("Ping: " .. ping .. " | Level: " .. Level .. " | FPS: " .. math.floor(fFps), main_color)
        imgui.Text("Time: " .. time .. " | Date: " .. date, main_color)
        imgui.Text("City: " .. city[getCityPlayerIsIn(PLAYER_HANDLE)] .. " | PlayerTime: " .. playhours .. ":" .. playmin .. ":" .. playsec, main_color)
        imgui.Text("Health: " .. Health .. " | Armour: " .. Armor .. " | Speed: " .. math.floor(pspeed), main_color)
        imgui.Text("Weapon: " .. weap.. " | Ammo: " .. ammo, main_color)
        imgui.Text("X: " .. math.floor(x) .. " | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z), main_color)
        imgui.End()
    else
        imgui.SetNextWindowPos(imgui.ImVec2(430, 824), imgui.Cond.FirstUseEver)
        imgui.ShowCursor = false
        imgui.SetMouseCursor(-1)
        _, id = sampGetPlayerIdByCharHandle(PLAYER_PED)
        car = storeCarCharIsInNoSave(playerPed)
        carmodel = getCarModel(car)
        carname = getGxtText(getNameOfVehicleModel(carmodel))
        _, cid = sampGetVehicleIdByCarHandle(car)
        carhp = getCarHealth(car)
        cspeed = getCarSpeed(car)
        server = sampGetCurrentServerName(PLAYER_HANDLE)
        ip = sampGetCurrentServerAddress(PLAYER_PED)
        nick = sampGetPlayerNickname(id)
        fFps = mem.getfloat(0xB7CB50, 4, false)  
        ping = sampGetPlayerPing(id)
        time = (os.date("%H",os.time())..':'..os.date("%M",os.time())..':'..os.date("%S",os.time()))
        date = (os.date("%d",os.time())..'/'..os.date("%m",os.time())..'/'..os.date("%Y",os.time()))
        Health = getCharHealth(PLAYER_PED)
        Armor = getCharArmour(PLAYER_PED)
        Hours = (os.date("%H", os.time()))
        Minuts = (os.date("%M", os.time()))
        Seconds = (os.date("%S", os.time()))
        Level = sampGetPlayerScore(id)
        x,y,z = getCharCoordinates(PLAYER_PED)
        imgui.Begin("INFOBAR | Coded by NNC.", window, imgui.WindowFlags.NoTitleBar + imgui.WindowFlags.NoResize + imgui.WindowFlags.AlwaysAutoResize + imgui.WindowFlags.ShowBorders)
        imgui.Text("Server: " .. server, main_color)
        imgui.Text("NickName: " .. nick ..  " | ID: " .. id, main_color)
        imgui.Text("Ping: " .. ping .. " | Level: " .. Level .. " | FPS: " .. math.floor(fFps), main_color)
        imgui.Text("Time: " .. time .. " | Date: " .. date, main_color)
        imgui.Text("City: " .. city[getCityPlayerIsIn(PLAYER_HANDLE)] .. " | PlayerTime: " .. playhours .. ":" .. playmin .. ":" .. playsec, main_color)
        imgui.Text("Health: " .. Health .. " | Armour: " .. Armor .. " | Speed: " .. math.floor(cspeed * 2.5), main_color)
        imgui.Text("CarHP: " .. carhp .. " | CarID: " .. cid .. " | CarType: " .. carmodel, main_color)
        imgui.Text("X: " .. math.floor(x) .. " | Y: " .. math.floor(y) .. " | Z: " .. math.floor(z), main_color)
        imgui.End()  
    end
end
И где тут получение координат? Что за рандомный вброс, вопрос читайте.
 

FBenz

Активный
328
40
Сделать переменную глобальной или объявить локальной в глобальной области.
Lua:
local var = 1
function main()
    whie true do
        var = 322
        wait(0)
    end
end
function callbackCmd(param)
print(var)
end
Да я чет так и делал, а толку ноль, переменную не читает.
Lua:
settings = { -- В начале скрипта
 -- какие-то переменные и поля,
 get = {
  count = 1
 }
}
lua_thread.create(function()--Где-то внутри говнокода
while true do
   wait(0)
   if settings.func.dead and settings.thread.dead then
    wait(500)
     if settings.func.dead and settings.thread.dead then
      sampAddChatMessage('{6600ff}'..casefile.get.count) -- вот эту count и не считает, если убрать поток, все прекрасно работает (без цикла, конечно, ибо он не в меине)
      break
     end
   end
  end
end)
 

trefa

Известный
Всефорумный модератор
2,097
1,231
Да я чет так и делал, а толку ноль, переменную не читает.
Lua:
settings = { -- В начале скрипта
 -- какие-то переменные и поля,
 get = {
  count = 1
 }
}
lua_thread.create(function()--Где-то внутри говнокода
while true do
   wait(0)
   if settings.func.dead and settings.thread.dead then
    wait(500)
     if settings.func.dead and settings.thread.dead then
      sampAddChatMessage('{6600ff}'..casefile.get.count) -- вот эту count и не считает, если убрать поток, все прекрасно работает (без цикла, конечно, ибо он не в меине)
      break
     end
   end
  end
end)
Ты вообще другую таблицу берёшь
 

FBenz

Активный
328
40
Ты вообще другую таблицу берёшь
Я код забыл часть скинуть) Ща
Lua:
settings = { -- В начале скрипта
-- какие-то переменные и поля,
get = {
  count = 1
}
}

asyncHttpRequest('GET', "ссыль", nil,
  function(response)
  settings.func = lua_thread.create(function()
    if response.text ~= nil and response.text ~= '' then
     casefile.get.count = tonumber(response.text)
    else
     sampAddChatMessage('{6600FF}[FIA] Не удается посчитать количество кейс-файлов')
    end
  end)
  end,
  function(err)
     sampAddChatMessage('{6600FF}Нет связи')
  end)
 
  while true do
   wait(0)
   if settings.func.dead and settings.thread.dead then
    wait(500)
     if settings.func.dead and settings.thread.dead then
      sampAddChatMessage('{6600ff}Функция первого асинхрона: '..tostring(settings.func.dead)..' и '..casefile.get.count)
      break
     end
   end
  end

lua_thread.create(function()--Где-то внутри говнокода
while true do
   wait(0)
   if settings.func.dead and settings.thread.dead then
    wait(500)
     if settings.func.dead and settings.thread.dead then
      sampAddChatMessage('{6600ff}'..casefile.get.count) -- вот эту count и не считает, если убрать поток, все прекрасно работает (без цикла, конечно, ибо он не в меине)
      break
     end
   end
  end
end)