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.

1

Learn Lua Basics

If you're new to Lua, start by understanding the fundamentals of the language

2

Explore the API

Familiarize yourself with the core modules and available functions

3

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 event
    callback function - Lua function to call when the event occurs
    event_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 event
    callback function - Lua function previously set with set_event_callback
    event_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 seconds
    callback function - Function to call
    ... - Additional parameters to pass to the callback
    delay 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 cmd
    cmd 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 msg
    msg 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 arguments
    r, g, b number - Цветовые компоненты RGB (0-255)
    message string - Сообщение для вывода
    ... - Дополнительные аргументы
  • client.error_log(message, ...) - Writes an error message to the console.Записывает сообщение об ошибке в консоль.
    message string - Error message
    ... - Additional arguments
    message 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 events
    userid 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 code
    key 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 player
  • entity.get_all(classname) - Returns all entities of the specified class
  • entity.get_players(enemies_only) - Returns all players
  • entity.get_prop(ent, propname) - Returns the value of an entity property
  • entity.set_prop(ent, propname, value) - Sets the value of an entity property
  • entity.is_enemy(ent) - Returns true if the entity is an enemy
  • entity.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 screen
    x, y number - Screen coordinates
    r, 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 render
    x, 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 measure
    flags 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 render
    r, g, b, a number - Компоненты цвета (0-255)
    ... string - Текст для отрисовки

Shape Rendering

  • renderer.rectangle(x, y, w, h, r, g, b, a) - Renders a rectangle
    x, y number - Top-left corner coordinates
    w, h number - Width and height
    r, 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 coordinates
    w, h number - Width and height
    r, 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 line
    xa, ya number - Start coordinates
    xb, yb number - End coordinates
    r, 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 coordinates
    w, h number - Width and height
    r1, g1, b1, a1 number - Start color
    r2, g2, b2, a2 number - End color
    horizontal 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 circle
    x, y number - Center coordinates
    r, g, b, a number - Color components (0-255)
    radius number - Circle radius
    start_degrees number - Starting angle in degrees
    percentage 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 thickness
    thickness 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 coordinates
    r, 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_png
    x, y number - Top-left corner coordinates
    w, h number - Width and height
    r, g, b, a number - Color components (0-255)
    id number - ID текстуры из renderer.load_svg или renderer.load_png
    x, 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 contents
    width, height number - Dimensions
    contents 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 contents
    width, height number - Dimensions
    contents 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 position
    x, y, z number - 3D world coordinates
    x, 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 checkbox
    tab string - Tab name (RAGE, AA, LEGIT, VISUALS, MISC, SKINS, PLAYERS, LUA)
    container string - Container name within the tab
    name string - Display name of the checkbox
    tab 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 slider
    min, max number - Minimum and maximum values
    init_value number - Initial value
    show_tooltip boolean - Whether to show the tooltip when dragging
    unit string - Unit to display after the value
    scale number - Scale for display value (0.1 = show values as 1/10th)
    tooltips table - Key-value pairs mapping slider values to tooltip strings
    min, 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 inline
    inline boolean - Отображать ли горячую клавишу встроенной
  • ui.new_button(tab, container, name, callback) - Creates a button
    callback function - Function to call when the button is clicked
    callback 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, LUA
    container string - Container name
    name string - Menu item name
    tab string - Название вкладки: RAGE, AA, LEGIT, VISUALS, MISC, SKINS, PLAYERS, LUA
    container string - Название контейнера
    name string - Название элемента меню
    Returns: number, ... - menu reference(s)
    Возвращает: number, ... - ссылка(и) на элемент меню
  • ui.set(item, value, ...) - Sets the value of a UI element
    item number - Menu reference from ui.new_* or ui.reference
    value any - Value to set
    ... - For multiselect, additional values
    item number - Ссылка на меню из ui.new_* или ui.reference
    value any - Значение для установки
    ... - Для мультивыбора, дополнительные значения
  • ui.get(item) - Gets the value of a UI element
    item number - Menu reference
    item 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 call
    item number - Ссылка на меню из ui.new_*
    callback function - Функция для вызова
  • ui.set_visible(item, visible) - Sets the visibility of a menu item.Устанавливает видимость элемента меню.
    item number - Menu reference
    visible boolean - Visibility state
    item 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 vector
    x, y, z number - Vector components
    x, y, z number - Компоненты вектора
    Returns: vector - A new vector object
    Возвращает: vector - Новый объект вектора
  • vector():unpack() - Unpacks the vector into x, y, z coordinates
    Returns: number, number, number - x, y, z components
    Возвращает: number, number, number - компоненты x, y, z

Vector Operations

  • vector():length() - Returns the length of the vector
    Returns: 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 vector
    other vector - Another vector
    other vector - Другой вектор
    Returns: number - Dot product result
    Возвращает: number - Результат скалярного произведения
  • vector():cross(other) - Returns the cross product with another vector
    other vector - Another vector
    other vector - Другой вектор
    Returns: vector - Cross product result
    Возвращает: vector - Результат векторного произведения
  • vector():normalized() - Returns the normalized vector
    Returns: vector - Normalized vector (length of 1 maintaining direction)
    Возвращает: vector - Нормализованный вектор (длина 1 с сохранением направления)
  • vector():lerp(other, percentage) - Performs linear interpolation between vectors.Выполняет линейную интерполяцию между векторами.
    other vector - Target vector
    percentage 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.

💬

Forums

Join discussions, ask questions, and share your scripts with the community.

Visit Forums
📖

Wiki

Contribute to the growing knowledge base of Gamesense Lua scripting.

Explore Wiki
🚀

Script Library

Browse and download community-created scripts for inspiration.

Browse Scripts