-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathluau.mdc
More file actions
638 lines (457 loc) · 19 KB
/
Copy pathluau.mdc
File metadata and controls
638 lines (457 loc) · 19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
---
globs: **/*.luau
alwaysApply: false
---
# Luau Language Rules
**Default context: Roblox Luau.** Unless otherwise stated, assume we are programming in Roblox Studio. Standard Luau differences are noted where relevant.
For code style and conventions (naming, OOP class pattern, performance idioms, type-safety rules), see `rules/luau-style.mdc`. This file covers language semantics only.
## Finding Documentation
- `.cursor/docs/usergenerated/roblox/en-us/luau/` - Roblox-specific Luau documentation (types, Roblox classes/enums, Studio integration)
- `.cursor/docs/usergenerated/luau/` - Official Luau language documentation (type system, standard library, syntax, guides)
- `.cursor/docs/usergenerated/luau-rfcs/` - RFC documents detailing every language feature and design decision
## Single-Threaded Execution Model
**Luau is completely single-threaded.** This is the most misunderstood aspect of the language.
### Key Facts
- Code in one script **cannot** run simultaneously with another script
- Execution only switches when code **yields** (`task.wait()`, `:Wait()`, `coroutine.yield()`, async APIs)
- **No yield = no other code runs.** Infinite loops without yields freeze the game.
### Practical Implications
```luau
-- SAFE: No yield between read/write, guaranteed atomic
local value = data.Value
data.Value = value + 1
-- UNSAFE: Yield allows other code to modify data.Value
local value = data.Value
task.wait(0.1) -- Other code can run here!
data.Value = value + 1 -- May not be what you expect
```
### Common Misconceptions
1. **"Multiple scripts run in parallel"** - False. They switch only at yield points.
2. **"I need mutexes/locks"** - Not in pure Luau. No yield = exclusive access.
3. **"`task.spawn` runs code in parallel"** - False. It schedules for later.
## Luau-Specific Syntax
### Arrays Are 1-Indexed
Unlike most languages, Luau arrays start at index 1, not 0.
```luau
local arr = {"first", "second", "third"}
print(arr[1]) -- "first"
print(arr[0]) -- nil
for i = 1, #arr do
print(arr[i])
end
```
### Generic Instantiation Uses `<<T>>`
Unique to Luau, easy to forget:
```luau
local binding = React.createBinding<<number?>>()
local result = someFunc<<string, number>>()
-- Single angle brackets are not allowed at call sites
-- local binding = React.createBinding<number?>()
```
### Type Ascription Uses `::`
```luau
local x = someValue :: string
local y = (a + b) :: number
```
### String Interpolation Uses Backticks
```luau
local name = "world"
print(`Hello {name}!`) -- Hello world!
print(`Result: {1 + 2}`) -- Result: 3
print(`Literal braces: \{not interpolated}`)
```
Inside backtick strings, `\` escapes `` ` ``, `{`, `\`, and newlines. `{{` is a parse error (use `\{` for a literal brace). Backtick strings are not permitted in type annotations.
### String Literal Escapes
```luau
"\xAB" -- Hex escape: byte 0xAB
"\u{1F600}" -- Unicode escape: UTF-8 for U+1F600 (braces required)
"long\z
string" -- \z skips following whitespace/newlines: "longstring"
```
### If Expressions
```luau
local x = if condition then value else alternative
local size = if x > 10 then "big" elseif x > 5 then "medium" else "small"
```
`else` is mandatory.
### Continue Statement
`continue` is contextual (not a reserved word) and must be the last statement in a block.
```luau
for i = 1, 10 do
if i % 2 == 0 then continue end
print(i)
end
```
### Compound Assignment
Operators: `+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `^=`, `..=`. The left-hand side is evaluated once. Compound assignments are statements, not expressions.
```luau
a += b
x //= 2
str ..= "suffix"
```
### Floor Division
`a // b` is `math.floor(a / b)` for numbers; for vectors it floors each component. Overloadable via the `__idiv` metamethod; `//=` is the compound form.
### Number Literals
Luau has a single number type (64-bit IEEE 754 double; integers exact up to 2^53).
```luau
local hex = 0xFF -- Hexadecimal
local bin = 0b10101010 -- Binary
local big = 1_048_576 -- Decimal separators for readability
local hexSep = 0xFFFF_FFFF
local binSep = 0b_0101_0101
```
## Type System Essentials
### Type Modes
- `--!strict`: Full type checking
- `--!nonstrict`: Reduced checking (default)
- `--!nocheck`: Disabled
### Primitive Types
The Luau VM has 10 primitive types: `nil`, `string`, `number`, `boolean`, `table`, `function`, `thread`, `userdata`, `vector`, `buffer`.
```luau
local x: number
local s: string
local b: boolean
local co: thread = coroutine.running()
local buf: buffer = buffer.create(256)
```
`table` and `function` use dedicated syntax (not written by name). `vector` is not representable by name in user type annotations. `userdata` is represented by concrete host types.
### `unknown`, `any`, and `never`
```luau
local u: unknown = anything -- Top type: accepts all values, must be refined before use
local a: any = anything -- Escape hatch: opts out of type checking
local n: never -- Bottom type: no value inhabits this type
```
- `unknown` requires refinement (e.g., `typeof(x) == "string"`) before use
- `any` silently allows all operations
- `never` is useful for exhaustiveness checking and impossible branches
### Core Type Syntax
```luau
local arr: {string} -- Array shorthand (equivalent to {[number]: string})
local map: {[string]: number} -- Dictionary with indexer
local obj: { x: number, y: number } -- Table with named properties
local maybe: string? -- Optional: string | nil
-- Union / Intersection (leading | and & allowed for formatting)
type Result = "ok" | "error"
type Action
= { type: "add", value: number }
| { type: "remove", id: string }
type Combined = TypeA & TypeB
-- Singleton (literal) types -- strings and booleans only, not numbers
type Direction = "up" | "down" | "left" | "right"
type Truthy = true
-- Function types, optionally with named parameters
type Callback = (number, string) -> boolean
type Named = (errorCode: number, errorText: string) -> ()
type Generic = <T>(T) -> T
type Multi = (number, string) -> (boolean, string)
```
### Generics with Defaults
Type aliases support default type parameters (functions do not):
```luau
type Pair<T> = { first: T, second: T }
type PairWithDefault<T = string> = Pair<T>
local p: PairWithDefault = { first = "hello", second = "world" }
```
### Read-Only and Write-Only Properties
```luau
type ReadOnly = { read x: number }
type WriteOnly = { write x: number }
-- Separate read/write types for the same field:
type Foo = { read p: Animal, write p: Dog }
```
Indexers also support `read`/`write`: `type ReadOnlyMap<K, V> = { read [K]: V }`.
### Tagged Unions (Discriminated Unions)
```luau
type Action =
| { type: "increment" }
| { type: "decrement" }
| { type: "set", value: number }
function reducer(state: number, action: Action): number
if action.type == "increment" then
return state + 1
elseif action.type == "decrement" then
return state - 1
elseif action.type == "set" then
return action.value
else
error("Unknown action")
end
end
```
### Exhaustiveness Checking with `never`
```luau
function handle(x: "a" | "b")
if x == "a" then
return 1
elseif x == "b" then
return 2
else
local _: never = x -- Type error if not exhaustive
end
end
```
### Built-in Type Functions
```luau
type Keys = keyof<MyTable> -- Union of all property names
type RawKeys = rawkeyof<MyTable> -- Keys without __index
type PropType = index<Person, "age"> -- Property type lookup
type RawProp = rawget<Person, "age"> -- Property lookup without __index
```
### Variadic Type Packs
```luau
-- Function definition
local function addNumbers(...: number)
-- ...
end
-- Type definition
type AddNumbers = (...number) -> number
-- Generic type packs
type Fields<self, P..., R...> = {
call: (self, P...) -> R...
}
```
### Type Exports
```luau
-- In Types.luau
export type Player = { name: string, score: number }
-- In another module
local Types = require(ReplicatedStorage.Types)
local player: Types.Player = { name = "Alice", score = 100 }
```
### Inferred Types with `typeof`
```luau
local config = { maxRetries = 3, timeout = 30 }
type Config = typeof(config) -- {maxRetries: number, timeout: number}
-- Also usable for metatable types
type Vector = typeof(setmetatable({}::{
x: number, y: number
}, {}::{
__add: (Vector, Vector) -> Vector
}))
```
### Type Refinements
The type checker narrows types based on control flow:
```luau
local x: string | number = getValue()
-- type() or typeof()
if type(x) == "string" then
local s: string = x
end
-- Truthy test rules out nil
local maybe: string? = getMaybe()
if maybe then
local s: string = maybe
end
-- Equality narrows to singleton
local s: string = getStr()
if s == "hello" then
local h: "hello" = s
end
-- and/or/not compose
if (type(x) == "string" or type(x) == "number") and x ~= nil then
-- x: string | number
end
-- assert() also refines
assert(type(x) == "string")
local s: string = x
```
### Sealed vs Unsealed Tables
**Unsealed** (table literal without annotation) — new properties may be added until the table leaves its defining scope:
```luau
local t = { x = 1 } -- unsealed: {x: number}
t.y = 2 -- ok
t.z = 3 -- ok
local u: { x: number, y: number? } = t -- ok, y is optional
```
**Sealed** (annotated or returned from a function) — locked; supports width subtyping:
```luau
local t: { x: number } = { x = 1 }
t.y = 2 -- not ok
type Point2D = { x: number, y: number }
type Point1D = { x: number }
local p: Point2D = { x = 5, y = 37 }
local q: Point1D = p -- ok, Point2D is a subtype (has extra properties)
```
### User-Defined Type Functions
Type functions run at analysis time and operate on types using the `types` library:
```luau
type function simple_keyof(ty)
if not ty:is("table") then
error("Can only call keyof on tables.")
end
local union = nil
for property in ty:properties() do
union = if union then types.unionof(union, property) else property
end
return if union then union else types.singleton(nil)
end
type Person = { name: string, age: number }
type Keys = simple_keyof<Person> -- "age" | "name"
```
A type's `tag` is one of: `"nil"`, `"unknown"`, `"never"`, `"any"`, `"boolean"`, `"number"`, `"string"`, `"singleton"`, `"negation"`, `"union"`, `"intersection"`, `"table"`, `"function"`, `"extern"`, `"thread"`, `"buffer"`. Use `ty:is("extern")` to test for Roblox class / foreign-host types (previously spelled `"class"`).
Useful `types` helpers beyond `unionof`/`intersectionof`/`singleton`:
- `types.optional(t)` — shorthand for `types.unionof(t, types.singleton(nil))`
- `types.negationof(t)` — negation type (regular Luau type syntax cannot write `~T`; this is only available inside type functions)
- `types.newtable(props, indexer?, metatable?)`, `types.newfunction(params, returns?, generics?)`, `types.copy(t)`, `types.generic(name?, ispack?)`
Type function environment: the `types` library plus `assert`, `error`, `print`, `next`, `pairs`, `ipairs`, `select`, `unpack`, `getmetatable`, `setmetatable`, `rawget`, `rawset`, `rawlen`, `raweq`, `tonumber`, `tostring`, `type`, `typeof`, and the `math`, `table`, `string`, `bit32`, `utf8`, `buffer` libraries.
## Roblox-Specific
For full Roblox Luau documentation, see `.cursor/docs/usergenerated/roblox/en-us/luau/`.
### Roblox Types in Annotations
All Roblox classes, data types, and enums are valid type annotations:
```luau
local part: Part = Instance.new("Part")
local color: BrickColor = part.BrickColor
local material: Enum.Material = part.Material
local pos: Vector3 = part.Position
local cf: CFrame = part.CFrame
```
### Use `Vector3`, Not `vector`
The `vector` primitive is not compatible with Roblox APIs. Use `Vector3`:
```luau
local pos = Vector3.new(1, 2, 3)
-- NOT: vector.create(1, 2, 3)
```
### Native Code Generation
`--!native` at the top of a script compiles its functions to machine code; `@native` does the same for an individual function. In Roblox, native code generation applies to **server-side** scripts only, and the engine enforces a shared code-size budget across the experience. Functions that call `getfenv`/`setfenv`, or pass non-numeric arguments to numeric builtins, fall back to interpreted execution.
## Module Require Semantics
### Roblox Luau (Instance requires)
```luau
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local MyModule = require(ReplicatedStorage.Modules.MyModule)
local Types = require(ReplicatedStorage.Shared.Types)
```
### Standalone Luau (String requires)
Outside Roblox (e.g., Lune, standalone tooling), requires use explicit string paths with mandatory prefixes:
```luau
local sibling = require("./sibling") -- Relative to current file
local parent = require("../parent") -- Parent directory
local lib = require("@lune/net") -- Alias (configured in .luaurc)
```
All paths must start with `./`, `../`, or `@` — bare names like `require("foo")` are rejected. Aliases are configured in `.luaurc`:
```json
{
"aliases": {
"lune": "packages/lune",
"shared": "src/shared"
}
}
```
### Cyclic Dependencies
Require paths must be statically resolvable. To break a cyclic module dependency, cast to `any`:
```luau
local myModule = require(MyModule) :: any
```
## Deprecated Functions
Deprecated in Luau:
- `getfenv`/`setfenv` — additionally disable compiler optimizations (imports, fastcalls, inlining)
- `table.getn` — use `#t` or `rawlen`
- `table.foreach`/`table.foreachi` — use `for..in` loops
- `wait()` (Roblox global) — use `task.wait()`
## Common Gotchas
### Raw Table Functions
`rawget`/`rawset`/`rawequal`/`rawlen` bypass metamethods:
```luau
local t = setmetatable({}, {
__index = function(self, key)
rawset(self, key, key * 10) -- Avoid triggering __newindex
return self[key]
end
})
```
### Metamethod Differences from Lua
- `__eq` is always called, even when operands are rawequal
- `__len` works on tables (not just userdata)
- `__iter` enables custom iteration
### No Bitwise Shift Operators
`<<` and `>>` do not exist (they would conflict with generic-instantiation syntax). Use `bit32.lshift`/`bit32.rshift`.
### Generalized Table Iteration
Tables can be iterated directly without `pairs`/`ipairs`:
```luau
for k, v in myTable do
-- ...
end
```
Iteration order is consecutive for elements `1..#t`, then unordered. Implement `__iter` on a metatable to provide custom iteration.
### Spreading Arrays with `unpack`
```luau
local args = {1, 2, 3}
print(unpack(args)) -- 1 2 3
```
### Function Attributes
```luau
@native
function hotFunction()
end
@deprecated
function oldFunction()
end
```
Attributes attach as metadata. Multiple attributes stack: `@attr1 @attr2 local function f() end`. `@inline` is not supported — the compiler handles inlining automatically.
## OOP (Language-Level)
The project's class/metatable pattern — type structure, `IsA`/`Assert` helpers, constructor params, metatable freezing — lives in `rules/luau-style.mdc`.
At the language level: when defining methods on a class table, the `self` parameter currently requires an explicit `self: T` annotation so the type checker can share `self`'s type across methods. (The shared-self types RFC is not yet implemented.)
## Standard Library Additions
Luau extends Lua 5.1's standard library. Highlights not covered elsewhere:
### Math
- `math.clamp(n, min, max)`, `math.sign(n)`, `math.round(n)` (halfway rounds away from 0)
- `math.lerp(a, b, t)` — exact at `t = 1`, monotonic; `math.map(x, inMin, inMax, outMin, outMax)`
- `math.noise(x, y?, z?)` — 3D Perlin noise in `[-1, 1]`
- `math.log(n, base?)` — optional base; `math.random()` uses a PCG RNG
- `math.isnan(x)`, `math.isinf(x)`, `math.isfinite(x)` — IEEE 754 checks
- Constants: `math.pi`, `math.huge`, `math.nan`, `math.e`, `math.phi`, `math.sqrt2`, `math.tau`
### String
```luau
string.split("a,b,c", ",") -- {"a", "b", "c"} (default separator is ",")
string.split("hello", "") -- {"h", "e", "l", "l", "o"}
-- Binary encoding (Lua 5.3 format strings; Luau uses fixed sizes:
-- short = 16-bit, long = 64-bit, int = 32-bit, size_t = 32-bit)
local packed = string.pack("i4f", 42, 3.14)
local i, f = string.unpack("i4f", packed)
local size = string.packsize("i4f") -- 8
```
### bit32
`bit32.countlz(n)` / `bit32.countrz(n)` (return 32 when `n` is 0) and `bit32.byteswap(n)`.
### coroutine
`coroutine.close(co)` puts a suspended/dead coroutine into a dead state and frees its stack. Returns `(true)` on success, `(false, error)` if the coroutine was in an error state.
## Immutable Tables
```luau
local config = table.freeze({ maxRetries = 3, timeout = 30 })
-- Clone before modifying
local newConfig = table.clone(config)
newConfig.maxRetries = 5
```
## Buffer Library
Fixed-size mutable byte arrays. Offsets are 0-based, reads/writes use little-endian byte order, and any access outside bounds throws.
```luau
local buf = buffer.create(1024) -- All bytes initialized to 0
local buf2 = buffer.fromstring("hello")
local str = buffer.tostring(buf2)
local len = buffer.len(buf)
```
- Numeric read/write families: `buffer.readi8`/`u8`/`i16`/`u16`/`i32`/`u32`/`f32`/`f64` and matching `write*`
- String: `buffer.readstring(b, off, count)`, `buffer.writestring(b, off, s, count?)`
- Bit-level: `buffer.readbits(b, bitOff, bitCount)` (`bitCount` in `[0, 32]`, unsigned result), `buffer.writebits(b, bitOff, bitCount, value)` (takes the least significant bits)
- Bulk: `buffer.copy(target, tOff, source, sOff?, count?)`, `buffer.fill(b, off, value, count?)`
## Vector Library
The `vector` primitive is a 3-component (4-component in 4-wide mode) immutable value type. Components are read via `.x`/`.y`/`.z` (and `.w` in 4-wide mode) but cannot be assigned individually.
```luau
local v = vector.create(1, 2, 3)
local zero = vector.zero -- (0, 0, 0)
local one = vector.one -- (1, 1, 1)
-- Component-wise: +, -, *, /, //, unary -
local sum = v + vector.create(4, 5, 6)
```
Operations: `vector.magnitude(v)`, `vector.normalize(v)`, `vector.dot(a, b)`, `vector.cross(a, b)` (3D only), `vector.angle(a, b, axis?)`, `vector.lerp(a, b, t)`, `vector.abs/sign/floor/ceil(v)`, `vector.clamp(v, min, max)`, `vector.max(...)`, `vector.min(...)`.
In Roblox, use `Vector3` instead — `Vector3` integrates with every Roblox API. The `vector` library is for standalone Luau and performance-critical native code.
## Differences from Lua
Luau is based on Lua 5.1 with selective features from 5.2–5.4 and its own additions:
- `_VERSION` is `"Luau"` (not `"Lua 5.1"`)
- Single number type: 64-bit double (no separate integer type)
- No tail call optimization (simplifies debugging and stack traces)
- `__eq` is always called, even when operands are rawequal
- No `goto` statement, no `__gc` metamethod (sandboxing)
- No `io`, `os.execute`, `package`, or full `debug` library (sandboxing)
- `loadstring` cannot load bytecode; `string.dump` is not available
- Table assignment order in literals follows program order (Lua 5.x may reorder)
- `function()` expressions may reuse a closure when all captured upvalues are identical
- `os.time` with a table argument returns UTC (not local time)