-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathluau-style.mdc
More file actions
429 lines (330 loc) · 13.8 KB
/
luau-style.mdc
File metadata and controls
429 lines (330 loc) · 13.8 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
---
globs: **/*.luau
alwaysApply: false
---
# Code Style
## File Headers
- Always use `--!strict` at the top of every Luau file, followed by one empty line before code begins
- For performance-critical functions, use `@native` on individual functions instead of file-level `--!native`
```luau
@native
local function HotPath(x: number): number
-- ...
end
```
## Code Preservation
- Do NOT clean up, refactor, or reformat existing code unless you are specifically modifying that EXACT section
- Only clean up a file when explicitly asked to do so
- Leave surrounding code untouched even if it doesn't match current style conventions
## Section Banners
- Use exactly 30 dashes on each side with spaces to separate major sections
- Common sections: Imports → Types → Constants → Asserts → Variables → Algorithm → Implementation → Header → Class → Module
- Format: `------------------------------ Section Name ------------------------------`
```luau
------------------------------ Imports ------------------------------
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Bindable = require(...)
------------------------------ Types ------------------------------
type Fields<self> = {}
------------------------------ Constants ------------------------------
local MaxValue = 100
------------------------------ Class ------------------------------
-- ...
```
## Naming Conventions
- Use PascalCase for:
- Module-level local functions (`LerpEN`, `ProcessData`)
- Module-level local variables/constants (`DefaultDuration`, `MaxRetries`)
- Module functions, class methods, and class fields (both public and private)
- Use camelCase only for function-local variables and parameters
- Prefix optional parameters with `_` (e.g., `_timeout: number?`), then normalize to local without prefix
```luau
local function processData(
value: string,
_timeout: number?
): boolean
local timeout = _timeout or 5
-- ...
end
```
## Conventions
- Always type function parameters and return values—this enables inference everywhere else
- Don't redundantly annotate locals when the type is inferred (e.g., `local x = 3` not `local x: number = 3`)
- Use `T?` for optional types—NEVER use `T | nil` (e.g., `number?` not `number | nil`)
- Use generics including `P...` and `R...` for variadic type packs
- Validate with `assert`; normalize optional `_args` to locals
- `pcall` callbacks; log errors with `warn()`
- Freeze module tables and Class tables; optionally freeze `self`
- Use local functions to optimize for inlining, then assign to Class table if needed
- Static helpers and singletons belong on the module table
- Always use `table.freeze()` for final module exports where possible
- Use raw `for..in` iteration—never use `ipairs` or `pairs` (raw generalized iteration is faster)
- Use `continue` to skip loop iterations instead of nested conditionals
- Use `bit32.bor(x, 0)` to ensure 32-bit unsigned integer wraparound
- Place `assert` calls at the start of functions for parameter validation
- Use `table.create(size, value)` for preallocation when size is known
- Use `table.pack()` for variable return values with `n` field for actual count
- Export module functions can be assigned directly: `module.IsA = IsA`
- For buffer operations, prefer buffer methods over string conversion when possible
- Use `table.concat(parts)` instead of repeated string concatenation
- Use backtick string interpolation for simple concatenation (lowers to optimized `string.format`)
- Use compound assignment operators (`+=`, `-=`, `*=`, `//=`, `..=`)—LHS evaluated once
- Use `a // b` instead of `math.floor(a / b)` (dedicated VM opcode, supports `//=`)
- Hoist library functions in hot paths: `local floor = math.floor` enables GETIMPORT fastcall
- Use `math.lerp(a, b, t)` instead of `a + (b - a) * t` (exact at endpoints, monotonic)
- Use `table.find(t, v)` instead of manual linear search loops
- Use `table.clone(t)` instead of manual `pairs` clone
- Use `bit32.byteswap(n)` and `bit32.countlz(n)` instead of manual implementations (CPU instructions)
- Use `obj:Method()` not `obj.Method(obj)` for fast method call instruction
- Use `if expr then A else B` over `cond and A or B` (one branch, safe for falsy values)
- Move `pcall` out of hot loops—it prevents native codegen optimization
- Use `string.method(s, ...)` over `s:method(...)` (fastcall path)
- NEVER use `getfenv`/`setfenv`/`loadstring`—they disable ALL optimizations (imports, fastcalls, inlining)
```luau
-- WRONG: ipairs/pairs adds overhead
for _, effect in ipairs(activeEffects) do
table.insert(effects, effect)
end
-- CORRECT: Raw iteration
for _, effect in activeEffects do
table.insert(effects, effect)
end
-- CORRECT: Raw dictionary iteration
for key, value in data do
print(key, value)
end
-- Use continue to simplify loop logic
for i = 1, 10 do
if i % 2 == 0 then continue end
print(i) -- Only odd numbers
end
```
```luau
-- WRONG: math.floor(a / b)
local index = math.floor(offset / stride)
-- CORRECT: Floor division (dedicated VM opcode)
local index = offset // stride
-- WRONG: Manual lerp (imprecise at t=1)
local result = a + (b - a) * t
-- CORRECT: math.lerp (exact at endpoints, monotonic)
local result = math.lerp(a, b, t)
-- Compound assignment (LHS evaluated once)
data[key].Score += delta
-- Library hoisting for hot paths
local floor = math.floor
local abs = math.abs
-- String interpolation (lowers to optimized string.format)
warn(`[{scriptName}] Failed to load {assetId}: {err}`)
-- WRONG: getfenv/setfenv/loadstring disable ALL optimizations
local env = getfenv() -- even read-only deoptimizes the entire file
-- CORRECT: Use debug.info for caller context
local source, line = debug.info(2, "sl")
```
## Documentation
- Use `--[[...]]` for multi-line docstrings above functions
- Include `@param` and `@return` descriptions for complex functions
- Keep comments concise; code should be self-documenting
- Use TODO comments with priority levels: `-- TODO(low):`, `-- TODO(high):`, `-- TODO(optimize):`
- Use `--stylua: ignore` to disable stylua formatting for specific lines (e.g., large data tables)
```luau
-- TODO(low): Implement cycle detection
-- TODO(optimize): convert all functions to local functions!
--[[
TODO(low): Implement cycle detection
TODO(optimize): convert all functions to local functions!
Validates and normalizes input data.
@param value Input value to validate
@param rules Validation rules to apply
@return Normalized value or error
]]
local function validate(value: string, rules: {Rule}): Result
-- ...
end
```
## OOP Pattern
### Type Structure
All field and method names use PascalCase, regardless of visibility.
Keep class type definitions in a bulk block with no blank lines between them.
Always use `Type` for the export (so users can do `Module.Type`).
No `PrivateFunctions` type - private functions are just local functions called directly (not via `self:`):
```luau
type Fields<self> = {
Value: number,
Name: string,
}
type Functions<self> = {
GetValue: (self) -> number,
SetName: (self, name: string) -> (),
}
type PrivateFields<self> = Fields<self> & {
InternalState: boolean,
Connection: RBXScriptConnection?,
}
export type Type = Fields<Type> & Functions<Type>
type Private = PrivateFields<Private>
```
For performance-critical code, private field names can be abbreviated with comments:
```luau
type PrivateFields<self> = Fields<self> & {
Ow: any?, -- Owner
Cb: (...any) -> (...any), -- Callback
Pr: number, -- Priority
}
```
For generic classes with variadic type packs:
```luau
type Fields<self, P..., R...> = { ... }
type Private<P... = ...any, R... = ...any> =
PrivateFields<Private<P..., R...>, P..., R...>
& PrivateFunctions<Private<P..., R...>, P..., R...>
```
### Class Implementation
Define local functions first, then build and freeze the Class table with only public methods.
Private functions are just local functions called directly (not added to Class):
```luau
------------------------------ Class ------------------------------
-- Private function (not added to Class)
local function UpdateInternal(self: Private)
-- ...
end
-- Public functions
local function Foo(self: Private, ...): T
UpdateInternal(self) -- Call directly, not self:UpdateInternal()
-- ...
end
local function Bar(self: Private): number
return self.Value
end
local Class: Functions<Private> = table.freeze({
Foo = Foo,
Bar = Bar,
})
local Metatable = table.freeze({ __index = Class })
```
### Module Export
Always export `IsA` and `Assert` helper functions for type checking:
```luau
------------------------------ Helpers ------------------------------
local function IsA(v: Type): boolean
return type(v) == "table" and getmetatable(v :: any) == Metatable
end
local function Assert(v: Type): Type
if not IsA(v) then error("<ClassName>", 2) end
return v
end
-- Params type and AssertParams go here (see Constructor Params)
------------------------------ Module ------------------------------
local module = {}
function module.new(params: Params): Type
-- ...
end
module.IsA = IsA
module.Assert = Assert
return table.freeze(module)
```
The `IsA` function uses metatable identity checking for fast, reliable type validation.
The `Assert` function provides runtime type checking with proper error levels.
### Constructor Params
When a class has a constructor that takes a params table, use `Params` (not `Config`):
1. Define an exported `Params` type after `IsA`/`Assert` helpers
2. Place `AssertParams` validator immediately after (no blank line)
3. Place `local module = {}` after the params
4. Validate params at the start of `module.new()`
See @asserts.mdc for the full `Asserts` module API.
```luau
export type Params = {
Callback: (value: number) -> (),
Duration: number?,
EasingStyle: Enum.EasingStyle?,
}
local AssertParams = Asserts.Table({
Callback = Asserts.Function,
Duration = Asserts.Optional(Asserts.FinitePositive),
EasingStyle = Asserts.Optional(Asserts.Enum(Enum.EasingStyle)),
})
local module = {}
function module.new(params: Params): Type
AssertParams(params)
local fields: PrivateFields<Private> = {
Callback = params.Callback,
Duration = params.Duration or DefaultDuration,
EasingStyle = params.EasingStyle or DefaultEasingStyle,
-- Don't initialize nil fields - they're implicit
}
local self: Private = setmetatable(fields, Metatable) :: any
return self
end
```
## Type Safety
- Strive for zero type errors in every file for good static analysis
- Avoid `:: any` unless absolutely necessary (e.g., metatable assignment)—it actively tells the compiler to give up optimization
- Prefer type refinements (`type()`, `typeof()`, `:IsA()`, `assert()`) over casts to provide type info from runtime checks
- When a cast is needed, use the narrowest type possible (`:: SpecificType`), never `:: any` as a shortcut
- Do not fix existing type errors unless explicitly asked
- **Never cast after `:IsA()` refinement**—Luau narrows the type automatically inside `if inst:IsA("X")` and after `assert(inst:IsA("X"))`
- **Prefer `assert(inst:IsA("X"), msg)` over `if not inst:IsA("X") then error(msg) end`**—`assert(:IsA())` narrows; guard-clause-with-`error()` does not
- **Use `assert(x)` to remove optional types** instead of `x :: Type` (e.g., `assert(part.Parent)` not `part.Parent :: Instance`)
- **For untyped API returns, define a local type and annotate the variable** instead of casting each access to `:: any`
- **Acceptable `:: any` uses**: metatable assignment, dynamic property access (`inst[name]`), string-based Enum indexing, single `:: any` at `GetService` binding for untyped services (always paired with a typed local annotation), accessing unofficial/unscriptable properties not in the type database
```luau
-- Only use :: any when required, such as complex setmetatable
local self: Private = setmetatable(fields, Metatable) :: any
-- WRONG: Casting to any silences the error but kills codegen
local value = data.Field :: any
-- CORRECT: Narrow with a runtime check (compiler uses the refinement)
if type(data.Field) == "number" then
local value = data.Field
end
-- WRONG: Redundant cast after :IsA() refinement
if inst:IsA("Model") then
(inst :: Model):ScaleTo(2)
end
-- CORRECT: :IsA() already narrowed the type
if inst:IsA("Model") then
inst:ScaleTo(2)
end
-- WRONG: guard clause doesn't narrow
if not inst:IsA("BasePart") then error("not a part") end
local cf = (inst :: BasePart).CFrame
-- CORRECT: assert narrows
assert(inst:IsA("BasePart"), "not a part")
local cf = inst.CFrame
-- WRONG: cast each access on an untyped API return
local item = (result :: any).Field
-- CORRECT: define the shape, annotate the local
type ApiResult = { Field: string, Count: number }
local result: ApiResult = SomeUntypedApi()
```
## Common Patterns
### Helper Functions
Place helper functions before the section where they're used:
```luau
------------------------------ Helpers ------------------------------
local function helperFunction(x: number): number
return x * 2
end
------------------------------ Class ------------------------------
local function DoSomething(self: Private): number
return helperFunction(self.Value)
end
local Class: Functions<Private> = table.freeze({
DoSomething = DoSomething,
})
local Metatable = table.freeze({ __index = Class })
```
### Module Singletons
For shared state or singleton instances, add them to the module table:
```luau
local module = {}
module.R = module.Unique() -- Singleton random generator
return table.freeze(module)
```
## Game Logic
Focus on modular, reusable, and simple code:
- Break complex logic into small, testable functions
- Prefer clarity in cold paths; apply the Conventions performance patterns in hot paths (RunService handlers, inner loops, recursive functions)
- Keep functions focused on a single responsibility
- Use descriptive variable names over abbreviated ones
## Validation
For runtime type assertions, see @asserts.mdc
Especially important for networking—always validate data received from remotes.