Utilities

FFI and memory

The memory helpers, and the FFI: off by default, opt-in per player.

The FFI is disabled by default. While it is off, ffi is nil and require("ffi"), require("debug") and require("jit.*") return nil. The built-in API (memory.*, entities.*, ...) keeps working because the runtime uses the FFI internally; only your script is cut off from it.

The player enables it with Allow Lua FFI (unsafe) in the Settings tab. Treat it as the player opting in to run code with full access to the game process: scripts that need it only work for players who turned it on, and a bad pointer crashes the game.

When it is on, ffi and bit are globals and everything LuaJIT's FFI offers works (ffi.cdef, ffi.C, ffi.cast, callbacks), and debug is available too. Call game functions from the thread they expect: create_move runs on the game thread, drawing callbacks on the render thread. Test with if not ffi then luna.notify("this script needs Allow Lua FFI") return end.

FunctionParametersReturnsDescription
memory.read(addr, type)i8 u8 i16 u16 i32 u32 i64 u64 f32 f64 ptr bool vec3 vec2 str textvalueNever crashes; unreadable memory gives nil or 0.
memory.write(addr, type, value...)boolFalse on protected memory. read_bytes, write_bytes
memory.find_pattern(module, pattern)"48 8B ?? ??"address or nilfind_export, create_interface, module(name), rel32, readable
memory.schema_offset(class, field)offset, typeSearches parent classes too.
memory.vfunc(object, index, ctype)functionCallable virtual function.
ffi.cdef [[
typedef struct { long x, y; } LUNA_POINT;
int GetCursorPos(LUNA_POINT* p);
]]

local point = ffi.new("LUNA_POINT")

events.present_queue:add(function()
    ffi.C.GetCursorPos(point)
    render.text(20, 200, point.x .. ", " .. point.y, Color.White())
    local pawn = entities.get_local_pawn()
    local offset = memory.schema_offset("C_BaseEntity", "m_iHealth")
    if pawn and offset then
        render.text(20, 216, "health " .. memory.read(pawn:get_address() + offset, "i32"), Color.White())
    end
end)