# LuaBNM > LuaBNM is an embedded Lua 5.1 runtime for Unity IL2CPP games on Android and VR (arm64). Scripts call any IL2CPP class, field, property and method by name, hook native methods with Lua callbacks, read XR controller input, send HTTP and HTTPS requests, parse JSON, read and write workspace files and raw memory. Docs: https://silenterased.github.io/BNMExplorer/ - the running mod serves this exact file at http://DEVICE_IP:8080/llms.txt This file documents every LuaBNM function, the runtime rules, the limits and the errors. Everything is written against the actual C++ source, so names and behavior match what runs inside the game. ## Writing scripts - rules for AI assistants (read before writing any code) Everything below applies to every script you write for LuaBNM. The examples at the end of this file show call patterns only. Never reuse their layout, names, colors or structure. ### Default script header Every script starts the same way: network setup first, then modules, then local state. ```lua http.set_ssl_verify(false) -- Modules local movements = require("mods/movements.lua") local visuals = require("mods/visuals.lua") local state = { menu_open = false, last_toggle = 0, } ``` Use snake_case for every name. Put one feature per module under `mods/`, and keep `main.lua` for wiring only. ### Do not copy the example Before writing a menu or a mod, decide these four things from the user's game and request, then write code that fits them: 1. Shape of the UI: wrist panel, floating board, ring around the hand, list on a wall. Pick one that suits the game. 2. Input: which controller button opens it and which one confirms. Read the game's own input class first. 3. Palette: take colors from the game's UI or ask the user. Do not default to a rainbow shift or to dark buttons with white text. 4. Names: new function names, new variable names, new file names. If your answer would look the same for two different games, it is a copy. Start again. ### Crash rules LuaBNM calls native code directly. A bad call kills the game, and the user has to relaunch and start over. Follow these every time. 1. Unity calls run on the main thread. Install `set_tick_hook` once at the top of `main.lua` and keep per-frame logic inside `on_update` or `every` callbacks that run after it. 2. Check every reference before use: `if not ref or not ref:is_valid() then return end`. Destroyed objects stay in Lua as dead references. 3. Never call `find_objects_of_type` or `scene.get_objects` every frame. Cache the result and refresh it at most every 2 seconds. 4. Skip inactive objects before reading their components: check `go.activeInHierarchy` and `continue` the loop body with an `if ... then` block. Lua 5.1 has no goto. 5. Wrap the body of every periodic callback in `pcall`. On failure print the error once and stop that task. A failing callback that keeps running floods the log and can crash the game. 6. Cache `find_class` and `get_method` results in locals at load time. Do not resolve names inside loops. 7. Read vectors once per frame into locals. Every `t.position` read builds a new table. 8. Do not call `http.request` on the main thread in a frame callback. Use `http.get_async` or `http.post_async`. 9. While developing, run `dev.debug_pcall(true)` so swallowed errors show up, and test risky calls inside `dev.guard(fn)`. It returns `false, message` on a native fault instead of killing the game. `dev.guard_calls` is on by default - keep it on while testing, turn it off in hot paths after a caught fault: the game state may be damaged, so restart the game before trusting it again. 10. Never write to a field or call a method on an object you found by walking a class dump. Confirm the class, the member name and the parameter types with `ref:list_members()` first. Safe periodic loop: ```lua local function safe_every(seconds, fn) local failed = false return every(seconds, function() if failed then return end local ok, err = pcall(fn) if not ok then failed = true print("task stopped: " .. tostring(err)) end end) end ``` ### Positioning, distances and rotation Most broken menus come from mixing world space and local space. Use this model and the math stays small. Parent every button, label and icon to one `panel_root` object. Set their positions with `localPosition`. Move or rotate only `panel_root` in world space. Children follow, so the distance from the menu to a button is a fixed local offset and never needs a world calculation. Grid layout in local units (meters): ```lua local function slot_position(col, row, cols, pitch_x, pitch_y, top_y) local x = (col - (cols - 1) / 2) * pitch_x local y = top_y - row * pitch_y return vec3(x, y, -0.005) end ``` - `pitch_x = button_width + gap`, `pitch_y = button_height + gap`. - Panel height = `rows * pitch_y + 2 * padding`. Panel width = `cols * pitch_x + 2 * padding`. - `top_y = panel_height / 2 - padding - button_height / 2`. - A face that reads correctly looks along local +Z. Put children at negative local Z (`-0.005` and smaller) so they sit between the panel and the viewer. Positive Z hides them behind the panel. - A world-space canvas with scale `0.001` makes one canvas unit equal one millimeter. A 300 x 80 button is then 0.3 m x 0.08 m. Do the arithmetic in the same unit for sizes and gaps. Facing the player. Text and canvases are readable from the side opposite their forward direction, so aim them away from the camera: ```lua local quaternion_class = find_class("UnityEngine.Quaternion") local function face_away_from(root_transform, camera_transform) local direction = root_transform.position - camera_transform.position direction.y = 0 if direction:length() < 0.001 then return end root_transform.rotation = quaternion_class.LookRotation(direction:normalized(), vec3(0, 1, 0)) end ``` `LookRotation(target - camera)` is correct. `LookRotation(camera - target)` mirrors the text. Zero the `y` component to keep the panel upright, and skip the update when the vector is near zero. Placing in front of a hand or head. Take the source transform, move along its forward and up axes, and never add raw world offsets: ```lua local function point_in_front(source_transform, forward_distance, up_offset) local origin = source_transform.position local forward = source_transform.forward local up = source_transform.up return origin + forward * forward_distance + up * up_offset end ``` Hit test for a poke or a ray. Convert the touch point into panel space, then compare against the button rectangle: ```lua local function button_hit(panel_transform, world_point, center, half_w, half_h, depth) local local_point = panel_transform:InverseTransformPoint(world_point) return math.abs(local_point.x - center.x) <= half_w and math.abs(local_point.y - center.y) <= half_h and math.abs(local_point.z - center.z) <= depth end ``` Keep `depth` between 0.02 and 0.04 for a finger poke. Smaller values miss fast hands. If the hand transform returns nil, print `ref.class_name` of the candidate object and search for a child named like the controller or anchor. Do not fall back to the world origin: the menu spawns at 0,0,0 and looks invisible. ### Reading the game before writing code 1. `find_class("Namespace.Class", "Assembly-CSharp.dll")` and `:dump()` the classes that matter. Read real field names and types. 2. Search for the singleton or the player class first: `Instance`, `Player`, `Manager`, `LocalPlayer`. 3. Read a value, print it, and only then write to it. 4. Hook one method, log its arguments, and build the feature from what you saw. 5. Keep each mod in its own module and return a table with `enable`, `disable` and `update` functions. `main.lua` calls them. ## Runtime facts - Language: Lua 5.1. Numbers are doubles, no integer type, no goto, no bitwise operators (use `bit`). - Standard libraries are open except these removed globals: `dofile`, `loadfile`, `module`, `package`, `io`, `os`, `debug`, `newproxy`, `gcinfo`. - One persistent Lua state. Globals and closures survive between Runs until Reset. - Chunk timeout: 5 seconds. Scheduler callback timeout: 1 second per call. A timeout raises "script timeout". - `print` joins values with tabs. Returned chunk values print one per line. - Errors are "SyntaxError: ..." (compile) or "RuntimeError: ..." with line and traceback (runtime). A scheduled task error prints `TaskError (task N): ...` and kills that task. `main_thread` errors print `MainThreadError: ...`, async http callback errors print `AsyncCallbackError: ...`, hook callback errors print "[Hook N Class::Method] ..." and the original method runs. - With `dev.debug_pcall(true)` every `pcall` that catches an error logs `PcallError: ...` to the output and logcat. - Output also lands in a log file on the device that survives a game crash: `dev.log_path()` gives the path, `dev.log_clear()` wipes it. The async output buffer caps at 65536 characters, oldest lines drop first. - Running a new file stops all tasks from the previous run, disables hook callbacks (trampolines stay installed and forward to the original methods) and clears the module cache. Threads: - A chunk started with Run executes on the Unity main thread by default, which makes Unity calls from top level code safe. - Scheduler callbacks (`every`, `after`, `on_update`, `on_game_start`) run on a background worker thread by default. Many Unity calls survive that, some crash. Install `set_tick_hook` or set `dev.main_tasks(true)` to move task callbacks onto the main thread. ## require(module_name) Workspace modules work through `require`: ```lua local movements = require("movements.lua") local utils = require("lib.utils") local init = require("lib/init.lua") ``` - Dots become folder separators: `"lib.utils"` loads `lib/utils.lua`. A name ending in `.lua` is used as is. A folder name loads `folder/init.lua`. - A module runs once per Run and its return value is cached. A module that returns nothing gets `true`. Circular require raises an error. - Each Run clears the module cache, so edits apply on the next Run. ## Value conversion between Lua and IL2CPP Method arguments convert by the declared IL2CPP parameter type. Return values convert back the same way. - `bool` - Lua boolean. - `int8..uint64, float, double, char, IntPtr` - Lua number. Enums are plain numbers. For `int64` and `uint64` pass a decimal or `0x` hex STRING when the value can exceed 2^53 (`self.ID = "28973212732379415"`), Lua doubles round past that. - `string` - Lua string. nil gives a null string, a null string comes back as nil. - `Vector2/3/4, Quaternion, Color` - tables from `vec2`, `vec3`, `vec4`, `quat`, `color`. Any table with `x, y, z, w` or `r, g, b, a` number fields is accepted too. - Object parameters - a reference, nil for null, or a string (converted to a managed string). - Other value types (structs) - pass a boxed struct reference or a raw address. Struct returns come back boxed and readable: ```lua local bounds = some_collider.bounds print(bounds.center.x, bounds.size.y) ``` - `ref` / `out` parameters arrive as raw addresses; use `memory.read*` / `memory.write*` on them. - Void methods return nothing. Overloads are picked by argument count first, then by types. A wrong count raises "method 'Name' expects N arguments, got M". Struct fields and struct returns are boxed IL2CPP objects. Reading `boxed.field` works, writing works, and struct field reads box a copy - assign through the owning object when you want to change the owner: ```lua local t = some_object.transform local p = t.localPosition p.y = p.y + 1 t.localPosition = p ``` ## Vectors, quaternions and colors Constructors: - `vec2(x, y) -> vector` - `vec3(x, y, z) -> vector` - `vec4(x, y, z, w) -> vector` - `quat(x, y, z, w) -> quaternion` - missing values default to 0 except w which defaults to 1 - `color(r, g, b, a) -> color` - missing values default to 0 except a which defaults to 1 Fields: `x, y, z, w` on vectors and quats, `r, g, b, a` on colors. The tables are mutable. Operators, component-wise with the shorter operand deciding the result length: `a + b`, `a - b`, `a * b`, `a / b` (division by zero gives 0), `vector * number`, `number * vector`, `vector / number`, `-a`, `a == b`. `tostring(v)` gives `(x, y, z)`. Methods: `v:length()`, `v:normalized()` (a zero vector stays zero), `v:dot(other)`, `v:distance(other)`. ```lua local dir = (target_pos - hand_pos):normalized() local half_red = color(1, 0, 0, 0.5) ``` ## Object references `find_class`, `wrap`, component lookups, method returns and field reads give back reference userdata. A reference stores a class and, for instances, an object pointer protected by a GC handle, so the object cannot be collected while Lua holds it. A class reference (from `find_class`) has no instance and reads as the static side. Special members on every reference: - `ref.addr -> number` - object address, 0 for class references - `ref.class_name -> string`, `ref.full_name -> string` - `ref:is_valid() -> boolean` - `ref:get_class() -> class reference` - `ref:get_field(name) -> value`, `ref:set_field(name, value)` - `ref:get_method(name, [argc]) -> method handle` - `ref:get_component(type)`, `ref:add_component(type)`, `ref:get_component_in_children(type)` - `ref:destroy([delay_seconds])` - `ref:find_objects() -> table` - all live objects of this class - `ref:new(...) -> reference` - constructs an instance, picking the `.ctor` overload by arguments - `ref:debug_info() -> string` - reflection sugar: `ref:list_methods([filter, inherited])`, `ref:list_fields()`, `ref:list_properties()`, `ref:list_members()`, `ref:list_parents()`, `ref:list_interfaces()`, `ref:list_nested()`, `ref:class_info()`, `ref:dump()` The `type` argument of the component functions is a full class name string like `"UnityEngine.Rigidbody"` or a class reference. Everything else is looked up by member name on the class and its parents: - Properties: `ref.Name` reads through the getter, `ref.Name = value` writes through the setter. - Fields: `ref.Name` reads, `ref.Name = value` writes. - Methods: `ref:Name(args)` for instance methods, `ref.Name(args)` for statics. - Unknown names raise "member 'Name' not found". References compare with `==` when they point at the same object. `tostring(ref)` gives `Namespace.Class`. ```lua local player = game_object.Find("GorillaPlayer") local body = player:get_component("UnityEngine.Rigidbody") body.velocity = vec3(0, 10, 0) player.transform.localScale = vec3(1.5, 1.5, 1.5) local pos = player.transform.position print(pos.x, pos.y, pos.z) ``` ### is_valid(value) -> boolean - nil -> false - non-reference values -> true - reference with an unresolved class -> false (`find_class` returns such a reference when the class does not exist) - instance reference -> true only when the pointer is plausible and, for UnityEngine.Object subclasses, `m_CachedPtr` is non-null. Destroyed Unity objects return false. Check `is_valid` before touching objects that can be destroyed at any time. ### type_name(value) -> string reference -> full class name, method handle -> "method", vector or color table -> "vec", anything else -> the Lua type name. ### wrap(address) -> reference or nil Casts a numeric address into a reference after plausibility checks on the pointer and its class pointer. Returns nil when the address looks invalid. ### find_class(full_name, [assembly_name]) -> class reference Looks up a class by namespace-qualified name. The text after the last dot is the class name, the rest is the namespace. The optional assembly name restricts the lookup, for example "Assembly-CSharp.dll". Results are cached. A missing class does not raise - the returned reference is just invalid. ```lua local photon = find_class("Photon.Pun.PhotonNetwork") if is_valid(photon) then photon.Disconnect() end ``` ### has_class(full_name, [assembly_name]) -> boolean True when the class exists right now. Use it instead of assuming a class survived stripping. ### assembly(name) Assembly-scoped lookups: - `assembly(name):namespace(ns):class(class_name, [address]) -> reference` - wraps `address` instead of looking up when a nonzero address is given - `assembly(name):class(full_class_name, [address]) -> reference` ```lua local player_class = assembly("Assembly-CSharp.dll"):namespace("GorillaLocomotion"):class("Player") ``` ### Method handles `ref:get_method(name, [argc]) -> handle` returns a method bound to that reference's instance. Class references give static handles. A missing method gives an invalid handle. - `handle(args...)` or `handle:invoke(args...)` - calls the method - `handle:is_valid()`, `handle:get_name()`, `handle:get_param_count()`, `handle:get_return_type()` - `handle:set_instance(ref_or_nil)` - rebinds the instance, nil for static ```lua local method = player:get_method("Awake", 0) if method:is_valid() then method() end ``` ### get_builtin_resource(type, path) -> reference or nil Loads a built-in Unity resource through `UnityEngine.Resources.GetBuiltinResource`. Common font paths: "Arial.ttf", "LegacyRuntime.ttf". ```lua local font = get_builtin_resource("UnityEngine.Font", "LegacyRuntime.ttf") ``` ## Scene queries - `scene.get_objects() -> table` - every live `UnityEngine.GameObject`. Cache it, never call per frame. - `scene.find_object(name) -> reference or nil` - `GameObject.Find`, active objects only - `scene.find_objects_of_type(type) -> table` - references of that class - `scene.SomeName` or `scene["Some Name"]` - shorthand for `find_object` - `find_object(name)` and `find_objects_of_type(type)` exist as globals too - `destroy(object_or_address, [delay_seconds])` - `UnityEngine.Object.Destroy`, also `ref:destroy([delay])` ```lua local camera = scene["Main Camera"] for _, body in ipairs(find_objects_of_type("UnityEngine.Rigidbody")) do print(body.gameObject.name) end destroy(camera, 2.0) ``` ## Scheduler and the main thread All timed callbacks share one task list. Every task has a numeric id. - `on_update(fn) -> id` - repeats every pump, zero interval - `every(seconds, fn) -> id` - repeats every N seconds, negatives clamp to 0 - `after(seconds, fn) -> id` - one shot after N seconds - `cancel(id) -> boolean`, `cancel_all()` - `get_time() -> number` - monotonic seconds, only differences are meaningful - `on_game_start(fn) -> id` - waits until the first Unity frame rendered (`Time.frameCount > 0`, checked every 0.25 s) and then runs `fn` once. Use it for code that needs a live scene. - `main_thread(fn)` - queues `fn` onto the Unity main thread. The queue is pumped from Unity frames once a frame hook exists; if none can be found the worker thread runs the callback after 3 seconds. Pumping: - By default a background worker thread pumps due tasks about every 8 ms. Unity API calls from that thread work for many things but can crash on others. - `set_tick_hook(full_class_name, method_name, [assembly_name]) -> boolean` installs a native hook on a zero argument void method (a game class Update or FixedUpdate for example). After it succeeds, tasks and the `main_thread` queue pump on the Unity main thread, throttled to once per 4 ms, and the background worker stops pumping. - Only one tick hook can exist and it cannot be removed. Guard it with `has_tick_hook()`. - Errors: "tick hook is already installed", "class 'X' not found", "method 'Y' without arguments not found", "method 'Y' must return void", "failed to hook 'Y'". - `dev.main_tasks(true)` moves all scheduler callbacks onto the main thread once frame hooks exist. - Re-running code manually inside one chunk stacks tasks - call `cancel_all()` first. ```lua if not has_tick_hook() then pcall(set_tick_hook, "GorillaLocomotion.Player", "FixedUpdate", "Assembly-CSharp.dll") end on_game_start(function() print("first frame", time.frameCount) end) main_thread(function() scene["Main Camera"].tag = "EditorOnly" end) ``` ## Native method hooks `hook_method(class_name, method_name, selector, callback, [assembly_name]) -> hook_id` Installs a native hook on a compiled IL2CPP method. The Lua callback runs synchronously on the calling thread of the hooked method. Lua state access is serialized with a mutex, so hooks and the console never run at the same time. The selector picks the overload: - a number - exact parameter count, not counting self - a string - signature like `"float,string"` using short type names (int, uint, long, ulong, short, ushort, byte, sbyte, float, bool map to their full names) - nil - only valid when exactly one overload exists When several overloads match, the error lists every candidate signature. Callback arguments: instance methods get `self` first, then the declared parameters. Statics get only their parameters. Booleans, integers and enums come as numbers, strings as Lua strings, objects as references, floats and doubles as numbers, `Vector2/3/4` and `Color` as vec tables, `ref`/`out` parameters as raw addresses (use `memory.read*` / `memory.write*` on them). Limits: at most 16 parameters and everything must fit the ARM64 calling convention registers (8 integer, self counts on instance methods, and 8 float; stack arguments are rejected). Struct parameters by value, generic methods and abstract bodies are rejected. Slot budget: 256 hooks for word sized returns (numbers, bools, enums, strings, objects, void), 48 hooks for `float`, `double`, `Vector2/3/4`, `Color` returns. Hooking the same address again replaces the callback and resets its call counter. Return behavior: - void method - return `true` or `"original"` to also run the original, return `false` or `nil` to skip it. - non-void method - return `nil` or `"original"` to run the original, return a compatible value to replace the result: numbers for numeric and enum returns, strings for string returns, references or strings for object returns (`{addr = 0x...}` for any pointer you built), vec tables for `Vector2/3/4` and `Color` returns (a color with 3 components gets alpha 1). - `HOOK_NULL` - a null reference for string and object returns. Management: - `unhook_method(hook_id) -> boolean` (alias `disable_method_hook`) - disables the callback, the trampoline stays and forwards to the original. - `unhook_all_methods() -> number` - disables every active callback, returns the count. - `has_method_hook(hook_id) -> boolean` - `hook_list() -> table` - array of `{id, name, active, calls}` - `get_hook(hook_id) -> table or nil` - `{id, name, active, calls, is_static, param_count, return_type, address}` - `set_hook_callback(hook_id, fn) -> boolean` - swaps the callback without reinstalling, resets the call counter and reactivates the hook - `hook_original(...)` - inside a callback, calls the original and returns its result. With no arguments it forwards the current arguments; pass replacements for any prefix of the arguments. - `hook_caller() -> string` - inside a callback, describes the caller (managed method or module+offset) A Lua error inside a callback prints "[Hook N Class::Method] error text" and the original method runs. ```lua local id = hook_method("PlayerHealth", "TakeDamage", "float", function(self, amount) print(hook_caller()) return hook_original(self, amount * 0.5) end) hook_method("GameManager", "GetPlayerName", 0, function(self) return "LuaPlayer" end) hook_method("CameraRig", "GetOffset", 0, function(self) return vec3(0, 2, -5) end) print(get_hook(id).return_type, hook_list()[1].calls) set_hook_callback(id, function(self, amount) return 0 end) ``` ## Networking `http.request(options) -> response` Blocking request. It blocks the calling thread for up to the timeout - on the main thread that freezes the game. Options table: - `url` - required, "http://" or "https://" - `method` - "GET" (default), "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS" - `headers` - table of strings - `body` - request body string - `content_type` - defaults to "application/octet-stream", a default User-Agent "LuaBNM" is always sent - `timeout` - seconds, default 10 - `follow_redirects` - default true - `verify` - per-request certificate check override, `ca_file` - per-request PEM bundle Successful response: `{ok = true, status, body, headers}` - headers maps lowercased names. Failed connection: `{ok = false, error, error_code}`. ``` http.get("http://10.0.0.5:9000/ping") -> { ok = true, status = 200, body = "pong", headers = { ["content-type"] = "text/plain" } } http.get("http://10.0.0.99:9000/ping") -> { ok = false, error = "Connection refused", error_code = 5 } ``` Certificate verification: - The bundled OpenSSL does not see the Android system CA store, so by default every https request fails with `SSL server verification failed` unless verification is off or a CA file is set. - `http.set_ssl_verify([enabled]) -> boolean` - get or set the global default. Call `http.set_ssl_verify(false)` first in every script; a request can override it with the `verify` field. - `http.set_ca_file([path]) -> boolean` - point verification at a PEM bundle. Relative paths resolve inside the workspace, so upload a `cacert.pem` (Mozilla bundle from curl.se) and call `http.set_ca_file("cacert.pem")` once per session. Call with no argument to clear. Shortcuts: - `http.get(url, [headers], [timeout]) -> response` - `http.post(url, [body], [headers], [content_type]) -> response` - a string body defaults the content type to "application/json" Async versions never block and never touch the game frame: `http.get_async(url, callback)`, `http.post_async(url, body, callback)`, `http.request_async(options, callback)`. They return `true` right away and `callback(response)` runs from the scheduler pump with the same response table. Errors before anything is sent (bad url, https without OpenSSL) raise immediately. ```lua http.set_ssl_verify(false) local r = http.get("https://raw.githubusercontent.com/some/repo/main/sounds.txt") local r2 = http.post("http://example.com/api/log", json.encode({name = "Lua", hp = 100})) if r2.ok then local data = json.decode(r2.body) print(data and data.name) end http.get_async("http://example.com/big.json", function(r3) if not r3.ok then print("download failed", r3.error) return end print("got", #r3.body, "bytes") end) ``` ## JSON - `json.encode(value) -> string` - Lua value to JSON. Sequential numeric keys become arrays, string keys become objects, nil drops the key, functions and userdata error. Avoid nil holes in arrays. - `json.decode(text) -> value, error` - JSON to Lua tables, arrays become 1-based, null becomes nil. Bad input returns nil plus an error message. - `json.stringify` / `json.parse` are aliases. ## Files The workspace holds files of any type: .lua scripts, .png textures, .json data, raw .bin blobs. - `fs.list([dir]) -> table` - array of `{path, name, dir, lua, size}` - `fs.read(path) -> string or nil, error` - raw bytes, binary safe - `fs.write(path, data) -> boolean` - writes bytes, creates parent folders, 1 MB limit - `fs.exists(path) -> boolean` - `fs.size(path) -> number` - errors when the file is missing - `fs.delete(path) -> boolean` - `fs.mkdir(path) -> boolean` Paths are workspace relative, `/` separated, no `..`, case sensitive. ```lua for _, e in ipairs(fs.list()) do print(e.path, e.size) end local png = fs.read("icon.png") local tex = find_class("UnityEngine.Texture2D"):new(2, 2, 4, false) tex:LoadImage(make_byte_array(png)) ``` `base64.encode(data_string) -> string`, `base64.decode(text) -> string` (stops at padding, ignores invalid characters). ## Memory Raw memory access by address. Reads probe the memory first and return nil when unreadable. Writes do not probe - a bad address will crash the game, that is on you. - `memory.read8/read16/read32/read64(addr) -> number or nil` - `memory.read_float(addr) -> number or nil`, `memory.read_double(addr) -> number or nil` - `memory.read_bytes(addr, length) -> string or nil` - up to 65536 bytes - `memory.read_string(addr, [max_length]) -> string or nil` - C string until a zero byte, default max 256 - `memory.write8/16/32/64(addr, value)`, `memory.write_float(addr, value)`, `memory.write_double(addr, value)` - `memory.write_bytes(addr, data_string)` - up to 65536 bytes - `memory.write_floats(addr, values) -> number` - bulk write, `values` is a table of numbers or a binary string whose length is a multiple of 4. One memcpy, so 40000 floats take microseconds. - `memory.read_floats(addr, count) -> table or nil` - bulk read, `{v1, v2, ...}`, count up to 1000000 - `memory.nop(addr, length) -> boolean` - fills whole instructions with ARM64 NOPs (1..1024 bytes), makes the page writable and clears the instruction cache Integer reads are signed, 64 bit values pass through doubles (precision to 2^53). ```lua local hp = memory.read32(0x7ABC1230) memory.write_float(0x7ABC1234, 99.5) memory.write_floats(0x7ABC1234, {0.5, 1, -1, 0.25}) local samples = memory.read_floats(arr.addr + 0x20, 48000) local name = memory.read_string(0x7ABC1240, 64) ``` ## bit Works on 64 bit values, results come back as doubles (precision to 2^53). - `bit.band(a, ...)`, `bit.bor(a, ...)`, `bit.bxor(a, ...)` - `bit.lshift(value, shift)`, `bit.rshift(value, shift)` (logical), `bit.arshift(value, shift)` (arithmetic), `bit.bnot(value)` ```lua local flags = bit.band(bit.bor(0x1, 0x4), 0xFF) ``` ## Binary data: string.pack and string.unpack Lua 5.1 has no packing, so LuaBNM adds it. The same functions exist as `pack.pack`, `pack.unpack` and as `string.pack`, `string.unpack`. Format characters: `<` little endian (default), `>` big endian, `x` one zero pad byte, `b`/`B` signed/unsigned byte, `h`/`H` 2 bytes, `i`/`I` 4 bytes or `i3`/`I5` style 1..8 bytes, `l`/`L` 8 bytes, `f` 4 byte float, `d` 8 byte double, `s` a 4 byte length followed by the string bytes. - `string.pack(fmt, ...) -> string` - `string.unpack(fmt, data, [init]) -> value..., next_position` ```lua local header = string.pack(" table` - `{Name = value}` for every constant - `enum_name(class, value) -> string or nil` ```lua local platform = enum_values("UnityEngine.RuntimePlatform") print(platform.WindowsPlayer, enum_name("UnityEngine.RuntimePlatform", 13)) ``` ## Reflection and search Search across every loaded assembly. All of these take an optional `path` filter shaped like `assembly/namespace/class` where each part is a partial case-insensitive match, and an optional `limit` (default 200, max 5000). A search text may use `Class::member` or `Class.member` to scope by class. The second return value is true when the result list hit the limit. - `find_classes(text, [path, limit]) -> table, truncated` - class references - `find_methods(text, [path, limit]) -> table, truncated` - hits `{kind, name, type, params, class, namespace, assembly, static, address}` - `find_fields(text, [path, limit])`, `find_properties(text, [path, limit])`, `find_members(text, [path, limit])` - `list_assemblies() -> table` - `list_classes([path, limit]) -> table` - default limit 2000 - `dump_class(name) -> string` - one class as C# shaped text Per-class reflection on any reference: `ref:list_methods([filter, inherited])`, `ref:list_fields()`, `ref:list_properties()` (hits carry `getter`/`setter` booleans), `ref:list_members()`, `ref:list_parents()`, `ref:list_interfaces()`, `ref:list_nested()`, `ref:class_info()`, `ref:dump()`. ```lua for _, m in ipairs(find_class("PlayerHealth"):list_methods("damage", true)) do print(m.class .. "." .. m.name .. "(" .. m.params .. ") : " .. m.type .. " @ " .. hex(m.address)) end print(dump_class("UnityEngine.GameObject")) ``` Reading and writing members falls back automatically: if a property has no getter but a `get_name` method exists, the read goes through it, same for a missing setter and `set_name`. A property that only has a setter errors on read with `property 'X' has no getter`. ## Arrays and lists - `to_table(object) -> table or nil` - converts an IL2CPP array (`T[]`) or `List` into a 1-based Lua table - `make_array(element_class, lua_table) -> reference` - creates a real IL2CPP array. Floats keep their fraction, integers truncate toward zero, strings make managed strings, references copy the pointer, structs copy from a boxed struct or raw address, nil zeros the slot. - `make_byte_array(data) -> reference` - a `byte[]` from a Lua string (binary safe) or a table of numbers - `make_float_array(values) -> reference` - a `float[]` from a table of numbers or a binary string of little-endian 4 byte floats - `array_set(arr, table, [offset]) -> number` - writes the table into an existing array, returns the count written - `array_set_floats(arr, values, [offset]) -> number` - fast float refill - `array_to_string(arr) -> string` - raw little-endian bytes of a numeric or bool array; handy for `fs.write` or `memory.write_floats` ```lua local bodies = to_table(find_objects_of_type("UnityEngine.Rigidbody")) for i, body in ipairs(bodies) do print(i, body.name) end local arr = make_array("System.Single", {0.5, 1, -1, 0.25}) print(table.concat(to_table(arr), " ")) -- 0.5 1 -1 0.25 local bin = array_to_string(arr) -- stash in a file fs.write("sine.bin", bin) local copy = make_float_array(fs.read("sine.bin")) ``` ## XR input Reads `UnityEngine.XR.InputDevices`. Needs the game to run Unity XR. Side argument: "left" or "right" (only the first letter matters). Feature names ignore case, underscores and spaces: `grip_button`, `GripButton` and "grip button" are the same. - `xr.is_available() -> boolean` - `xr.get_bool_feature(name, side) -> boolean` - `xr.get_float_feature(name, side) -> number` - `xr.get_vector2_feature(name, side) -> vector` - `{x, y}` - `xr.send_haptic_impulse(side, amplitude, duration) -> boolean` - channel 0 Bool features: `primary_button`, `primary_touch`, `secondary_button`, `secondary_touch`, `grip_button`, `trigger_button`, `menu_button`, `primary_2d_axis_click`, `primary_2d_axis_touch`, `secondary_2d_axis_click`, `secondary_2d_axis_touch`. Float: `trigger`, `grip`. Vector2: `primary_2d_axis`, `secondary_2d_axis`. An unknown feature raises an error. A missing device returns false, 0 or `vec2(0, 0)`. On Quest style controllers `primary_button` is A/X, `secondary_button` is B/Y. ```lua if xr.get_bool_feature("grip_button", "left") then xr.send_haptic_impulse("left", 0.5, 0.1) end ``` ## Audio Native wav, ogg and mp3 decoding in the mod (dr_wav, stb_vorbis, dr_mp3). `audio.formats()` returns `{"wav", "ogg", "mp3"}`. Every function takes a workspace path or raw bytes of the whole file. Decoded output caps at 32 million samples. - `audio.decode(path_or_bytes) -> table or nil, error` - returns `{data, rate, channels, frames}`. `data` is a binary Lua string of interleaved little-endian float32 samples. - `audio.load(path_or_bytes, [name]) -> clip or nil, error` - creates a real `UnityEngine.AudioClip` filled with the samples - `audio.play(clip, [options]) -> handle or nil, error` - options: `volume` (1), `loop` (false), `spatial_blend` (0, so 2D), `parent` (a GameObject reference). The handle is `{clip, src, go}`. - `audio.stop(handle) -> boolean, error` - `audio.route_to_mic(clip, [loop]) -> boolean, error` - plays the clip into the game's voice recorder (Gorilla Tag style builds with `GorillaTagger.Instance.myRecorder`); other games error with a clear message instead of crashing - `audio.restore_mic() -> boolean, error` `audio.load`, `audio.play`, `audio.stop` and the mic functions detect when they are off the main thread and post the work there, waiting up to 10 seconds. During a startup freeze they error with a timeout message - run them after `on_game_start` or from the console. ```lua on_game_start(function() local clip, err = audio.load("Custom_Sounds/test.wav") if not clip then print("load failed", err) return end local handle = audio.play(clip, { volume = 1, spatial_blend = 0 }) after(5, function() audio.stop(handle) end) end) ``` ## dev - debugging tools - `dev.info() -> table` - `{tasks, main_tasks, debug_pcall, guard_calls, tick_hook, main_pumping, worker, on_main_thread}`. `on_main_thread` is the cheapest way to check which thread your code is on. - `dev.debug_pcall([on]) -> boolean` - get or set the pcall logging flag - `dev.main_tasks([on]) -> boolean` - get or set the run-tasks-on-main-thread flag - `dev.guard_calls([on]) -> boolean` - get or set the crash guard for IL2CPP method calls. When on (default), a method call that segfaults inside IL2CPP surfaces as the Lua error `native crash (signal) inside 'MethodName'; the call was aborted` instead of killing the game. It wraps every call in a signal checkpoint, so turn it off in hot paths after testing. - `dev.guard(fn, ...) -> ok, result_or_error` - runs `fn` in a crash sandbox one level deep: a native segfault inside becomes `ok = false` with a text error. After a caught fault the process is alive but may be unstable - restart the game before trusting it again. - `dev.self_test() -> table` - array and float integrity checks against the real IL2CPP heap - `dev.log_path() -> string`, `dev.log_clear()` ```lua dev.debug_pcall(true) local ok, result = dev.guard(function() return risky_ref:SomeNativeCall() end) if not ok then print("survived", result) end ``` ## Introspection and stripped builds Games strip assemblies. `find_class` on a missing class returns an invalid reference instead of raising, so scripts that assume a class exists hang silently. Check with `has_class` up front, and list what did survive with `list_assemblies()` / `list_classes()`. ```lua if not has_class("UnityEngine.AudioClip") then error("this build has no AudioClip, audio is impossible here") end ``` Stripping also eats property accessors. The member lookup falls back to `get_X` / `set_X` methods automatically, and `list_properties` shows `getter` / `setter` booleans so a script can check before it reads. ## Utility functions - `hex(number) -> string`, `parse_hex(text) -> number` - `set_timescale(value)`, `get_timescale() -> number` - `Time.timeScale` - `log_info(...)`, `log_warn(...)`, `log_error(...)` - like print but also writes to the Android logcat - `il2cpp_loaded() -> boolean` - `destroy(object_or_address, [delay])` Prelude globals defined before every script: - `game_object` - UnityEngine.GameObject class reference - `unity_object` - UnityEngine.Object - `time` - UnityEngine.Time, so `time.frameCount` and `time.deltaTime` work - `shader` - UnityEngine.Shader, `shader.Find(name)` - `quaternion`, `mathf`, `physics` - matching UnityEngine classes - `force_mode` - `{force = 0, impulse = 1, velocity_change = 2, acceleration = 5}` - `primitive_type` - `{sphere = 0, capsule = 1, cylinder = 2, cube = 3, plane = 4, quad = 5}` Prelude helpers: - `find_shader([name]) -> reference or nil` - with a name it calls `shader.Find(name)`. Without one it tries "Standard", "GorillaTag/UberShader", "Universal Render Pipeline/Lit", "Unlit/Color" and returns the first hit. - `create_primitive(kind, [color], [shader_name]) -> reference` - `GameObject.CreatePrimitive` with a shader and color applied. ```lua local cube = create_primitive(primitive_type.cube, color(1, 0, 0, 1), "Unlit/Color") cube.transform.position = vec3(0, 2, 0) cube:destroy(5.0) ``` ## API quick list Every global, one line each. Core and values: - `print(...)`, `type_name(value) -> string`, `is_valid(value) -> boolean`, `wrap(address) -> reference or nil` - `get_time() -> number`, `hex(number) -> string`, `parse_hex(text) -> number`, `il2cpp_loaded() -> boolean` - `vec2(x, y)`, `vec3(x, y, z)`, `vec4(x, y, z, w)`, `quat(x, y, z, w)`, `color(r, g, b, a)` Classes and objects: - `find_class(full_name, [assembly_name]) -> reference` - `has_class(full_name, [assembly_name]) -> boolean` - `assembly(name) -> assembly helper` - `get_builtin_resource(type, path) -> reference or nil` - `destroy(object_or_address, [delay_seconds])` - `find_object(name) -> reference or nil`, `find_objects_of_type(type) -> table` Scene: - `scene.get_objects() -> table` - `scene.find_object(name) -> reference or nil` - `scene.find_objects_of_type(type) -> table` - `scene.AnyName -> reference or nil` Scheduler: - `on_update(fn) -> id`, `every(seconds, fn) -> id`, `after(seconds, fn) -> id` - `cancel(id) -> boolean`, `cancel_all()`, `get_time() -> number` - `on_game_start(fn) -> id`, `main_thread(fn)` - `set_tick_hook(full_class_name, method_name, [assembly_name]) -> boolean`, `has_tick_hook() -> boolean` Hooks: - `hook_method(class_name, method_name, selector, callback, [assembly_name]) -> hook_id` - `unhook_method(hook_id) -> boolean`, `disable_method_hook(hook_id) -> boolean`, `unhook_all_methods() -> number` - `has_method_hook(hook_id) -> boolean`, `hook_list() -> table`, `get_hook(hook_id) -> table or nil` - `set_hook_callback(hook_id, fn) -> boolean`, `hook_original([...]) -> value`, `hook_caller() -> string` - `HOOK_NULL -> userdata` Networking and data: - `http.request(options) -> response` - `http.get(url, [headers], [timeout]) -> response` - `http.post(url, [body], [headers], [content_type]) -> response` - `http.get_async(url, callback)`, `http.post_async(url, body, callback)`, `http.request_async(options, callback)` - `http.set_ssl_verify([enabled]) -> boolean`, `http.set_ca_file([path]) -> boolean` - `json.encode(value) -> string`, `json.decode(text) -> value, error` - `fs.list([dir])`, `fs.read(path)`, `fs.write(path, data)`, `fs.exists(path)`, `fs.size(path)`, `fs.delete(path)`, `fs.mkdir(path)` - `base64.encode(data) -> string`, `base64.decode(text) -> string` - `string.pack(fmt, ...) -> string`, `string.unpack(fmt, data, [init]) -> values..., pos` (also `pack.pack` / `pack.unpack`) Memory and bits: - `memory.read8/16/32/64(addr)`, `memory.read_float(addr)`, `memory.read_double(addr)` - `memory.read_bytes(addr, length)`, `memory.read_string(addr, [max_length])` - `memory.write8/16/32/64(addr, value)`, `memory.write_float(addr, value)`, `memory.write_double(addr, value)`, `memory.write_bytes(addr, data)` - `memory.write_floats(addr, values) -> number`, `memory.read_floats(addr, count) -> table or nil` - `memory.nop(addr, length) -> boolean` - `bit.band/bor/bxor/lshift/rshift/arshift/bnot` Reflection: - `find_classes/find_methods/find_fields/find_properties/find_members(text, [path, limit]) -> table, truncated` - `list_assemblies() -> table`, `list_classes([path, limit]) -> table`, `dump_class(name) -> string` - `enum_values(class) -> table`, `enum_name(class, value) -> string or nil` - `to_table(object) -> table or nil`, `make_array(element_class, table) -> reference` - `make_byte_array(data) -> reference`, `make_float_array(table_or_string) -> reference` - `array_set(arr, table, [offset]) -> number`, `array_set_floats(arr, values, [offset]) -> number`, `array_to_string(arr) -> string` Reference and handle members (colon syntax): - `ref.addr -> number`, `ref.class_name -> string`, `ref.full_name -> string` - `ref:is_valid()`, `ref:get_class()`, `ref:get_field(name)`, `ref:set_field(name, value)` - `ref:get_method(name, [argc]) -> handle`, `ref:new(...) -> reference` - `ref:get_component(type)`, `ref:add_component(type)`, `ref:get_component_in_children(type)` - `ref:destroy([delay_seconds])`, `ref:find_objects() -> table`, `ref:debug_info() -> string` - `ref:list_methods/list_fields/list_properties/list_members([filter, inherited]) -> table` - `ref:list_parents()`, `ref:list_interfaces()`, `ref:list_nested()`, `ref:class_info()`, `ref:dump()` - `handle:invoke(args...)`, `handle:is_valid()`, `handle:get_name()`, `handle:get_param_count()`, `handle:get_return_type()`, `handle:set_instance(ref_or_nil)` XR: - `xr.is_available() -> boolean` - `xr.get_bool_feature(name, side) -> boolean` - `xr.get_float_feature(name, side) -> number` - `xr.get_vector2_feature(name, side) -> vector` - `xr.send_haptic_impulse(side, amplitude, duration) -> boolean` Audio: - `audio.decode(path_or_bytes) -> table or nil, error` - `audio.load(path_or_bytes, [name]) -> clip or nil, error` - `audio.play(clip, [options]) -> handle or nil, error` - `audio.stop(handle) -> boolean, error` - `audio.route_to_mic(clip, [loop]) -> boolean, error` - `audio.restore_mic() -> boolean, error` - `audio.formats() -> table` dev: - `dev.info() -> table`, `dev.debug_pcall([on]) -> boolean`, `dev.main_tasks([on]) -> boolean` - `dev.guard_calls([on]) -> boolean`, `dev.guard(fn, ...) -> ok, result_or_error` - `dev.self_test() -> table`, `dev.log_path() -> string`, `dev.log_clear()` Utility: - `find_shader([name]) -> reference or nil` - `create_primitive(kind, [color], [shader_name]) -> reference` - `set_timescale(value)`, `get_timescale() -> number` - `log_info(...)`, `log_warn(...)`, `log_error(...)` ## Common patterns Safe cached lookups: ```lua local hands = {} local function get_hand(side) if not is_valid(hands[side]) then hands[side] = game_object.Find(side == "left" and "LeftHand Controller" or "RightHand Controller") end if is_valid(hands[side]) then return hands[side] end return nil end ``` Cleanup that survives script reloads - leave a global function behind and call the old one on the next run: ```lua local previous_cleanup = my_mod_cleanup my_mod_cleanup = function() if is_valid(menu_root) then destroy(menu_root) end end if previous_cleanup then pcall(previous_cleanup) end ``` Attaching UI to a hand - try the real class first, then fall back to object names, and cache both: ```lua local hand_cache = {} local function hand_transform(side) local cached = hand_cache[side] if is_valid(cached) then return cached end local player = find_class("GorillaLocomotion.Player").Instance if is_valid(player) then local field = side == "right" and "rightHandTransform" or "leftHandTransform" if player[field] then hand_cache[side] = player[field] return hand_cache[side] end end local obj = game_object.Find(side == "right" and "RightHand Controller" or "LeftHand Controller") if is_valid(obj) then hand_cache[side] = obj.transform return obj.transform end return nil end ``` Surviving a crashy IL2CPP call while testing an unknown game: ```lua local ok = dev.guard(function() return weird_ref:ExecuteNativeStuff() end) print("still alive", ok) ``` ## Troubleshooting - "member 'X' not found" - wrong name or the member lives on another class in the hierarchy. Inspect with `ref:get_class()`, `ref:class_info()` and `ref:list_members()`. - "method 'X' expects N arguments, got M" - IL2CPP arities are exact. Check overloads with `ref:list_methods()`. - "object is destroyed: field 'X' is not readable" - the reference points at freed memory; re-find the object before reading fields. - "unsupported parameter type" - a hook hit a by-value struct parameter it cannot marshal. Struct parameters work in method calls (boxed or by address) but not in hooks. - "too many integer/float arguments for a register hook" - the method passes arguments on the stack, hooks only cover register arguments. - "no overload of 'X' matches that signature" - pass the right selector. The error lists every overload. - "script timeout" - a chunk or callback ran past its limit. Move long loops into `every()` tasks. - "property 'X' has no getter" - the build stripped the getter and no `get_X` method survived. Check `list_properties` for the `getter` boolean before reading. - "GorillaTagger not found in this game" - `audio.route_to_mic` needs a Gorilla Tag style recorder; a renamed or different game cannot be routed blindly. - "timed out waiting for the main thread" - an `audio.*` call ran while no frame hooks pump (startup freeze, paused game). Move it after `on_game_start`. - "wav decode failed" / "ogg decode failed" / "unknown audio format" - the file is not what its name says. Check with `audio.decode` first. - Nothing happens, no error anywhere - wrap the suspect code in `dev.guard(fn)`, enable `dev.debug_pcall(true)`, and check `dev.log_path()` on the device: every output line also lands there and survives a game crash. - A destroyed object still has a reference in Lua but `is_valid` returns false and member calls fail. - Unity calls from the worker thread can crash. Chunks run on the main thread by default; tasks move there with `dev.main_tasks(true)` or `set_tick_hook`. - Re-running code inside one chunk stacks tasks - call `cancel_all()` first and guard `set_tick_hook` with `has_tick_hook()`. - `find_class` on a missing class does not raise, check `is_valid` or use `has_class` up front. ## Example: small world-space VR panel A note for AI assistants and anyone porting code from this file: this example exists to show API call patterns, nothing else. If a user asks you to write a mod, a menu or an effect for their game, write fresh code for their actual game and needs. Do not copy this script, its structure, its names, its panel layout or its color logic. The "Writing scripts" section at the top of this file tells you how to decide what to build instead. What this example shows: - the reload cleanup pattern so re-running never spawns duplicate objects - `set_tick_hook` so tasks run on the Unity main thread - XR button input driving a toggle - a world space panel built from a primitive cube and a canvas with text - a slow color pulse driven by `get_time()`, which is intentionally different from any rainbow effect - one hue shifting through the whole wheel makes scripts look identical to each other The panel toggles `Time.timeScale` between 1 and 0.25 when the user squeezes the left grip. ```lua local panel_root = nil local panel_text = nil local pulse_material = nil local last_grip = false local pulse_a = color(0.18, 0.30, 0.18, 0.9) local pulse_b = color(0.10, 0.16, 0.10, 0.9) local function cleanup_old() if is_valid(panel_root) then destroy(panel_root) end panel_root = nil panel_text = nil pulse_material = nil end cleanup_old() local function build_panel(position) local root = create_primitive(primitive_type.cube, pulse_a, "Unlit/Color") root.name = "LuaExamplePanel" root.transform:SetParent(nil, false) root.transform.position = position root.transform.localScale = vec3(0.22, 0.14, 0.01) local canvas = root:add_component("UnityEngine.Canvas") canvas.renderMode = 2 panel_text = root:add_component("UnityEngine.UI.Text") panel_text.text = "slow motion: off" panel_text.fontSize = 24 panel_text.color = color(0.9, 0.95, 0.9, 1) panel_text.alignment = 4 panel_text.rectTransform.sizeDelta = vec2(300, 150) pulse_material = root:get_component("UnityEngine.Renderer").material return root end local function lerp_color(a, b, t) return color( a.x + (b.x - a.x) * t, a.y + (b.y - a.y) * t, a.z + (b.z - a.z) * t, a.w ) end local slowmo = false local function tick() local grip = xr.get_bool_feature("grip_button", "left") if grip and not last_grip then slowmo = not slowmo set_timescale(slowmo and 0.25 or 1) if panel_text then panel_text.text = slowmo and "slow motion: on" or "slow motion: off" end end last_grip = grip if is_valid(pulse_material) then local t = 0.5 + 0.5 * math.sin(get_time() * 1.5) pulse_material.color = lerp_color(pulse_a, pulse_b, t) end end on_game_start(function() if not has_class("UnityEngine.UI.Text") then print("no UI namespace in this build, panel text skipped") end if not has_tick_hook() then pcall(set_tick_hook, "GorillaLocomotion.Player", "FixedUpdate", "Assembly-CSharp.dll") end local camera = scene.find_object("Main Camera") local forward = is_valid(camera) and camera.transform.forward or vec3(0, 0, 1) local spot = is_valid(camera) and camera.transform.position + forward * 2.0 or vec3(0, 2, 0) panel_root = build_panel(spot) cancel_all() on_update(tick) print("panel ready, squeeze left grip to toggle slow motion") end) ``` ## Links - Docs site: https://silenterased.github.io/BNMExplorer/ - This file on GitHub Pages: https://silenterased.github.io/BNMExplorer/llms.txt - The mod serves the same file at http://DEVICE_IP:8080/llms.txt - Source repository: https://github.com/SilentErased/BNMExplorer --- ## Researching game systems and authentication - methodology How to reverse a game's online auth and gated features with LuaBNM, from a real session (a VR game with a Cloudflare Worker gate, PlayFab tickets, Meta proof, APK integrity checks and an obfuscated anti-cheat suite). This section exists so an assistant plans the reverse engineering like an algorithm, not like guesswork. Full playbook: auth-research.txt next to this file (also on GitHub Pages). Rules first: - dump.cs is a signature map, not a call graph. Reconstruct the flow by hooking, not by reading. - `return true` in a hook callback is ONLY valid for void-returning methods. For IEnumerator/Task/bool returns it is converted to the raw word 0x1 and silently kills the flow - use `return "original"`. - Methods with no address comment in the dump are never compiled - wrap every hook_method in a pcall wrapper. - Tiny property getters/setters are INLINED - hooks on them never fire; read/write the field via get_field/set_field instead. - Block exit paths early: Application.Quit, Environment.Exit and the game's own exit helpers. Prefer blocking the game's exit helper methods and failure setters over blocking Environment.Exit (undefined behavior if something expects the process to die). Phase ladder: 1. Read the dump as a map. Search for Auth, Gate, Guard, Proof, Ticket, Session, Lease, Manifest, Register, Validate, Entitlement, Maintenance, Preauth, Attestation, PlayFab, Origin. List ALL classes of the obfuscated anti-cheat suite. For each class note: statics (the state), TaskCompletionSource fields (sync points), methods with addresses vs without, string params that look like ids/tokens/nonces, MonoBehaviour callbacks. 2. Trace-only hooks on every chain method. Void - print, `return true`. Non-void - print, `return "original"`. The last print before silence is where the chain dies. Poll statics every few seconds and print a combined line only on change. 3. Failure reasons: suites route failures through one or two static void setters taking a String reason. Passthrough hook prints every failure live; blocking hook (return false) keeps the flow alive while still printing the reason. Reason strings name the layer: "Meta entitlement rejected", "Release manifest changed", "Client validator did not finish within 180 seconds". 4. Unblock synchronization: chains hang on static TaskCompletionSource fields when upstream was blocked. Complete manually: `gate:get_field("Ready")` then `ready.Task.Status` (1 waiting, 5 ran-to-completion) and `ready:TrySetResult(...)` (try true, then "", then 0 under pcall). Reset blocking bools. Re-run the hanging Boot via get_method + invoke. 5. Enumerate the server from a PC: read Origin/endpoint statics, then curl the endpoints directly. A missing guard report on /preauth usually means a hook blocked the client's report method - let guards run, block only their quit paths. 6. Substitute values LAST, at the layer that carries them, and never at layers bound to a different identity system. In the researched game the gate Authenticate carried a PlayFab ticket where user equals the PlayFab id inside the ticket - replacing it with an Oculus id broke it. Nonces are single-use and expire - generate just-in-time. 7. Confirm gating through the scene: the gated object (a room-code terminal) spawns only after server approval. Loop scene_hierarchy before and after each auth stage and diff - the spawn appearing is your live indicator of server approval. Base Oculus account auth (on-device), placeholder values: ```lua http.set_ssl_verify(false) local my_access_token = "PASTE_YOUR_PERSONAL_USER_TOKEN" local app_id = "PASTE_YOUR_APP_ID" local function grab(body, key) if not body then return nil end local s = body:match('"' .. key .. '"%s*:%s*"([^"]*)"') if s and s ~= "" then return s end return body:match('"' .. key .. '"%s*:%s*(-?%d+)') end local r1 = http.request({ url = "https://graph.oculus.com/authenticate_application?app_id=" .. app_id .. "&access_token=" .. my_access_token, method = "POST", timeout = 15 }) local t = r1 and r1.ok and json.decode(r1.body) local access = t and t.access_token if not access then print("auth failed", r1 and r1.body:sub(1, 200) or "no response") return end local r2 = http.get("https://graph.oculus.com/me?fields=id,org_scoped_id,alias,presence,presence_status,profile_url_small,profile_url,display_name&access_token=" .. access, nil, 15) local r3 = http.request({ url = "https://graph.oculus.com/user_nonce_generate?access_token=" .. access, method = "POST", timeout = 15 }) org_scoped = grab(r2 and r2.body, "org_scoped_id") oculus_id = grab(r2 and r2.body, "id") user_proof = grab(r3 and r3.body, "nonce") local me = r2 and r2.ok and json.decode(r2.body) display_name = (me and me.display_name) or oculus_id auth_ready = true print("display_name = " .. tostring(display_name)) print("oculus_id = " .. tostring(oculus_id)) print("org_scoped = " .. tostring(org_scoped)) print("user_proof = " .. tostring(user_proof)) ``` Then hook the platform model constructors so every object the game builds carries your values: User (.ctor, 1 arg) - ID/OculusID/DisplayName; OrgScopedID (.ctor, 1 arg) - ID; UserProof (.ctor, 1 arg) - Value. Two modes: overlay - hook_original first, then overwrite fields, return false; full - skip the original, set fields on the zeroed object, return false. Guard with auth_ready so pre-auth constructions pass through (`return true` - void here, it is a constructor). Install before game boot (startup freeze plus Auto Lua) - the proof flow runs once at startup and only the CAPI getter hooks (ovr_User_GetID, ovr_User_GetOculusID, ovr_User_GetDisplayName, ovr_UserProof_GetNonce) keep working after boot, so they are the fallback layer that reads of native handles always hit. Identity systems must not be mixed: a PlayFab-based gate identifies the player by the ticket (user equals the PlayFab id inside it), Oculus-layer substitution belongs at Oculus-layer hooks. Nonces go stale in minutes - refresh them near the moment of use.