DEPENDENCIES:
You will be physically and mentally unable to read and use these unless you read these threads beforehand:
translation: it is recommended you educate yourself on this corner/mindset of Luau before reading
🔘
https://devforum.roblox.com/t/δ-the-lost-art-of-optimization-what-do-we-gain-when-we-drop-oops-training-wheels/4123198
https://devforum.roblox.com/t/discussion-the-case-against-oop-in-luau-and-why-its-so-bad/3969021
Narrowing the LuaBridge overhead (old)
https://devforum.roblox.com/t/the-rise-of-the-new-luau-order/4116730/
https://devforum.roblox.com/t/the-new-luau-order-micro-optimizations-will-eat-all-ze-bugs/3969724
Legal Disclaimer (for Engineers and Other Lawyers)
This post is not:
- a suggestion for (((normal))) game code,
- a replacement for good architecture, (jk)
- or a promise Roblox will never change any of this.
- not actually illegal
This is:
- a guided tour of Luau’s dark corners,
- a set of experiments that produced real, measured speedups,
- and a reminder that the Lua→C++ boundary (“Luabridge”) is secretly where a lot of time goes to die, and I’m not sorry.
- legal, and works as of today
Everything here is:
- fragile
Roblox can nerf any of it tomorrow and they would be 100% right to do so. Would pmo and I would quit.
Use these tricks only when:
- you want to
Benchmark Setup (aka: I Actually Measured, I Promise)
All numbers in this post come from a single script that:
- steals internal metamethods using
debug.info+xpcall, - runs each micro-benchmark thousands of times,
- measures with
os.clock()and reports nanoseconds per call.
The basic pattern looks like this:
local function bench(name: string, iterations: number, fn: () -> ())
local t0 = os.clock()
for _ = 1, iterations do
fn()
end
local dt = os.clock() - t0
local nsPer = dt / iterations * 1e9
print(("[%-40s] %8d iters %8.3f ms %8.1f ns/call")
:format(name, iterations, dt * 1000, nsPer))
end
I then compare:
- baseline Luau behavior (property access, namecall, etc.)
- against the illegal version (raw metamethod, function pointer, etc.)
so HOW the HELL does this work?
Discovered by that one guy in the Luabridge thread.
I am calling this the:
Stealing Candy From a Baby and Using it to Hotwire a Fusion Reactor Method (works 2025 )
Let us go very slow.
Step 0. What even is game.Name under the hood
When you write:
local name = game.Name
you are not reading a Lua table field.
game is userdata.
That means:
- it is a C++ thing
- it does not have Lua keys
- all of its behavior goes through a hidden metatable
Inside that metatable are special fields like:
__index→ runs when you doobj.SomeProperty__newindex→ runs when you doobj.SomeProperty = value
For Instances, these are C functions owned by the engine.
They speak C++ to the DataModel.
Lua never sees the real storage.
So:
game.Name
is really:
-- fake code
local __index = <some internal C function>
local name = __index(game, "Name")
We normally do not see that function.
Roblox does not expose it.
We are going to steal it.
Step 1. xpcall lets you look at the stack after a function explodes
Lua has pcall and xpcall.
pcall(fn)runsfnand catches errorsxpcall(fn, handler)runsfnand if it errors, runshandler(err)
The important bit:
Inside handler, the call stack is still there.
So from that handler we can inspect who was running when the error happened.
That is the opening.
Step 2. debug.info lets you ask “who is at stack level N”
Luau has debug.info(level, what).
levelis how far up the call stack you lookwhatis what you want (we want"f"which means “function”)
Example:
local function a()
local function b()
print(debug.info(1, "f")) -- prints b
print(debug.info(2, "f")) -- prints a
end
b()
end
a()
So:
- level 1 = current function
- level 2 = whoever called the current function
- level 3 = whoever called that, and so on
We will use this from inside the xpcall error handler.
Step 3. Make the engine __index explode on purpose
We need a call that:
- goes through the internal
__indexmetamethod - errors inside that code
- hits our xpcall handler while the stack is still intact
So we do something like this:
xpcall(function()
return (game :: any)["_definitely_not_a_real_property"]
end, function()
local f = debug.info(2, "f")
print(f)
end)
What happens:
-
(game :: any)["_definitely_not_a_real_property"]runs -
Luau sees
gameis userdata, so it calls the internal C__index -
C
__indextries to resolve that property name, fails, and errors -
xpcall catches that error and runs our handler
-
Inside the handler,
debug.info(2, "f")means:- level 1 = the handler itself
- level 2 = the function that errored
The function that errored is the internal C metamethod.
So debug.info(2, "f") returns a function object that points straight at the engine __index.
We store that.
Congrats. You just stole candy from the baby.
Step 4. Turn this into a reusable “steal” helper
We do not want to write that pattern every time, so we build a helper:
local function stealMetamethod(thunk: () -> ()): (...any) -> ...any
local stolen: any = nil
xpcall(thunk, function()
stolen = debug.info(2, "f")
end)
return stolen :: (...any) -> ...any
end
You call stealMetamethod with some tiny function that triggers the error.
Inside the error handler we grab the function at stack level 2.
Now we can steal different engine metamethods by giving it different triggers.
Step 5. Steal __index and __newindex for Instances
For Instances, the trigger can be a fake property access and a fake property write:
local rawInstanceIndex = stealMetamethod(function()
return (game :: any)["_definitely_not_a_real_property"]
end)
local rawInstanceNewIndex = stealMetamethod(function()
(game :: any)["_definitely_not_a_real_property"] = nil
end)
These functions are:
rawInstanceIndex(instance, "PropertyName") -- like instance.PropertyName
rawInstanceNewIndex(instance, "PropertyName", value) -- like instance.PropertyName = value
They are the universal C metamethods shared by all Instances.
They do not care which Instance you pass in.
They talk directly to the engine.
That is why this works:
rawInstanceNewIndex(workspace, "Name", "I broke the rules")
print(workspace.Name)
No Luau property lookup. No colon sugar. You just yeeted straight into the C layer.
Step 6. Same crime, new victims
The same pattern works for other userdata:
CFramefields- maybe Enums
- probably some other internal types
Example for CFrame:
local rawCFrameIndex = stealMetamethod(function()
return (CFrame.new() :: any).ThisFieldDoesNotExist
end)
local cf = CFrame.new()
local look = rawCFrameIndex(cf, "LookVector")
You triggered the CFrame __index metamethod with a bogus field, made it error, stole it, and now use it for valid fields.
Step 7. Why this feels like hotwiring a fusion reactor
This technique is not an “official API”. It is pure implementation leakage.
We are:
- Forcing the engine into an error path.
- Using debug tools to capture internal function objects.
- Calling those internals directly on our own data.
It is the Luau version of:
“I stole a config pointer out of a crash log and now I am driving the kernel”.
Roblox did not intend you to do this.
They might patch it tomorrow.
Until then, it is a genuinely fun way to learn how the Luabridge behaves.
Now that you know how the candy theft works, the rest of the crimes should make more sense.
CRIME #1 — Calling the Engine’s Property Metamethod Directly
What Roblox tells you
Just use
part.Nameandpart.Name = "X".
Luau optimizes this, it’s already fast, don’t worry about it.
What we actually did
… so we stole the C++ __index and __newindex metamethods for Instances. yeah.
as follow:
local function stealMetamethod(thunk: () -> ()): (...any) -> ...any
local stolen: any = nil
xpcall(thunk, function()
stolen = debug.info(2, "f")
end)
return stolen :: (...any) -> ...any
end
local rawInstanceIndex = stealMetamethod(function()
return (game :: any)["_definitely_not_a_real_property"]
end)
local rawInstanceNewIndex = stealMetamethod(function()
(game :: any)["_definitely_not_a_real_property"] = nil
end)
These are the actual C functions the engine uses to implement property access on Instances.
Now we benchmark:
local part = Instance.new("Part")
part.Name = "BenchPart"
bench("baseline part.Name", 200000, function()
local _ = part.Name
end)
bench("rawInstanceIndex(part,'Name')", 200000, function()
local _ = rawInstanceIndex(part, "Name")
end)
bench("baseline part.Name = 'X'", 200000, function()
part.Name = "X"
end)
bench("rawInstanceNewIndex(part,'Name','X')", 200000, function()
rawInstanceNewIndex(part, "Name", "X")
end)
Numbers I got
Your numbers will differ, but the shape should match.
part.Name→ ~78 ns / callrawInstanceIndex(part, "Name")→ ~73 ns / callpart.Name = "X"→ ~122 ns / callrawInstanceNewIndex(part, "Name", "X")→ ~98 ns / call
What this means
- The “illegal” getter is slightly faster than the public property path.
- The “illegal” setter is noticeably faster (~20%+) than
part.Name = value.
In other words:
The raw engine metamethods can beat Luau’s supposedly “fast path” for property access.
Great!
CRIME #2 — CFrame’s LookVector Is Slower Than It Should Be
Experiment
Same trick, but for CFrame userdata:
local rawCFrameIndex = stealMetamethod(function()
return (CFrame.new() :: any).ThisFieldDoesNotExist
end)
local cf = CFrame.new()
bench("cf.LookVector", 200000, function()
local _ = cf.LookVector
end)
bench("rawCFrameIndex(cf,'LookVector')", 200000, function()
local _ = rawCFrameIndex(cf, "LookVector")
end)
Numbers I saw
cf.LookVector→ ~28 ns / callrawCFrameIndex(cf, "LookVector")→ ~21 ns / call
That’s a ~25% speedup just by skipping Luau’s userdata field logic and jumping straight into the C metamethod.
Why this matters
If you’re doing:
- custom character controllers,
- CPU raycasters,
- viewshed / FOV checks,
- physics approximations / steering behaviors,
where you call LookVector, RightVector, UpVector thousands of times per frame, this overhead is very real.
How to weaponize it
You can wrap specific hot fields:
local function fastLookVector(cf: CFrame): Vector3
return rawCFrameIndex(cf, "LookVector")
end
Then in critical loops:
for i = 1, #parts do
local cf = parts[i].CFrame
local dir = fastLookVector(cf)
-- ...
end
This is the sort of thing you only do after you’ve already profiled and found “cf.LookVector is hot”.
(okay but both of these are–in theory–slower than repeating the same crime accross lines)
CRIME #3 — Struct-of-Arrays vs Naive Instance Loops (aka: Stop Crossing the Bridge)
Everyone says “Lua→C++ boundary is slow”.
We decided to measure just how slow, and how much you can claw back by not crossing it in your tight loops.
Naive version: touch Instances every iteration
local function naiveStep(parts, rot: CFrame)
for i = 1, #parts do
local cf = parts[i].CFrame
parts[i].CFrame = cf * rot
end
end
SoA version: math in Luau, apply in bulk
local function buildParts(count: number): ({BasePart}, {CFrame})
local parts = table.create(count)
local poses = table.create(count)
for i = 1, count do
local p = Instance.new("Part")
p.Anchored = true
p.CanCollide = false
p.CFrame = CFrame.new(i, 0, 0)
p.Parent = nil
parts[i] = p
poses[i] = p.CFrame
end
return parts :: {BasePart}, poses :: {CFrame}
end
local function soaStep(poses: {CFrame}, rot: CFrame)
for i = 1, #poses do
poses[i] = poses[i] * rot
end
end
local function flush(parts: {BasePart}, poses: {CFrame})
for i = 1, #parts do
rawInstanceNewIndex(parts[i], "CFrame", poses[i])
end
end
Benchmark:
local count = 3000
local partsNaive, _ = buildParts(count)
local partsSoA, poses = buildParts(count)
local rot = CFrame.Angles(0, math.rad(1), 0)
bench(("naive %d parts CFrame step"):format(count), 200, function()
naiveStep(partsNaive, rot)
end)
bench(("SoA %d parts step+flush"):format(count), 200, function()
soaStep(poses, rot)
flush(partsSoA, poses)
end)
Numbers (example)
- naive: ~1.11 ms / call
- SoA: ~0.88 ms / call
That’s a ~20–25% speedup just by:
- doing all math on a pure
CFramearray, - paying the Instance property write cost once per part, rather than twice per iteration.
Takeaway
If your hot loop is bouncing back and forth between Luau and engine objects, you’re wasting a scary amount of time.
In performance-critical systems:
- hold data in plain Lua arrays,
- compute there,
- then apply back to Instances in one big burst.
CRIME #4 - Namecall is comfy, function pointers are rude
What Roblox tells you
Just write
instance:IsA("BasePart")andparent:FindFirstChild("Thing").
The colon syntax is nice and fast.
What we actually did
We grabbed the universal methods directly off real objects:
local IsA = game.IsA
local FindFirstChild = workspace.FindFirstChild
Then we compared:
-- namecall
bench("IsA namecall (5000 insts)", 200, function()
local n = 0
for i = 1, count do
if list[i]:IsA("BasePart") then
n += 1
end
end
end)
-- direct function pointer
bench("IsA func ptr (5000 insts)", 200, function()
local n = 0
for i = 1, count do
if IsA(list[i], "BasePart") then
n += 1
end
end
end)
-- same idea for FindFirstChild
bench("FindFirstChild namecall (5000 parents)", 200, function()
local n = 0
for i = 1, count do
if parents[i]:FindFirstChild("Target") ~= nil then
n += 1
end
end
end)
bench("FindFirstChild func ptr (5000 parents)", 200, function()
local n = 0
for i = 1, count do
if FindFirstChild(parents[i], "Target") ~= nil then
n += 1
end
end
end)
Numbers I saw
-
IsAnamecall - about 295k ns / batch -
IsAfunction pointer - about 288k ns / batch -
FindFirstChildnamecall - about 610k ns / batch -
FindFirstChildfunction pointer - about 572k ns / batch
These loops all do the same work on the same data.
The only difference is colon syntax versus direct function pointer.
What this means
Namecall has to go through a small dispatch layer that:
- resolves the method name,
- picks the right overload,
- does namecall magic.
When you use the universal function directly, that layer is skipped.
The method is still C++, but you are one step closer to it.
The win is small per call.
Inside a 5000 item loop that runs every frame, it becomes very real!
CRIME #5 - Signals: function pointer Fire is cursed fast
Signals are another Luabridge hotspot.
So we did the same crime to them.
Setup
local sig = workspace.ChildAdded
local Connect = sig.Connect
bench("signal:Connect(fn); Disconnect", 20000, function()
local c = sig:Connect(function() end)
c:Disconnect()
end)
bench("Connect(signal, fn); Disconnect", 20000, function()
local c = Connect(sig, function() end)
c:Disconnect()
end)
local evt = Instance.new("BindableEvent")
local Fire = evt.Fire
bench("evt:Fire()", 20000, function()
evt:Fire()
end)
bench("Fire(evt)", 20000, function()
Fire(evt)
end)
Numbers I saw
signal:Connect(fn)- about 842 ns / callConnect(signal, fn)- about 830 ns / call
So Connect(signal, fn) is a tiny bit faster.
Not a big deal, still funny.
The fun part is Fire:
evt:Fire()- about 97 ns / callFire(evt)- about 59 ns / call
That is a huge gap for something this small.
The function pointer call is roughly 1.6x faster.
What this means
The colon syntax path for :Fire() has visible overhead.
Again, the universal method pointer skips some dispatch work.
If you have a system that pumps thousands of BindableEvents per frame
you are leaving performance on the floor.
How to weaponize this
In something like an ECS event bus or hot signal hub:
local evt = Instance.new("BindableEvent")
local Fire = evt.Fire
local function emit()
Fire(evt)
end
Still readable.
Just faster in the hot path.
CRIME #6 - GC pain: coroutine.wrap is 250 times slower than you think
This one is not even a micro optimization
it is just an intervention.
The experiment
local part = Instance.new("Part")
part.Name = "GCBench"
local function readName()
return part.Name
end
bench("inline closure (function() part.Name end)()", 50000, function()
(function()
local _ = part.Name
end)()
end)
bench("pcall(closure read part.Name)", 50000, function()
local _ok, _ = pcall(function()
return part.Name
end)
end)
bench("coroutine.wrap(readName)()", 50000, function()
local co = coroutine.wrap(readName)
co()
end)
bench("rawInstanceIndex(part,'Name')", 50000, function()
local _ = rawInstanceIndex(part, "Name")
end)
Numbers I saw
- inline closure - about 96 ns / call
- pcall closure - about 173 ns / call
- coroutine.wrap each time - about 18,568 ns / call
- rawInstanceIndex - about 74 ns / call
What this means
coroutine.wrap in a tight loop is not just slow
it is an entire new class of slow.
You are paying for:
- allocation
- stack state
- scheduling machinery
Every single iteration.
In comparison, even pcall looks reasonable
and the raw metamethod read is just chilling.
Rule of thumb
- Do not put
coroutine.wrapin hot loops. - Do not spawn coroutines per item per frame.
- If you need asynchrony, batch it.
Coroutines are for structure and scheduling
not for micro units of work in a 50,000 iteration loop.
CRIME #7 - Table shapes actually matter
Luau has an optimizer that likes tables with a stable “shape”.
We poked it with a stick.
The tests
local iterations = 200
local mono = { x = 1, y = 2, z = 3 }
bench("monomorphic table sum (x,y,z)", iterations, function()
local s = 0
for _ = 1, 1000 do
s += mono.x + mono.y + mono.z
end
end)
local poly = { x = 1, y = 2, z = 3 }
bench("polymorphic (add/remove w)", iterations, function()
local s = 0
for i = 1, 1000 do
if i % 2 == 0 then
poly.w = 123
else
poly.w = nil
end
s += poly.x + poly.y + poly.z
end
end)
local morph = { x = 0, y = 0, z = 0 }
bench("type-morphing field x (number/string)", iterations, function()
for i = 1, 1000 do
if i % 2 == 0 then
morph.x = 1
else
morph.x = "one"
end
end
end)
Numbers I saw
- monomorphic sum - about 22,078 ns / batch
- polymorphic shape - about 28,116 ns / batch
Shape churn makes it slower.
Type morph:
- type mangle on
x- about 13,275 ns / batch
Which is faster, because the inner loop is doing less math
but the main point stands
The VM really prefers “boring” shapes.
Takeaway
- Do not add and remove random keys from hot tables.
- Try to keep objects structurally stable.
- Use arrays for data and separate side maps for metadata if needed.
This is more of a design note
but it supports the same idea as SoA
keep data simple on the Lua side and the VM can run faster.
CRIME #8 - Arrays, ipairs and why your for loop is not always king
I wanted to see how Luau treats packed arrays versus weird tables.
Setup
local N = 10000
local iterations = 100
local packed = table.create(N, 1)
local mixed = {}
for i = 1, N do
if i % 2 == 0 then
mixed[i] = 1
else
mixed["k" .. i] = 1
end
end
bench("packed: for i=1,N do arr[i] end", iterations, function()
local s = 0
for i = 1, N do
s += packed[i]
end
end)
bench("packed: ipairs(arr)", iterations, function()
local s = 0
for _, v in ipairs(packed) do
s += v
end
end)
bench("packed: pairs(arr)", iterations, function()
local s = 0
for _, v in pairs(packed) do
s += v
end
end)
bench("mixed: pairs(mixed)", iterations, function()
local s = 0
for _, v in pairs(mixed) do
s += v
end
end)
Numbers I saw
- packed index loop - about 77,027 ns / batch
- packed
ipairs- about 40,322 ns / batch - packed
pairs- about 41,584 ns / batch - mixed
pairs- about 83,547 ns / batch
So on a packed numeric array:
ipairsis about twice as fast as hand writtenfor i = 1, Nin this runpairsis about the same asipairshere- mixed tables are simply heavier to iterate
This is very different from stock Lua folklore.
Luau has a specialized fast path for ipairs on packed arrays.
If your data is a clean numeric list, you can lean into that.
CRIME #9 - We stole __namecall and it did not want to play
I had to try.
The experiment
local rawNamecall: any = nil
xpcall(function()
(game :: any):ThisMethodDoesNotExist("arg1")
end, function()
rawNamecall = debug.info(2, "f")
end)
print("rawNamecall type:", type(rawNamecall))
if type(rawNamecall) == "function" then
local ok, res = pcall(function()
return (rawNamecall :: any)(game, "IsA", "DataModel")
end)
print("test call success?", ok, "result:", res)
end
Result
rawNamecallis indeed afunction- calling it like
rawNamecall(game, "IsA", "DataModel")does not work - the error complains about
ThisMethodDoesNotExiston the DataModel
So this thing exists on the stack
but the signature and expectations are not like __index.
Takeaway
There is some kind of namecall handler in there
but it is glued into the VM in a way that is not friendly to direct calling.
So for now:
- raw
__indexand__newindexare useful and safe to call - CFrame
__indexis useful - raw namecall is an interesting ghost that we saw and then backed away from
final thoughts
i believe i have only touched the surface. in this regard.
the purpose of this tutorial is to educate you on this corner of the language, and i encourage you to explore further.