### Example Usage of Network Utilities (Lua) Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Networking API.md This snippet provides a concise example of how to call the primary network utility functions. It demonstrates running immediate connectivity tests, benchmarking DNS resolution, and starting the continuous network monitoring process. ```Lua NetworkUtils.run_connectivity_tests() NetworkUtils.benchmark_dns_resolution() NetworkUtils.start_monitoring() ``` -------------------------------- ### Setting Up Default Input Contexts and Bindings in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Input System API.md Demonstrates the initial setup of the input binding system. It creates default contexts like "default", "menu", and "inventory", and then binds specific keys (e.g., 'W' for 'move_forward') within the "default" context, providing a starting configuration for the system. ```Lua input_binding_system:create_context("default") input_binding_system:create_context("menu") input_binding_system:create_context("inventory") -- Default context bindings input_binding_system:bind_key("default", 87, "move_forward") -- W ``` -------------------------------- ### Basic Lua Bytecode Conversion Example (Bash) Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Lua to ByteCode.md An example demonstrating the basic usage of `luac.exe` to convert `hello.lua` into `hello.luac`, stripping debug information for a smaller output file. ```bash luac.exe -s -o hello.luac hello.lua ``` -------------------------------- ### Initializing JSON Best Practices and Naming Convention Example in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/JSON API.md This snippet initializes a Lua table to store JSON best practices examples and demonstrates the first guideline: using consistent, descriptive naming conventions for JSON fields, as shown with a 'user_profile' example. ```Lua -- Best practices for JSON structure and usage local json_best_practices = { examples = {} } -- 1. Use consistent naming conventions json_best_practices.examples.good_naming = { user_profile = { user_id = 12345, display_name = "PlayerOne", creation_date = "2024-01-15", last_login = "2024-01-20T10:30:00Z", preferences = { theme_name = "dark", language_code = "en", notifications_enabled = true } } } ``` -------------------------------- ### Initializing Example Game Features - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Process Functions.md This function sets up features specifically for 'Example Game'. It demonstrates reading the PE header from the process's base address, specifically checking for the `e_lfanew` offset and validating the NT headers' PE signature, logging the results. ```Lua function GameAttacher.initialize_example_game() engine.log("Setting up Example Game features...", 0, 255, 255, 255) -- Example: Read PE header local base_addr = proc.base_address() local e_lfanew = proc.read_int32(base_addr + 0x3C) if e_lfanew then engine.log("PE Header e_lfanew: 0x" .. string.format("%X", e_lfanew), 255, 255, 255, 255) -- Read NT headers local nt_signature = proc.read_int32(base_addr + e_lfanew) if nt_signature == 0x00004550 then -- "PE\0\0" engine.log("Valid PE signature found", 0, 255, 0, 255) else engine.log("Invalid PE signature: 0x" .. string.format("%X", nt_signature), 255, 255, 0, 255) end end end ``` -------------------------------- ### Example HTTP Client Usage in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Networking API.md This snippet demonstrates how to initialize the `HTTPClient` and send various types of HTTP requests: a GET request to GitHub, a POST request with form data to httpbin.org, and a POST request with JSON payload to JSONPlaceholder. ```Lua -- Initialize HTTP client HTTPClient.initialize() -- Example usage HTTPClient.send_get_request("https://api.github.com/users/octocat") HTTPClient.send_post_request("https://httpbin.org/post", "name=test&value=123") HTTPClient.send_json_request("https://jsonplaceholder.typicode.com/posts", '{"title":"Test","body":"Test content","userId":1}') ``` -------------------------------- ### Example Code Injection and Listing in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Process API.md This example demonstrates the process of finding a suitable code cave, injecting a simple shellcode (NOPs followed by a RET instruction), and then listing all active hooks to verify the injection. It requires the process to be attached. ```Lua if proc.is_attached() then -- Find a suitable location for code injection local code_cave = CodeInjector.find_code_cave("", 32) if code_cave then -- Example shellcode: NOP sled + return local example_shellcode = {0x90, 0x90, 0x90, 0x90, 0xC3} -- 4 NOPs + RET CodeInjector.inject_shellcode(code_cave, example_shellcode, "Example injection") -- List all active hooks CodeInjector.list_active_hooks() end end ``` -------------------------------- ### Example Game Configurations for Attachment in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Attach to a Process.md Provides example configurations for different games, demonstrating how to specify executable names, window classes, window titles, and anti-cheat types. These configurations are used by the `setup_game_attachment` function to define target processes. ```Lua -- Game configuration examples local game_configs = { { name = "Notepad", executable = "notepad.exe", window_class = "Notepad", window_title = nil, anticheat = "none" }, { name = "Protected Game", executable = "game.exe", window_class = "UnityWndClass", window_title = "Game Window", anticheat = "eac" } } ``` -------------------------------- ### Usage Examples for Mouse Pattern Creation - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Input System API.md Provides examples of how to create circular and square mouse movement patterns using the `auto_mouse` object's methods. These patterns can then be passed to `auto_mouse:execute_pattern` for animated mouse control. ```lua -- Usage local circle_pattern = auto_mouse:create_circle_pattern(50, 32) local square_pattern = auto_mouse:create_square_pattern(100) ``` -------------------------------- ### Demonstrating TimeCalculator Functions in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Time API.md This section provides examples of how to instantiate and use the `create_timer`, `create_event_scheduler`, and `analyze_time_periods` functions. It shows how to initialize a timer, schedule a reminder, and analyze a set of activity timestamps. ```Lua -- Usage examples local timer = TimeCalculator.create_timer(300) -- 5-minute timer print("Timer remaining: " .. timer.get_remaining() .. " seconds") print("Timer progress: " .. string.format("%.1f%%", timer.get_progress() * 100)) local scheduler = TimeCalculator.create_event_scheduler() scheduler.schedule_event("reminder", 60, function() print("Reminder: Check your progress!") end) -- Analyze user activity timestamps local activity_times = {time.unix() - 3600, time.unix() - 1800, time.unix() - 900, time.unix()} ``` -------------------------------- ### Usage Examples for String Operations in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Memory API.md This snippet provides examples of how to call the previously defined `StringOperations` functions. It demonstrates the full lifecycle of string handling, from demonstrating basic string operations to creating, reading, and freeing a string array. ```Lua -- Usage examples StringOperations.demonstrate_strings() local string_handle, offsets = StringOperations.create_string_array() if string_handle then local retrieved_strings = StringOperations.read_string_array(string_handle, offsets) MemoryManager.safe_free(string_handle) end ``` -------------------------------- ### Starting Gesture Recording in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Input System API.md Sets the `recording` flag to true, clears the `current_gesture` table, and records the `gesture_start_time` using `time.unix_ms()`. It also logs a message indicating that recording has begun. ```Lua function gesture_recognizer:start_recording() self.recording = true self.current_gesture = {} self.gesture_start_time = time.unix_ms() engine.log("Started gesture recording", 255, 255, 0, 255) end ``` -------------------------------- ### Finding and Analyzing Specific Applications in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Windows API.md This example demonstrates how to use the `window_finder` utility to locate a specific application, such as Notepad, by its class name. It logs a success message if the window is found, showcasing a practical application of the window finding capabilities. ```Lua function find_and_analyze_notepad() local hwnd = window_finder.find_by_class("Notepad") if hwnd then engine.log("Found Notepad window!", 0, 255, 0, 255) end end ``` -------------------------------- ### Initializing TimeTracker and Starting Sessions in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Time API.md This snippet initializes the `TimeTracker` module, setting up data structures for sessions and categories. It defines the `start_session` function, which creates a new active session with a unique ID, category, description, and tags, recording its start time and updating category tracking. ```Lua -- Time tracking and productivity analysis system local TimeTracker = { sessions = {}, categories = {}, session_id_counter = 1 } function TimeTracker.start_session(category, description, tags) local session_id = TimeTracker.session_id_counter TimeTracker.session_id_counter = TimeTracker.session_id_counter + 1 local session = { id = session_id, category = category, description = description or "", tags = tags or {}, start_time = time.unix(), end_time = nil, duration = 0, status = "active" } TimeTracker.sessions[session_id] = session -- Update category tracking if not TimeTracker.categories[category] then TimeTracker.categories[category] = { total_sessions = 0, total_time = 0, average_session = 0, last_session = nil } end TimeTracker.categories[category].last_session = time.unix() return session_id end ``` -------------------------------- ### Loading Bitmaps from Files and URLs in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/rendering API.md This example demonstrates how to load bitmap images into the application using `render.create_bitmap_from_file` for local assets and `render.create_bitmap_from_url` for images hosted online. It shows the basic usage to obtain bitmap handles. ```Lua -- Load bitmaps from different sources local logo_bitmap = render.create_bitmap_from_file("assets/logo.png") local avatar_bitmap = render.create_bitmap_from_url("https://example.com/avatar.jpg") ``` -------------------------------- ### Demonstrating Utility Function Usage in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Extended Math API.md Provides practical examples of how to call the previously defined functions, including `range_system` methods, `map_distance_to_volume`, `map_world_to_screen`, and `update_day_night_cycle`, with sample input values. This showcases the functions in action and their expected outputs. ```Lua -- Usage examples range_system.process_sensor_reading("Temperature", 72.5, 32, 100) range_system.process_sensor_reading("Pressure", 14.7, 0, 20) range_system.process_sensor_reading("Humidity", 65, 0, 100) range_system.display_sensor_dashboard() range_system.update_circular_angle("rotation", 45, 0, 360) range_system.update_circular_angle("rotation", 320, 0, 360) -- Should wrap map_distance_to_volume(15.5, 5, 50) local world_bounds = {min_x = -100, max_x = 100, min_y = -50, max_y = 50} local screen_bounds = {min_x = 0, max_x = 1920, min_y = 0, max_y = 1080} map_world_to_screen(25, -10, world_bounds, screen_bounds) update_day_night_cycle(14.5) -- 2:30 PM update_day_night_cycle(25.2) -- Wraps to 1:12 AM ``` -------------------------------- ### Initializing Game Attacher Module - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Process Functions.md This line represents the initial call to set up the `GameAttacher` module. It is typically executed once at the start of the application to prepare the module for managing game process attachments. ```Lua GameAttacher.initialize() ``` -------------------------------- ### Example Usage of MemoryEditor Bookmarks in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Process API.md Demonstrates how to create, read, and modify memory bookmarks using the `MemoryEditor` API. It shows setting up bookmarks for player health, score, and name, then reading their current values and updating numerical ones. ```Lua MemoryEditor.create_bookmark("player_health", proc.base_address() + 0x1000, "int32", "Player health points") MemoryEditor.create_bookmark("player_score", proc.base_address() + 0x1004, "int64", "Player score") MemoryEditor.create_bookmark("player_name", proc.base_address() + 0x2000, "string", "Player name") -- Read current values MemoryEditor.read_bookmark("player_health") MemoryEditor.read_bookmark("player_score") -- Modify values MemoryEditor.write_bookmark("player_health", 999) MemoryEditor.write_bookmark("player_score", 1000000) ``` -------------------------------- ### Example HTTP GET Request with SocketManager in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Networking API.md This example demonstrates how to use SocketManager.send_http_request to perform a GET request to httpbin.org. It includes custom headers and logs either a preview of the successful response or an error message if the request fails. ```Lua local response, error = SocketManager.send_http_request("httpbin.org", 80, "/get", "GET", { ["User-Agent"] = "LuaSocketClient/1.0", ["Accept"] = "application/json" }) if response then engine.log("HTTP response preview: " .. response:sub(1, 200), 255, 255, 255, 255) else engine.log("HTTP request failed: " .. error, 255, 0, 0, 255) end ``` -------------------------------- ### Lua String Search and Indexing Usage Examples Source: https://github.com/shadowthijs/perception-lua-api/blob/master/String API.md Demonstrates the usage of `analyze_text` to get word counts and positions, and `find_all_positions` to locate all occurrences of a substring within a sample text. It shows how to call these functions and the expected output. ```Lua -- Usage examples local sample_text = "The quick brown fox jumps over the lazy dog" local analysis = analyze_text(sample_text, "the") -- Result: {count = 2, first_position = 1, last_position = 32, found = true} local positions = find_all_positions("hello world hello", "hello") -- Result: {1, 13} ``` -------------------------------- ### Initializing Settings UI Panels in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Perception GUI API.md Sets up the main settings tab and creates various panels for different categories: General, UI Customization, Performance, and Configuration. It calls dedicated functions to populate each panel with specific UI elements, organizing the settings interface. ```Lua function SettingsManager.initialize() local settings_tab = gui.get_tab("settings") -- General settings panel local general_panel = settings_tab:create_panel("General Settings", false) SettingsManager.create_general_settings(general_panel) -- UI customization panel local ui_panel = settings_tab:create_panel("UI Customization", false) SettingsManager.create_ui_settings(ui_panel) -- Performance settings local perf_panel = settings_tab:create_panel("Performance", true) SettingsManager.create_performance_settings(perf_panel) -- Configuration management local config_panel = settings_tab:create_panel("Configuration", true) SettingsManager.create_config_management(config_panel) end ``` -------------------------------- ### Demonstrating Advanced Controls Usage - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Perception GUI API.md This Lua snippet illustrates the practical application of the `AdvancedControls` module. It initializes a UI panel and then demonstrates how to create a color scheme picker using `AdvancedControls.create_color_scheme_picker` with predefined UI colors. Subsequently, it sets up a keybind manager via `AdvancedControls.create_keybind_manager`, configuring two keybinds ('toggle_feature' and 'quick_action') with their respective labels, key codes, modes, actions, and descriptions. ```Lua -- Usage examples local panel = gui.get_ ``` -------------------------------- ### Calculating Business Days Between Dates in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Time API.md This snippet illustrates how to calculate the number of business days between two specified dates. It first determines a start date 30 days prior to the current date using `time.add_days` and then calls `DateManager.calculate_business_days` to get the count, which is then printed. This functionality depends on the `time` and `DateManager` modules. ```Lua local start_date = time.add_days(today, -30) -- 30 days ago local business_days = DateManager.calculate_business_days(start_date, today) print("Business days in last 30 days: " .. business_days) ``` -------------------------------- ### Drawing Gradient Lines with `render.draw_gradient_line` in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/rendering API.md This function draws a line with a gradient of colors. It requires start and end coordinates (`x1, y1, x2, y2`), a table of color values for the gradient (`color_table`), and a thickness. Examples demonstrate simple two-color, multi-color rainbow, and animated gradients, showcasing dynamic color generation. ```Lua -- Simple gradient line local gradient_colors = { {255, 0, 0, 255}, -- Red {0, 0, 255, 255} -- Blue } render.draw_gradient_line(100, 100, 300, 100, gradient_colors, 5) -- Rainbow gradient line local rainbow_colors = { {255, 0, 0, 255}, -- Red {255, 127, 0, 255}, -- Orange {255, 255, 0, 255}, -- Yellow {0, 255, 0, 255}, -- Green {0, 0, 255, 255}, -- Blue {75, 0, 130, 255}, -- Indigo {148, 0, 211, 255} -- Violet } render.draw_gradient_line(100, 200, 500, 200, rainbow_colors, 8) -- Animated gradient line function draw_animated_gradient_line(x1, y1, x2, y2, time) local colors = {} for i = 1, 5 do local hue = ((time * 50) + (i * 72)) % 360 local r, g, b = hsv_to_rgb(hue, 1, 1) table.insert(colors, {r*255, g*255, b*255, 255}) end render.draw_gradient_line(x1, y1, x2, y2, colors, 6) end ``` -------------------------------- ### Usage Examples for Lua Selection Managers Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Perception GUI API.md Demonstrates how to instantiate and use the `create_dynamic_selector` and `create_categorized_selection` functions. It shows how to create a panel, define dynamic options for a player selector, and set up categorized features with predefined items. This section illustrates the practical application of the `SelectionManager`. ```Lua -- Usage examples local panel = gui.get_tab("lua"):create_panel("Selection Controls", false) -- Dynamic options (e.g., available players, loaded configs, etc.) local player_selector = SelectionManager.create_dynamic_selector( panel, "Target Player", function() return {"Player1", "Player2", "Player3"} end, -- Dynamic provider "single" ) -- Categorized selection for features local feature_categories = { ["Visual Features"] = {"ESP", "Glow", "Crosshair", "Radar"}, ["Audio Features"] = {"Sound ESP", "Footsteps", "Voice Chat"}, } ``` -------------------------------- ### Implementing a Performance Profiler with winapi.get_tickcount64() in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Windows API.md This advanced example demonstrates how to build a simple performance profiler using `winapi.get_tickcount64()`. It allows starting and stopping timers for different operations and generates a report of elapsed times, useful for identifying performance bottlenecks in Lua applications. The profiler uses a table to store timers and results, logging output via `engine.log`. ```Lua -- Performance profiler local profiler = { timers = {}, results = {} } function profiler.start(name) profiler.timers[name] = winapi.get_tickcount64() end function profiler.stop(name) if profiler.timers[name] then local elapsed = winapi.get_tickcount64() - profiler.timers[name] profiler.results[name] = elapsed profiler.timers[name] = nil engine.log(string.format("Profile [%s]: %d ms", name, elapsed), 255, 165, 0, 255) return elapsed end return nil end function profiler.report() engine.log("=== Performance Report ===", 255, 255, 255, 255) for name, time in pairs(profiler.results) do engine.log(string.format(" %s: %d ms", name, time), 200, 200, 200, 255) end end -- Usage example profiler.start("database_query") -- ... perform database operation ... profiler.stop("database_query") profiler.start("file_processing") -- ... process files ... profiler.stop("file_processing") profiler.report() ``` -------------------------------- ### Setting Up Window Targets and Registering for Updates - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Windows API.md This snippet demonstrates how to register specific applications like Notepad and Calculator as targets for the `window_controller`. It also shows how to register the `update_targets` function with the `engine.register_on_engine_tick` callback to ensure continuous monitoring and control of these windows. ```Lua -- Setup and automation examples window_controller.add_target("notepad", "Notepad", nil) window_controller.add_target("calculator", nil, "Calculator") -- Register for updates engine.register_on_engine_tick(window_controller.update_targets) ``` -------------------------------- ### Demonstrating Good File Naming Conventions in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/File System API.md This snippet illustrates best practices for naming files in Lua applications. It shows examples of descriptive filenames, consistent naming conventions (e.g., `app_config.json`), and grouping related files with common prefixes, enhancing readability and maintainability. ```Lua -- Good file naming examples local files = { config = "app_config.json", user_data = "user_profile.dat", temp_cache = "temp_cache.tmp", error_log = "error_log.txt", backup = "backup_" .. time.format_custom(time.unix(), "%Y%m%d") .. ".bak" } ``` -------------------------------- ### Initializing and Demonstrating Settings Manager Usage in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/JSON API.md This snippet demonstrates the typical workflow for using the `settings_manager`. It initializes the manager, modifies several settings using `set_setting`, saves the current settings to a JSON string, loads them back, and then displays some of the retrieved settings using `engine.log`. ```Lua settings_manager:initialize() -- Modify some settings settings_manager:set_setting("graphics.quality", "medium") settings_manager:set_setting("audio.master_volume", 0.7) settings_manager:set_setting("controls.mouse_sensitivity", 3.0) -- Save settings local settings_json = settings_manager:save_to_json() -- Load settings back local test_load = settings_manager:load_from_json(settings_json) -- Display some settings engine.log("Graphics Quality: " .. tostring(settings_manager:get_setting("graphics.quality")), 0, 255, 255, 255) engine.log("Master Volume: " .. tostring(settings_manager:get_setting("audio.master_volume")), 0, 255, 255, 255) engine.log("Mouse Sensitivity: " .. tostring(settings_manager:get_setting("controls.mouse_sensitivity")), 0, 255, 255, 255) ``` -------------------------------- ### Examples of Lua Unicode String Operations Source: https://github.com/shadowthijs/perception-lua-api/blob/master/String API.md This snippet demonstrates the usage of the previously defined Unicode string handling functions ('process_international_text', 'utf8_truncate', 'utf8_safe_slice') with example Unicode text and shows their expected outputs. ```Lua -- Examples local unicode_text = "Hello δΈ–η•Œ! 🌍" local analysis = process_international_text(unicode_text) -- Result: {characters = 11, bytes = 17, is_ascii = false, text = "Hello δΈ–η•Œ! 🌍"} local truncated_unicode = utf8_truncate("γ“γ‚“γ«γ‘γ―δΈ–η•Œ", 5) -- Result: "こんにけは…" local safe_substring = utf8_safe_slice("CafΓ© β˜• Paris", 1, 4) -- Result: "CafΓ©" ``` -------------------------------- ### Lua String Transformation Usage Examples Source: https://github.com/shadowthijs/perception-lua-api/blob/master/String API.md Provides practical examples demonstrating the use of `sanitize_filename` to clean up a file name string and `is_palindrome` to check if a phrase is a palindrome. It shows the input and expected output for each function call. ```Lua -- Examples local safe_filename = sanitize_filename("My File: Version 2.0") -- "My_File-_Version_2.0" local is_pal = is_palindrome("A man a plan a canal Panama") -- true ``` -------------------------------- ### Demonstrating Data Compression and Storage with Lua `fs` Source: https://github.com/shadowthijs/perception-lua-api/blob/master/File System API.md This snippet provides a comprehensive example of using `fs.compress` and `fs.decompress` for data compression and an `fs`-based data storage system. It shows how to compress a string, calculate compression ratios, save compressed data to a file, and then decompress and load it back, verifying data integrity. It also includes a `DataStorage` module for saving and loading compressed data efficiently. ```Lua function demonstrate_compression() -- Create a large string with repetitive data local original_data = "" for i = 1, 1000 do original_data = original_data .. "This is repetitive data line " .. i .. "\n" end local original_size = string.len(original_data) engine.log("Original data size: " .. format_file_size(original_size), 255, 255, 255, 255) -- Compress the data local compressed_data = fs.compress(original_data) local compressed_size = string.len(compressed_data) -- Calculate compression ratio local ratio = (1 - (compressed_size / original_size)) * 100 engine.log("Compressed size: " .. format_file_size(compressed_size), 0, 255, 255, 255) engine.log("Compression ratio: " .. string.format("%.1f%%", ratio), 0, 255, 0, 255) -- Save compressed data fs.write_to_file("compressed_data.comp", compressed_data) -- Test decompression local decompressed_data = fs.decompress(compressed_data) local decompressed_size = string.len(decompressed_data) if decompressed_size == original_size then engine.log("Decompression successful!", 0, 255, 0, 255) else engine.log("Decompression failed!", 255, 0, 0, 255) end end -- Efficient data storage system local DataStorage = {} function DataStorage.save_compressed(filename, data) local compressed = fs.compress(data) fs.write_to_file(filename .. ".comp", compressed) local original_size = string.len(data) local compressed_size = string.len(compressed) local savings = original_size - compressed_size engine.log("Saved compressed: " .. format_file_size(savings) .. " saved", 0, 255, 0, 255) end function DataStorage.load_compressed(filename) local comp_filename = filename .. ".comp" if fs.does_file_exist(comp_filename) then local compressed_data = fs.read_from_file(comp_filename) if compressed_data then return fs.decompress(compressed_data) end } return nil end -- Usage example local large_config = generate_large_config_string() DataStorage.save_compressed("user_config", large_config) local loaded_config = DataStorage.load_compressed("user_config") if loaded_config then engine.log("Configuration loaded successfully", 0, 255, 0, 255) end ``` -------------------------------- ### Implementing a Configuration Manager with Lua `fs` Source: https://github.com/shadowthijs/perception-lua-api/blob/master/File System API.md This example demonstrates a robust `ConfigManager` module for handling application configuration files. It includes functions to load configuration from a file, save current configuration (with automatic backup), and restore from a backup. It utilizes `fs` functions like `does_file_exist`, `read_from_file`, `write_to_file`, and `get_file_size` for file operations, assuming JSON parsing/encoding utilities are available. ```Lua -- Comprehensive configuration management system local ConfigManager = { config_file = "app_config.json", backup_file = "app_config.backup", default_config = { version = "1.0", user_preferences = { theme = "dark", language = "en", auto_save = true }, system_settings = { max_log_size = 1024 * 1024, -- 1MB cache_duration = 3600, -- 1 hour debug_mode = false } } } function ConfigManager.load() if fs.does_file_exist(ConfigManager.config_file) then local content = fs.read_from_file(ConfigManager.config_file) if content and content ~= "" then engine.log("Configuration loaded from file", 0, 255, 0, 255) -- Parse JSON here (assuming JSON parser available) return parse_json(content) or ConfigManager.default_config end end engine.log("Using default configuration", 255, 255, 0, 255) return ConfigManager.default_config end function ConfigManager.save(config) -- Create backup of current config if fs.does_file_exist(ConfigManager.config_file) then local current_config = fs.read_from_file(ConfigManager.config_file) fs.write_to_file(ConfigManager.backup_file, current_config) engine.log("Configuration backed up", 0, 255, 255, 255) end -- Save new configuration local json_data = json_encode(config) -- Assuming JSON encoder available fs.write_to_file(ConfigManager.config_file, json_data) local file_size = fs.get_file_size(ConfigManager.config_file) engine.log("Configuration saved (" .. format_file_size(file_size) .. ")", 0, 255, 0, 255) end function ConfigManager.restore_backup() if fs.does_file_exist(ConfigManager.backup_file) then local backup_content = fs.read_from_file(ConfigManager.backup_file) fs.write_to_file(ConfigManager.config_file, backup_content) engine.log("Configuration restored from backup", 255, 255, 0, 255) return true end engine.log("No backup file available", 255, 0, 0, 255) return false end -- Initialize configuration system local app_config = ConfigManager.load() ``` -------------------------------- ### Finding All Substring Positions in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/String API.md This function iterates through a `text` to find all starting positions of a specified `pattern`. It uses `str.indexof` repeatedly, updating the search start position, and collects all found indices into a table. It returns a table of numerical indices. ```Lua -- Find and replace with position tracking function find_all_positions(text, pattern) local positions = {} local start = 1 while true do local pos = str.indexof(text, pattern, start) if pos == -1 or pos == 0 then break end table.insert(positions, pos) start = pos + 1 end return positions end ``` -------------------------------- ### Initializing and Testing APIClient (Lua) Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Networking API.md This block demonstrates the initialization of the `APIClient` and a series of test API calls. It initializes the client, then calls functions to retrieve multiple posts, a single post, all users, creates a new test post, and finally displays the client's statistics. ```Lua APIClient.initialize() APIClient.get_posts(5) APIClient.get_post(1) APIClient.get_users() APIClient.create_post("Test Post", "This is a test post created by Lua", 1) APIClient.get_stats() ``` -------------------------------- ### Example Usage of PatternScanner Module - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Process API.md This block demonstrates typical usage of the `PatternScanner` module. It first checks if a process is attached, then proceeds to scan specific modules (like `` and `kernel32.dll`) for predefined signatures such as 'push_ebp' and 'call_pattern'. It also shows how to verify the integrity of a previously added signature. ```Lua if proc.is_attached() then -- Scan for common patterns PatternScanner.scan_module_for_signature("", "push_ebp") PatternScanner.scan_module_for_signature("kernel32.dll", "call_pattern") -- Verify signature integrity PatternScanner.verify_signature_integrity("push_ebp") end ``` -------------------------------- ### Calculating Business Days in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Time API.md This function calculates the number of business days (non-weekend days) between a start and an end timestamp. It iterates day by day, checking if each day is a weekend using `time.is_weekend` and increments a counter. The timestamps are normalized to the start of their respective days. ```Lua -- Business day calculations function DateManager.calculate_business_days(start_timestamp, end_timestamp) local business_days = 0 local current = time.start_of_day(start_timestamp) local end_day = time.start_of_day(end_timestamp) while current <= end_day do if not time.is_weekend(current) then business_days = business_days + 1 end current = time.add_days(current, 1) end return business_days end ``` -------------------------------- ### Example Usage of Debugging Utilities in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Vec2, Vec3, Vec4 & Mat4 API.md This snippet provides examples of how to call the 'debug_vector', 'validate_vector', and 'debug_matrix' functions with typical inputs, demonstrating their application for inspecting player positions, velocities, camera directions, and world transformation matrices. ```Lua debug_vector(player.position, "Player Position", "POSITION") debug_vector(player.velocity, "Player Velocity", "VELOCITY") validate_vector(camera_forward, "Camera Forward", 1.0) -- Should be unit vector debug_matrix(transform_matrix, "World Transform") ``` -------------------------------- ### Rendering Basic and Outlined Text in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/rendering API.md This snippet demonstrates how to initialize fonts using `render.create_font` and then use `render.draw_text` to display simple text and text with an outline. It illustrates setting text position, color, and outline thickness and color. ```Lua -- Basic text rendering local main_font = render.create_font("arial", 24) local title_font = render.create_font("arial", 36) render.draw_text(main_font, "Hello World!", 100, 100, 255, 255, 255, 255, 0, 0, 0, 0, 0) -- Text with outline render.draw_text(title_font, "TITLE TEXT", 100, 50, 255, 255, 0, 255, 2, 0, 0, 0, 255) ``` -------------------------------- ### Example Usage of DataEncoder Functions in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Networking API.md This example demonstrates how to use the DataEncoder module's functions, including test_encoding_round_trip for verification, encode_base64 for encoding JSON data, and encode_credentials for creating basic authentication headers. Finally, it calls get_encoding_stats to display the accumulated operation statistics. ```Lua -- Example usage DataEncoder.test_encoding_round_trip() -- Encode some sample data local sample_json = '{\"user\":\"admin\",\"token\":\"abc123\",\"expires\":1234567890}' local encoded_json = DataEncoder.encode_base64(sample_json, "API token") -- Create basic auth header local auth_header = DataEncoder.encode_credentials("user", "password") -- Show statistics DataEncoder.get_encoding_stats() ``` -------------------------------- ### Using Descriptive Field Names in JSON for Clarity in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/JSON API.md This snippet illustrates the sixth guideline: using descriptive field names and avoiding abbreviations in JSON. It provides a 'good' example with clear names like 'total_playtime_seconds' and a 'bad' example with ambiguous abbreviations, highlighting the importance of readability. ```Lua -- 6. Use descriptive field names and avoid abbreviations json_best_practices.examples.descriptive_names = { -- Good: Clear and descriptive player_statistics = { total_playtime_seconds = 7200, enemies_defeated_count = 127, items_collected_count = 89, levels_completed_count = 5 }, -- Avoid: Abbreviated and unclear player_stats_bad = { tt = 7200, -- total time? ed = 127, -- enemies defeated? ic = 89, -- items collected? lc = 5 -- levels completed? } } ``` -------------------------------- ### Retrieving Predefined Application Tabs - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Perception GUI API.md This snippet demonstrates how to retrieve predefined application tabs using `gui.get_tab(name)`. It shows basic access to common tabs like "aimbot", "visuals", "lua", and "settings", and includes a `TabManager` utility wrapper for organized tab retrieval and initial UI configuration. The `create_config_ui` function illustrates how to iterate through configuration sections to create corresponding panels within a tab. ```Lua -- Basic tab access local aimbot_tab = gui.get_tab("aimbot") local visuals_tab = gui.get_tab("visuals") local lua_tab = gui.get_tab("lua") local settings_tab = gui.get_tab("settings") -- Tab utility wrapper local TabManager = {} function TabManager.get_tabs() return { aimbot = gui.get_tab("aimbot"), visuals = gui.get_tab("visuals"), lua = gui.get_tab("lua"), settings = gui.get_tab("settings") } end function TabManager.create_config_ui(tab_name, config_sections) local tab = gui.get_tab(tab_name) local panels = {} for section_name, widgets in pairs(config_sections) do panels[section_name] = tab:create_panel(section_name, false) -- Widget creation would continue here end return panels end ``` -------------------------------- ### Sending GET HTTP Requests in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Networking API.md The `send_get_request` function initiates an HTTP GET request to a specified URL. It allows for optional custom headers, defaulting to the client's predefined headers if none are provided. The function logs the request, tracks it in `active_requests` with its method and timestamp, and then uses `net.send_request` to dispatch it. ```Lua function HTTPClient.send_get_request(url, custom_headers) local headers = custom_headers or HTTPClient.default_headers engine.log("Sending GET request to: " .. url, 255, 255, 0, 255) -- Track the request HTTPClient.active_requests[url] = { method = "GET", sent_at = time.unix(), headers = headers } net.send_request(url, headers, nil) return true end ``` -------------------------------- ### Example Usage of Binary File Format Handler - Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Memory API.md This snippet demonstrates how to use the `BinaryFileFormat` functions to save and load game data. It defines a sample `game_save_data` table, then calls `create_file` to save it to 'savegame.dat', and subsequently `load_file` to retrieve the data, showcasing the full round-trip functionality. ```Lua local game_save_data = { player_name = "TestPlayer", level = 42, score = 123456, completed_levels = {1, 2, 3, 4, 5}, settings = { difficulty = "normal", sound_enabled = true, music_volume = 0.8 } } -- Save to binary format if BinaryFileFormat.create_file("savegame.dat", game_save_data) then -- Load it back local loaded_data = BinaryFileFormat.load_file("savegame.dat") ``` -------------------------------- ### Retrieving User Information and Preferences in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Registering Callbacks & Engine API.md This example defines a 'greet_user' function that retrieves the current user's username using 'engine.get_username()'. It logs a welcome message, performs personalized logging, and calls a 'load_user_preferences' function to handle user-specific configurations, demonstrating user-aware application logic. ```Lua function greet_user() local username = engine.get_username() if username and username ~= "" then log_info("Welcome, " .. username .. "!") -- Personalized logging engine.log("Session started for user: " .. username, COLORS.GREEN[1], COLORS.GREEN[2], COLORS.GREEN[3], COLORS.GREEN[4]) -- User-specific configuration load_user_preferences(username) else log_warning("Unable to retrieve username") end end function load_user_preferences(username) log_debug("Loading preferences for: " .. username) -- Load user-specific settings, themes, etc. end -- Call on script initialization greet_user() ``` -------------------------------- ### Implementing Game Mechanics with Vectors and Matrices in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Vec2, Vec3, Vec4 & Mat4 API.md This snippet provides practical game development examples demonstrating the application of vectors and matrices. It includes functions for updating player movement with physics (acceleration, friction), simulating projectile trajectories under gravity, and implementing a smooth camera follow system using linear interpolation and a look-at matrix. These examples showcase how mathematical concepts are applied in real-world game scenarios. ```Lua -- Player movement with physics local player = { position = vec3(0, 0, 0), velocity = vec3(0, 0, 0), speed = 10, friction = 0.95 } function update_player_movement(input_dir, delta_time) -- Convert 2D input to 3D direction local move_dir = vec3(input_dir.x, 0, input_dir.y):normalize() -- Apply acceleration local acceleration = move_dir * player.speed player.velocity = player.velocity + acceleration * delta_time -- Apply friction player.velocity = player.velocity * player.friction -- Update position player.position = player.position + player.velocity * delta_time engine.log("Player pos: (" .. player.position.x .. ", " .. player.position.y .. ", " .. player.position.z .. ")", 0, 255, 0, 255) end -- Projectile physics function simulate_projectile(start_pos, initial_velocity, gravity, time) local gravity_vec = vec3(0, -gravity, 0) local position = start_pos + initial_velocity * time + gravity_vec * (time * time * 0.5) local velocity = initial_velocity + gravity_vec * time return position, velocity end -- Camera follow system local camera = { position = vec3(0, 10, -10), target = vec3(0, 0, 0), offset = vec3(0, 5, -8), smoothness = 0.1 } function update_camera_follow(player_pos) local desired_pos = player_pos + camera.offset camera.position = camera.position:lerp(desired_pos, camera.smoothness) camera.target = camera.target:lerp(player_pos, camera.smoothness) -- Create view matrix local view_matrix = mat4.look_at(camera.position, camera.target, vec3(0, 1, 0)) engine.log("Camera updated", 128, 128, 255, 255) end ``` -------------------------------- ### Validating Timestamps and Ranges in Lua Source: https://github.com/shadowthijs/perception-lua-api/blob/master/Time API.md This snippet defines `TimeValidator.create_timestamp_validator()`, which returns an object with two functions: `validate_timestamp` and `validate_timestamp_range`. `validate_timestamp` checks if a given timestamp is valid, within a reasonable year range (1970-2100), and not excessively far in the future (50 years) or past (100 years). `validate_timestamp_range` validates both start and end timestamps individually and ensures the start timestamp precedes the end timestamp. It relies on external `time` library functions like `time.is_valid`, `time.unix`, and `time.year_month_day`. ```Lua -- Time validation and system information utilities local TimeValidator = {} function TimeValidator.create_timestamp_validator() return { validate_timestamp = function(timestamp) local is_valid = time.is_valid(timestamp) local validation_result = { is_valid = is_valid, timestamp = timestamp, errors = {} } if not is_valid then table.insert(validation_result.errors, "Invalid timestamp") return validation_result end -- Additional validation checks local current_time = time.unix() local year_components = time.year_month_day(timestamp) -- Check for reasonable year range if year_components.year < 1970 or year_components.year > 2100 then table.insert(validation_result.errors, "Year out of reasonable range") end -- Check if timestamp is too far in the future local years_in_future = (timestamp - current_time) / (365.25 * 24 * 3600) if years_in_future > 50 then table.insert(validation_result.errors, "Timestamp too far in the future") end -- Check if timestamp is too far in the past local years_in_past = (current_time - timestamp) / (365.25 * 24 * 3600) if years_in_past > 100 then table.insert(validation_result.errors, "Timestamp too far in the past") end validation_result.has_warnings = #validation_result.errors > 0 return validation_result end, validate_timestamp_range = function(start_timestamp, end_timestamp) local start_validation = TimeValidator.create_timestamp_validator().validate_timestamp(start_timestamp) local end_validation = TimeValidator.create_timestamp_validator().validate_timestamp(end_timestamp) local range_validation = { start_valid = start_validation.is_valid, end_valid = end_validation.is_valid, range_valid = false, errors = {} } -- Combine individual errors for _, error in ipairs(start_validation.errors) do table.insert(range_validation.errors, "Start: " .. error) end for _, error in ipairs(end_validation.errors) do table.insert(range_validation.errors, "End: " .. error) end -- Check range validity if start_validation.is_valid and end_validation.is_valid then if start_timestamp >= end_timestamp then table.insert(range_validation.errors, "Start timestamp must be before end timestamp") else range_validation.range_valid = true end end return range_validation end } end ```