Master the Gamesense Lua API
A comprehensive guide for beginners, developers and enthusiasts to create powerful scripts for CS:GO
Documentation
Complete API reference
Code Examples
Practical snippets
Tools
Helpful utilities
Introduction to Gamesense Lua API
Gamesense Lua API provides a powerful framework for creating custom scripts and functionality within CS:GO. This guide will help you understand the fundamentals and capabilities of the API.
What is Gamesense Lua API?
Gamesense Lua API is a scripting interface that allows developers to extend the functionality of the Gamesense client for CS:GO. It provides access to game events, entity properties, rendering capabilities, and user interface elements.
Why Use Lua Scripts?
Lua scripts allow you to customize and extend the functionality of the Gamesense client to suit your specific needs. Create custom visualizations, automation tools, or entirely new features to enhance your gameplay experience.
Getting Started
To begin developing with Gamesense Lua API, you'll need to understand the core modules and libraries available. Let's explore the key components.
Learn Lua Basics
If you're new to Lua, start by understanding the fundamentals of the language
Explore the API
Familiarize yourself with the core modules and available functions
Create Your First Script
Start with a simple script following our examples
Core Libraries
Gamesense provides several essential libraries that extend your scripting capabilities. These libraries handle everything from UI elements to mathematical operations.
PUI (Perfect User Interface)
A library that enhances the built-in UI functionality with improved configuration systems, optimizations, and interface enhancements.
local pui = require("gamesense/pui")
Vector
Provides vector mathematics functionality essential for 3D operations in the game world. Create, manipulate and transform vectors with ease.
local vector = require("vector")
Clipboard
Interact with the system clipboard to copy or paste text.
local clipboard = require("gamesense/clipboard")
Base64
Encode and decode data using the Base64 encoding scheme.
local base64 = require("gamesense/base64")
Images
Load and manipulate images for use in your scripts.
local images = require("gamesense/images")
Safely Loading Libraries
Use this utility function to safely load libraries without causing errors if they're not available:
local function try_require(name, err_msg)
local status, lib = pcall(require, name)
if not status then
if err_msg ~= nil then
error(err_msg)
end
return nil
end
return lib
end
-- Example usage
local http = try_require("gamesense/http")
local ent = try_require("gamesense/entity")
API Modules
Gamesense Lua API provides several core modules for interacting with the game. These modules let you access game state, modify entities, render visuals, and create UI elements.
globals Module
Provides access to global game state and timing information. This module allows you to retrieve game time, frame information, and other essential timing data.
Functions for getting game globals such as the server time and map name.
Функции для получения глобальных игровых переменных, таких как серверное время и название карты.
-
globals.absoluteframetime()
- Returns the number of seconds passed during the last game frameВозвращает количество секунд, прошедших за последний игровой кадрReturns: number - seconds elapsed during the last game frameВозвращает: number - количество секунд, прошедших за последний игровой кадр -
globals.chokedcommands()
- Returns the number of choked commands, i.e. the number of commands that haven't yet been sent to the server.Возвращает количество задержанных команд, то есть количество команд, которые еще не были отправлены на сервер.Returns: number - number of choked commandsВозвращает: number - количество задержанных команд -
globals.commandack()
- Returns the command number of the most recent server-acknowledged command.Возвращает номер последней команды, подтвержденной сервером.Returns: number - command numberВозвращает: number - номер команды -
globals.curtime()
- Returns the game time in seconds (server synchronized)Возвращает игровое время в секундах (синхронизировано с сервером)Returns: number - game time in secondsВозвращает: number - игровое время в секундах -
globals.framecount()
- Returns the number of frames since the game started.Возвращает количество кадров с момента запуска игры.Returns: number - number of framesВозвращает: number - количество кадров -
globals.frametime()
- Returns the time elapsed during the last frameВозвращает время, прошедшее за последний кадр в секундахReturns: number - seconds elapsed during the last frameВозвращает: number - время, прошедшее за последний кадр в секундах -
globals.lastoutgoingcommand()
- Returns the command number of the last outgoing command.Возвращает номер последней исходящей команды.Returns: number - command numberВозвращает: number - номер команды -
globals.mapname()
- Returns the name of the loaded map, or nil if you are not in game.Возвращает название загруженной карты или nil, если вы не в игре.Returns: string - map nameВозвращает: string - название карты -
globals.maxplayers()
- Returns the maximum number of players in the server.Возвращает максимальное количество игроков на сервере.Returns: number - maximum number of playersВозвращает: number - максимальное количество игроков -
globals.oldcommandack()
- Returns the command number of the previous server-acknowledged command.Возвращает номер предыдущей команды, подтвержденной сервером.Returns: number - command numberВозвращает: number - номер команды -
globals.realtime()
- Returns the local time in secondsВозвращает локальное время в секундахReturns: number - local time in secondsВозвращает: number - локальное время в секундах -
globals.tickcount()
- Returns the number of ticks elapsed on the serverВозвращает количество тиков, прошедших на сервереReturns: number - number of ticksВозвращает: number - количество тиков, прошедших на сервере -
globals.tickinterval()
- Returns the time elapsed per game tick in secondsВозвращает время, прошедшее за один игровой тик в секундахReturns: number - seconds per tickВозвращает: number - время, прошедшее за один игровой тик в секундах
client Module
Provides functions to interact with the game client and events. This module is essential for responding to game events and executing commands.
The client module provides access to the game client, events, and general functions for interacting with the game and cheat client. It allows you to execute console commands, handle events, work with the user interface, and much more.
Модуль client предоставляет доступ к игровому клиенту, событиям и общим функциям взаимодействия с игрой и чит-клиентом. С его помощью можно выполнять консольные команды, обрабатывать события, работать с пользовательским интерфейсом и многое другое.
Event Handling
-
client.set_event_callback(event_name, callback)
- Sets a callback function for a game event. Used to respond to various in-game events.event_name string - The name of the eventcallback function - Lua function to call when the event occursevent_name string - Название событияcallback function - Lua функция для вызова при наступлении события -
client.unset_event_callback(event_name, callback)
- Removes a previously set event callback.Удаляет ранее установленный обработчик события.event_name string - The name of the eventcallback function - Lua function previously set with set_event_callbackevent_name string - Название событияcallback function - Lua функция, ранее установленная через set_event_callback -
client.delay_call(delay, callback, ...)
- Calls the callback function after the specified delay. Useful for scheduled actions.delay number - Delay in secondscallback function - Function to call... - Additional parameters to pass to the callbackdelay number - Задержка в секундахcallback function - Функция для вызова... - Дополнительные параметры для передачи в callback
Console and Logging
-
client.exec(cmd, ...)
- Executes a console command. Multiple commands can be combined with ';'.cmd string - Console command to execute... - Additional arguments to concatenate with cmdcmd string - Консольная команда для выполнения... - Дополнительные аргументы для конкатенации с cmd -
client.log(msg, ...)
- Logs a message to console in the [gamesense] format.Выводит сообщение в консоль в формате [gamesense].msg string - Message to output... - Additional arguments to concatenate with msgmsg string - Сообщение для вывода... - Дополнительные аргументы для конкатенации с msg -
client.color_log(r, g, b, message, ...)
- Logs a message to console with the specified color.r, g, b number - RGB color components (0-255)message string - Message to output... - Additional argumentsr, g, b number - Цветовые компоненты RGB (0-255)message string - Сообщение для вывода... - Дополнительные аргументы -
client.error_log(message, ...)
- Writes an error message to the console.Записывает сообщение об ошибке в консоль.message string - Error message... - Additional argumentsmessage string - Сообщение об ошибке... - Дополнительные аргументы
Player and Game Information
-
client.userid_to_entindex(userid)
- Converts a user ID to an entity index. Essential for working with game events.userid number - User ID, often provided by game eventsuserid number - ID пользователя, часто предоставляется игровыми событиямиReturns: number - entity index or 0 on failureВозвращает: number - индекс сущности или 0 при неудаче -
client.eye_position()
- Returns the local player's eye position in world coordinates.Возвращает позицию глаз локального игрока в мировых координатах.Returns: number, number, number - x, y, z coordinates in world spaceВозвращает: number, number, number - x, y, z координаты в мировом пространстве -
client.trace_line(skip_entindex, from_x, from_y, from_z, to_x, to_y, to_z)
- Performs a line trace between two points.Выполняет трассировку линии между двумя точками.Returns: number, number - fraction (0.0-1.0), entindexВозвращает: number, number - fraction (0.0-1.0), entindex -
client.trace_bullet(from_player, from_x, from_y, from_z, to_x, to_y, to_z, skip_players)
- Traces a bullet's path and checks for hits.Отслеживает путь пули и проверяет на попадания.Returns: number, number - entindex, damageВозвращает: number, number - entindex, damage
Rendering and Visualization
-
client.screen_size()
- Returns the width and height of the game window.Возвращает ширину и высоту окна игры.Returns: number, number - width, heightВозвращает: number, number - ширина, высота -
client.draw_hitboxes(entindex, duration, hitboxes, r, g, b, a, tick)
- Draws hitbox overlays for debugging.Отрисовывает хитбоксы для отладки. -
client.draw_debug_text(x, y, z, line_offset, duration, r, g, b, a, ...)
- Draws text in 3D space for debugging.Отрисовывает текст в 3D пространстве для отладки. -
client.register_esp_flag(flag, r, g, b, callback)
- Registers a custom ESP flag that will be shown when callback returns true.Регистрирует пользовательский флаг ESP, который будет показан, когда callback вернет true.
Utility Functions
-
client.latency()
- Returns your network latency in seconds.Возвращает сетевую задержку в секундах.Returns: number - latency in secondsВозвращает: number - задержка в секундах -
client.timestamp()
- Returns high precision timestamp in milliseconds.Возвращает высокоточную метку времени в миллисекундах.Returns: number - timestamp in millisecondsВозвращает: number - метка времени в миллисекундах -
client.unix_time()
- Returns current UNIX time (seconds since January 1, 1970).Возвращает текущее время UNIX (секунды с 1 января 1970 года).Returns: number - UNIX timeВозвращает: number - UNIX время -
client.system_time()
- Returns Windows system time as hours, minutes, seconds, milliseconds.Возвращает системное время Windows в часах, минутах, секундах, миллисекундах.Returns: number, number, number, number - hours, minutes, seconds, millisecondsВозвращает: number, number, number, number - часы, минуты, секунды, миллисекунды -
client.key_state(key)
- Returns true if the specified key is pressed.Возвращает true, если указанная клавиша нажата.key number - Virtual key codekey number - Виртуальный код клавишиReturns: booleanВозвращает: boolean -
client.random_int(minimum, maximum)
- Returns a random integer in the specified range.Возвращает случайное целое число в указанном диапазоне. -
client.random_float(minimum, maximum)
- Returns a random float in the specified range.Возвращает случайное число с плавающей точкой в указанном диапазоне.
Miscellaneous
-
client.set_clan_tag(...)
- Sets the player's clan tag. Empty string removes it.Устанавливает клан-тег игрока. Пустая строка удаляет его. -
client.reload_active_scripts()
- Reloads all active scripts on the next frame.Перезагружает все активные скрипты на следующем кадре. -
client.update_player_list()
- Updates the player list tab without having to open it.Обновляет вкладку списка игроков без необходимости её открытия. -
client.find_signature(module_name, pattern)
- Finds a pattern in a module and returns a pointer to it.Находит шаблон в модуле и возвращает указатель на него.
Pro Tip
Use client.set_event_callback("paint", function) to create continuous visual effects that update every frame.
entity Module
Provides functions to interact with game entities. This module allows you to get information about players, weapons, and other objects in the game world.
entity.get_local_player()
- Returns the entity index of the local playerentity.get_all(classname)
- Returns all entities of the specified classentity.get_players(enemies_only)
- Returns all playersentity.get_prop(ent, propname)
- Returns the value of an entity propertyentity.set_prop(ent, propname, value)
- Sets the value of an entity propertyentity.is_enemy(ent)
- Returns true if the entity is an enemyentity.is_alive(ent)
- Returns true if the entity is alive
renderer Module
Provides functions for rendering UI elements and visual effects on the screen. Use this module to draw shapes, text, and indicators.
The renderer module provides functions for drawing various UI elements and visual effects on the screen, such as text, shapes, and textures.
Модуль renderer предоставляет функции для отрисовки различных элементов интерфейса и визуальных эффектов на экране, таких как текст, фигуры и текстуры.
Text Rendering
-
renderer.text(x, y, r, g, b, a, flags, max_width, ...)
- Renders text on the screenx, y number - Screen coordinatesr, g, b, a number - Color components (0-255)flags string - Text flags: "+" (large), "-" (small), "c" (centered), "r" (right-aligned), "b" (bold), "d" (high DPI)max_width number - Maximum text width before wrapping... string - Text to renderx, y number - Координаты на экранеr, g, b, a number - Компоненты цвета (0-255)flags string - Флаги текста: "+" (большой), "-" (маленький), "c" (центрированный), "r" (по правому краю), "b" (жирный), "d" (высокий DPI)max_width number - Максимальная ширина текста перед переносом... string - Текст для отрисовки -
renderer.measure_text(flags, ...)
- Measures the dimensions of text without rendering it.Измеряет размеры текста без его отрисовки.flags string - Text flags (same as renderer.text)... string - Text to measureflags string - Флаги текста (как в renderer.text)... string - Текст для измеренияReturns: number, number - width, height of the textВозвращает: number, number - ширина и высота текста -
renderer.indicator(r, g, b, a, ...)
- Draws a cheat indicator.Отрисовывает индикатор чита.r, g, b, a number - Color components (0-255)... string - Text to renderr, g, b, a number - Компоненты цвета (0-255)... string - Текст для отрисовки
Shape Rendering
-
renderer.rectangle(x, y, w, h, r, g, b, a)
- Renders a rectanglex, y number - Top-left corner coordinatesw, h number - Width and heightr, g, b, a number - Color components (0-255)x, y number - Координаты верхнего левого углаw, h number - Ширина и высотаr, g, b, a number - Компоненты цвета (0-255) -
renderer.rectangle_outline(x, y, w, h, r, g, b, a)
- Renders the outline of a rectangle.Отрисовывает контур прямоугольника.x, y number - Top-left corner coordinatesw, h number - Width and heightr, g, b, a number - Color components (0-255)x, y number - Координаты верхнего левого углаw, h number - Ширина и высотаr, g, b, a number - Компоненты цвета (0-255) -
renderer.line(xa, ya, xb, yb, r, g, b, a)
- Renders a linexa, ya number - Start coordinatesxb, yb number - End coordinatesr, g, b, a number - Color components (0-255)xa, ya number - Начальные координатыxb, yb number - Конечные координатыr, g, b, a number - Компоненты цвета (0-255) -
renderer.gradient(x, y, w, h, r1, g1, b1, a1, r2, g2, b2, a2, horizontal)
- Renders a gradient rectangle.Отрисовывает градиентный прямоугольник.x, y number - Top-left corner coordinatesw, h number - Width and heightr1, g1, b1, a1 number - Start colorr2, g2, b2, a2 number - End colorhorizontal boolean - Gradient direction (true for horizontal)x, y number - Координаты верхнего левого углаw, h number - Ширина и высотаr1, g1, b1, a1 number - Начальный цветr2, g2, b2, a2 number - Конечный цветhorizontal boolean - Направление градиента (true для горизонтального) -
renderer.circle(x, y, r, g, b, a, radius, start_degrees, percentage)
- Renders a circlex, y number - Center coordinatesr, g, b, a number - Color components (0-255)radius number - Circle radiusstart_degrees number - Starting angle in degreespercentage number - Percentage of the circle to draw (0-1)x, y number - Координаты центраr, g, b, a number - Компоненты цвета (0-255)radius number - Радиус кругаstart_degrees number - Начальный угол в градусахpercentage number - Процент круга для отрисовки (0-1) -
renderer.circle_outline(x, y, r, g, b, a, radius, start_degrees, percentage, thickness)
- Renders a circle outline.Отрисовывает контур круга.thickness number - Outline thicknessthickness number - Толщина контура -
renderer.triangle(x0, y0, x1, y1, x2, y2, r, g, b, a)
- Renders a triangle.Отрисовывает треугольник.x0, y0, x1, y1, x2, y2 number - Triangle vertex coordinatesr, g, b, a number - Color components (0-255)x0, y0, x1, y1, x2, y2 number - Координаты вершин треугольникаr, g, b, a number - Компоненты цвета (0-255)
Texture and Image Rendering
-
renderer.texture(id, x, y, w, h, r, g, b, a)
- Renders a texture.Отрисовывает текстуру.id number - Texture ID from renderer.load_svg or renderer.load_pngx, y number - Top-left corner coordinatesw, h number - Width and heightr, g, b, a number - Color components (0-255)id number - ID текстуры из renderer.load_svg или renderer.load_pngx, y number - Координаты верхнего левого углаw, h number - Ширина и высотаr, g, b, a number - Компоненты цвета (0-255) -
renderer.load_svg(contents, width, height)
- Loads an SVG image.Загружает SVG изображение.contents string - SVG file contentswidth, height number - Dimensionscontents string - Содержимое SVG файлаwidth, height number - РазмерыReturns: number - texture IDВозвращает: number - ID текстуры -
renderer.load_png(contents, width, height)
- Loads a PNG image.Загружает PNG изображение.contents string - PNG file contentswidth, height number - Dimensionscontents string - Содержимое PNG файлаwidth, height number - РазмерыReturns: number - texture IDВозвращает: number - ID текстуры
Coordinate Transformation
-
renderer.world_to_screen(x, y, z)
- Converts a 3D position to a 2D screen positionx, y, z number - 3D world coordinatesx, y, z number - 3D координаты в мировом пространствеReturns: number, number - screen x, y coordinates or nil if the position is not visibleВозвращает: number, number - экранные координаты x, y или nil, если позиция не видна
ui Module
Provides functions for creating user interface elements. This module allows you to create interactive controls for your scripts.
The ui module allows you to create menu items, buttons, sliders and other UI elements. These elements can be used to create controls for your scripts and integrate them into the cheat's menu.
Модуль ui позволяет создавать элементы меню, кнопки, ползунки и другие элементы пользовательского интерфейса. Эти элементы можно использовать для создания элементов управления для ваших скриптов и интеграции их в меню чита.
Creating UI Elements
-
ui.new_checkbox(tab, container, name)
- Creates a new checkboxtab string - Tab name (RAGE, AA, LEGIT, VISUALS, MISC, SKINS, PLAYERS, LUA)container string - Container name within the tabname string - Display name of the checkboxtab string - Название вкладки (RAGE, AA, LEGIT, VISUALS, MISC, SKINS, PLAYERS, LUA)container string - Название контейнера внутри вкладкиname string - Отображаемое имя флажкаReturns: number - menu item referenceВозвращает: number - ссылка на элемент меню -
ui.new_slider(tab, container, name, min, max, init_value, show_tooltip, unit, scale, tooltips)
- Creates a slidermin, max number - Minimum and maximum valuesinit_value number - Initial valueshow_tooltip boolean - Whether to show the tooltip when draggingunit string - Unit to display after the valuescale number - Scale for display value (0.1 = show values as 1/10th)tooltips table - Key-value pairs mapping slider values to tooltip stringsmin, max number - Минимальное и максимальное значенияinit_value number - Начальное значениеshow_tooltip boolean - Показывать ли подсказку при перетаскиванииunit string - Единица измерения для отображения после значенияscale number - Масштаб для отображаемого значения (0.1 = показывать значения в 1/10)tooltips table - Пары ключ-значение, сопоставляющие значения слайдера со строками подсказок -
ui.new_combobox(tab, container, name, ...)
- Creates a dropdown list... string - Option strings... string - Строки вариантов -
ui.new_multiselect(tab, container, name, ...)
- Creates a multi-select dropdown.Создает выпадающий список с множественным выбором.... string - Option strings... string - Строки вариантов -
ui.new_hotkey(tab, container, name, inline)
- Creates a hotkey control element.Создает элемент управления горячими клавишами.inline boolean - Whether to display the hotkey inlineinline boolean - Отображать ли горячую клавишу встроенной -
ui.new_button(tab, container, name, callback)
- Creates a buttoncallback function - Function to call when the button is clickedcallback function - Функция, вызываемая при нажатии кнопки -
ui.new_color_picker(tab, container, name, r, g, b, a)
- Creates a color picker.Создает инструмент выбора цвета.r, g, b, a number - Initial color values (0-255)r, g, b, a number - Начальные значения цвета (0-255) -
ui.new_textbox(tab, container, name)
- Creates a text input box.Создает текстовое поле ввода.
Managing UI Elements
-
ui.reference(tab, container, name)
- Gets a reference to a built-in menu item.Получает ссылку на встроенный элемент меню.tab string - Tab name: RAGE, AA, LEGIT, VISUALS, MISC, SKINS, PLAYERS, LUAcontainer string - Container namename string - Menu item nametab string - Название вкладки: RAGE, AA, LEGIT, VISUALS, MISC, SKINS, PLAYERS, LUAcontainer string - Название контейнераname string - Название элемента менюReturns: number, ... - menu reference(s)Возвращает: number, ... - ссылка(и) на элемент меню -
ui.set(item, value, ...)
- Sets the value of a UI elementitem number - Menu reference from ui.new_* or ui.referencevalue any - Value to set... - For multiselect, additional valuesitem number - Ссылка на меню из ui.new_* или ui.referencevalue any - Значение для установки... - Для мультивыбора, дополнительные значения -
ui.get(item)
- Gets the value of a UI elementitem number - Menu referenceitem number - Ссылка на менюReturns: any - current valueВозвращает: any - текущее значение -
ui.set_callback(item, callback)
- Sets a function to be called when the menu item's value changes.Устанавливает функцию, которая будет вызываться при изменении значения элемента меню.item number - Menu reference from ui.new_*callback function - Function to callitem number - Ссылка на меню из ui.new_*callback function - Функция для вызова -
ui.set_visible(item, visible)
- Sets the visibility of a menu item.Устанавливает видимость элемента меню.item number - Menu referencevisible boolean - Visibility stateitem number - Ссылка на менюvisible boolean - Состояние видимости -
ui.update(item, value, ...)
- Updates a menu item's value without triggering its callbacks.Обновляет значение элемента меню без вызова его обратных вызовов.
vector Module
Provides vector mathematics functionality. This module is essential for working with positions and directions in 3D space.
The vector module provides functionality for creating and manipulating 3D vectors, which are essential for working with positions, angles, and directions in the game world.
Модуль vector предоставляет функциональность для создания и манипулирования 3D векторами, которые необходимы для работы с позициями, углами и направлениями в игровом мире.
Creating and Accessing Vectors
-
vector(x, y, z)
- Creates a new vectorx, y, z number - Vector componentsx, y, z number - Компоненты вектораReturns: vector - A new vector objectВозвращает: vector - Новый объект вектора -
vector():unpack()
- Unpacks the vector into x, y, z coordinatesReturns: number, number, number - x, y, z componentsВозвращает: number, number, number - компоненты x, y, z
Vector Operations
-
vector():length()
- Returns the length of the vectorReturns: number - Vector lengthВозвращает: number - Длина вектора -
vector():length2d()
- Returns the 2D length of the vector (x and y only)Returns: number - 2D length (ignoring z component)Возвращает: number - 2D длина (игнорируя компонент z) -
vector():dot(other)
- Returns the dot product with another vectorother vector - Another vectorother vector - Другой векторReturns: number - Dot product resultВозвращает: number - Результат скалярного произведения -
vector():cross(other)
- Returns the cross product with another vectorother vector - Another vectorother vector - Другой векторReturns: vector - Cross product resultВозвращает: vector - Результат векторного произведения -
vector():normalized()
- Returns the normalized vectorReturns: vector - Normalized vector (length of 1 maintaining direction)Возвращает: vector - Нормализованный вектор (длина 1 с сохранением направления) -
vector():lerp(other, percentage)
- Performs linear interpolation between vectors.Выполняет линейную интерполяцию между векторами.other vector - Target vectorpercentage number - Interpolation amount (0-1)other vector - Целевой векторpercentage number - Степень интерполяции (0-1)Returns: vector - Interpolated vectorВозвращает: vector - Интерполированный вектор
Vector Arithmetic
-
vector() + vector()
- Adds two vectors.Складывает два вектора.Returns: vector - Sum of vectorsВозвращает: vector - Сумма векторов -
vector() - vector()
- Subtracts two vectors.Вычитает два вектора.Returns: vector - Difference of vectorsВозвращает: vector - Разность векторов -
vector() * number
- Multiplies a vector by a scalar.Умножает вектор на скаляр.Returns: vector - Scaled vectorВозвращает: vector - Масштабированный вектор -
vector() / number
- Divides a vector by a scalar.Делит вектор на скаляр.Returns: vector - Scaled vectorВозвращает: vector - Масштабированный вектор
Examples
Learn how to use the Gamesense Lua API with practical examples. These code samples demonstrate common patterns and techniques for creating effective scripts.
Basic Script Structure
A simple script that displays an indicator when enabled:
-- Example basic script for Gamesense
-- Loading required libraries
local vector = require("vector")
local ent = try_require("gamesense/entity")
-- Creating UI elements
local enabled = ui.new_checkbox("LUA", "A", "Enable script")
local color = ui.new_color_picker("LUA", "A", "Indicator color", 76, 222, 128, 255)
-- Paint event handler
client.set_event_callback("paint", function()
-- Check if script is enabled
if not ui.get(enabled) then
return
end
-- Get local player
local local_player = entity.get_local_player()
-- Check if local player is alive
if not entity.is_alive(local_player) then
return
end
-- Get color from picker
local r, g, b, a = ui.get(color)
-- Draw indicator
renderer.indicator(r, g, b, a, "Example indicator")
end)
-- Shutdown event handler
client.set_event_callback("shutdown", function()
-- Cleanup resources here
print("Script unloaded")
end)
Simple Player ESP
A basic ESP (Extra Sensory Perception) script that draws boxes around players:
-- Simple ESP example
local enabled = ui.new_checkbox("LUA", "A", "Simple ESP")
local color_enemy = ui.new_color_picker("LUA", "A", "Enemy color", 255, 30, 30, 200)
local color_team = ui.new_color_picker("LUA", "A", "Team color", 30, 255, 30, 200)
client.set_event_callback("paint", function()
if not ui.get(enabled) then return end
local players = entity.get_players(false)
local local_player = entity.get_local_player()
for i=1, #players do
local player = players[i]
if entity.is_alive(player) and not entity.is_dormant(player) then
local x1, y1, x2, y2 = entity.get_bounding_box(player)
if x1 ~= nil and y1 ~= nil then
local is_enemy = entity.is_enemy(player)
local r, g, b, a = ui.get(is_enemy and color_enemy or color_team)
-- Draw box
renderer.rectangle_outline(x1, y1, x2-x1, y2-y1, r, g, b, a)
-- Draw name
local name = entity.get_player_name(player)
local text_width, text_height = renderer.measure_text("", name)
renderer.text(x1 + (x2-x1)/2 - text_width/2, y1 - text_height - 5, r, g, b, a, "", name)
end
end
end
end)
Auto Bunny Hop
A simple script that automatically jumps while holding space:
-- Auto bunny hop script
local enabled = ui.new_checkbox("MISC", "Movement", "Auto bunny hop")
client.set_event_callback("setup_command", function(cmd)
if not ui.get(enabled) then return end
local local_player = entity.get_local_player()
if not entity.is_alive(local_player) then return end
-- Check if player is on ground and space is pressed
local flags = entity.get_prop(local_player, "m_fFlags")
local on_ground = bit.band(flags, 1) == 1
if on_ground and cmd.in_jump then
cmd.in_jump = 0 -- Release jump to prepare for next jump
else
if cmd.in_jump then
cmd.in_jump = 0 -- Release jump in air
cmd.in_jump = 1 -- Press jump right before landing
end
end
end)
Useful Tips
Best practices for Gamesense Lua development. Follow these guidelines to create efficient, stable, and effective scripts.
Library Loading
Always use try_require for external libraries to avoid errors when they're missing. This ensures your script won't crash if a specific library isn't available.
Optimization
Optimize calls in the "paint" event as it's called every frame. Avoid complex calculations and unnecessary operations that could impact performance.
Event Callbacks
Use client.set_event_callback to subscribe to various game events. This allows your script to react to specific situations like player death, round start, or weapon firing.
Resource Cleanup
Ensure you free resources in the "shutdown" event handler. This prevents memory leaks and ensures a clean unload of your script.
Advanced Tips
Scope Variables
Use local variables whenever possible to improve performance and prevent global namespace pollution.
Cache Results
Cache results of expensive operations rather than recalculating them every frame.
Error Handling
Implement proper error handling with pcall to prevent your script from crashing.
Join the Community
Connect with other Gamesense Lua developers to share knowledge, get help, and collaborate on projects.