### CFrame and Vector3 Multiplication Example Source: https://github.com/luau-lang/site/blob/master/src/content/news/2022-10-31-luau-semantic-subtyping.md This example demonstrates a scenario where Luau's type system might report a false positive due to the interaction of CFrame multiplication with different types. It highlights the need for accurate type analysis. ```luau --!hidden FIXME: definitions for CFrame and Vector3 --!hidden mode=nocheck local x = CFrame.new() local y if (math.random()) then y = CFrame.new() else y = Vector3.new() end local z = x * y ``` -------------------------------- ### Direct string.byte() call example Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-06-20-luau-recap-june-2020.md Demonstrates the direct call to string.byte() for retrieving a byte value from a string at a specific position. ```luau local byteValue = string.byte(foo, 5) ``` -------------------------------- ### Luau Continue Statement Example Source: https://github.com/luau-lang/site/blob/master/src/content/docs/getting-started/syntax.md Demonstrates the `continue` statement in Luau, which must be the last statement in a block and is not a keyword. ```luau --!hidden mode=nocheck if x < 0 then continue end ``` -------------------------------- ### Declaring Array-like Table Types with Short Syntax (Luau) Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-10-30-luau-recap-october-2020.md This example shows the new, concise syntax for declaring an array-like table that holds string values. ```Luau {string} ``` -------------------------------- ### Luau Type Inference Examples Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Demonstrates Luau's type inference for basic types. Note that `any` allows type system bypass, which can lead to runtime errors. ```luau local s = "foo" local n = 1 local b = true local t = coroutine.running() local a: any = 1 print(a.x) -- Type checker believes this to be ok, but crashes at runtime. ``` -------------------------------- ### Example Runtime Error Message Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-06-20-luau-recap-june-2020.md Illustrates the improved runtime error message for type mismatches, now including the function name and specific type expectations. ```luau invalid argument #1 to 'abs' (number expected, got nil) ``` -------------------------------- ### Luau Compound Assignment Example Source: https://github.com/luau-lang/site/blob/master/src/content/docs/getting-started/syntax.md Demonstrates the usage of compound assignment operators like `+=` in Luau, noting they are statements, not expressions. ```luau local a = 5 -- this works a += 1 -- this doesn't work print(a += 1) ``` -------------------------------- ### Luau `unknown` Type Examples Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Shows how to declare variables with the `unknown` type, which acts as a top type but requires type refinements for safe usage. ```luau local a: unknown = "hello world!" local b: unknown = 5 local c: unknown = function() return 5 end ``` -------------------------------- ### Luau table.insert and table.remove Examples Source: https://context7.com/luau-lang/site/llms.txt Use `table.insert` to add elements at the end or a specific index, and `table.remove` to remove elements from the end or a specific index. These are efficient for array-like tables. ```luau -- Basic insertion (append) local fruits = {"apple", "banana"} table.insert(fruits, "cherry") print(table.concat(fruits, ", ")) --> apple, banana, cherry ``` ```luau -- Insert at specific position table.insert(fruits, 2, "apricot") print(table.concat(fruits, ", ")) --> apple, apricot, banana, cherry ``` ```luau -- Remove last element local last = table.remove(fruits) print(last) --> cherry ``` ```luau -- Remove at specific index local removed = table.remove(fruits, 2) print(removed) --> apricot print(table.concat(fruits, ", ")) --> apple, banana ``` ```luau -- Stack implementation local stack = {} local function push(value) table.insert(stack, value) end local function pop() return table.remove(stack) end push("first") push("second") push("third") print(pop()) --> third print(pop()) --> second ``` -------------------------------- ### Fastest Table Creation with table.create and Sequential Insertion Source: https://github.com/luau-lang/site/blob/master/src/content/docs/guides/performance.md For sequential table filling, using `table.create` with a known size and then inserting elements by index can be more efficient than `table.insert`. This example demonstrates building a table of squares. ```luau local t = table.create(N) for i=1,N do t[i] = i * i end ``` -------------------------------- ### Get Table Metatable Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Gets the table's metatable, or nil if it doesn't exist. ```luau tabletype:metatable(): type? ``` -------------------------------- ### Vector Creation Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Explains how to create new vector instances. ```APIDOC ## vector.create ### Description Creates a new vector with the given component values. The first constructor sets the fourth (`w`) component to 0.0 in _4-wide mode_. ### Parameters #### Overloads 1. **vector.create(x: number, y: number, z: number): vector** 2. **vector.create(x: number, y: number, z: number, w: number): vector** ### Usage ```luau local vec3 = vector.create(1.0, 2.0, 3.0) local vec4 = vector.create(1.0, 2.0, 3.0, 4.0) ``` ``` -------------------------------- ### Get UNIX timestamp with os.time() Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-06-20-luau-recap-june-2020.md Use os.time() to obtain a UNIX timestamp with a stable baseline from 1970 and 1-second resolution. This is recommended for getting a UNIX timestamp. ```luau local unixTimestamp = os.time() ``` -------------------------------- ### Select arguments from a varargs list Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md When called with '#', returns the number of arguments. Otherwise, returns a subset of arguments starting from the specified index. Index can be positive (from start) or negative (from end). ```luau function select(i: string, args: ...T): number ``` ```luau function select(i: number, args: ...T): ...T ``` -------------------------------- ### Instantiate and Cast a Part Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/roblox-types.md Demonstrates creating a new Part instance and assigning it to a variable typed as BasePart, showcasing implicit casting. ```luau --!hidden mode=nocheck local part = Instance.new("Part") local basePart: BasePart = part ``` -------------------------------- ### Luau Type Error Example with Semantic Subtyping Source: https://github.com/luau-lang/site/blob/master/src/content/news/2022-11-01-luau-recap-september-october-2022.md This example demonstrates a scenario where Luau's previous type system would report a false positive error. It involves multiplication between CFrame and Vector3 types. ```luau --!hidden FIXME: definitions for vector and cframe --!hidden mode=nocheck local x : CFrame = CFrame.new() local y : Vector3 | CFrame if (math.random()) then y = CFrame.new() else y = Vector3.new() end local z : Vector3 | CFrame = x * y -- Type Error! ``` -------------------------------- ### Enable New Lua VM Beta Source: https://github.com/luau-lang/site/blob/master/src/content/news/2019-11-11-luau-recap-november-2019.md To use the new debugger, ensure you are enrolled in the new Lua VM beta. This is typically done through a setting in your development environment. ```text ![Enable New Lua VM](../../assets/images/luau-recap-november-2019-option.png) ``` -------------------------------- ### Buffer Creation and Initialization Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Functions for creating and initializing buffer objects. ```APIDOC ## buffer.create(size: number): buffer ### Description Creates a buffer of the requested size with all bytes initialized to 0. The size limit is 1GB (1,073,741,824 bytes). ### Method `buffer.create` ### Parameters #### Path Parameters - **size** (number) - Required - The desired size of the buffer in bytes. ### Response Example ```json { "example": "buffer object" } ``` ## buffer.fromstring(str: string): buffer ### Description Creates a buffer initialized to the contents of the string. The size of the buffer equals the length of the string. ### Method `buffer.fromstring` ### Parameters #### Path Parameters - **str** (string) - Required - The string to initialize the buffer with. ### Response Example ```json { "example": "buffer object" } ``` ``` -------------------------------- ### Luau Type Checker Robustness Example Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-05-18-luau-recap-may-2020.md An example of obscure script syntax that the Luau type checker is designed to handle without crashing or entering unbounded recursion. This snippet is intended to test the robustness of the type checker. ```luau --!hidden mode=nocheck type ( ... ) ( ) ; ( ... ) ( - - ... ) ( - ... ) type = ( ... ) ; ( ... ) ( ) ( ... ) ; ( ... ) "" ``` -------------------------------- ### Get Negated Type Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns the type that is being negated. ```luau type:inner(): type ``` -------------------------------- ### Basic Coroutine Creation and Resumption Source: https://context7.com/luau-lang/site/llms.txt Demonstrates the creation, status checking, and resumption of a basic coroutine. Coroutines allow for cooperative multitasking. ```luau -- Basic coroutine local function counter(max: number) for i = 1, max do print(`Count: {i}`) coroutine.yield(i) end return "done" end local co = coroutine.create(counter) print(coroutine.status(co)) --> suspended local success, value = coroutine.resume(co, 5) print(success, value) --> true 1 coroutine.resume(co) --> Count: 2 coroutine.resume(co) --> Count: 3 ``` -------------------------------- ### Luau Structural Type System Example Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/overview.md Luau's type system is structural, comparing the shape of tables. This example shows type compatibility between `A` and `B` types, where `a2` is assignable to `A` but `b2` is not assignable to `B` due to a missing optional field. ```luau --!hidden FIXME(LUAU): there's a bug in the new type solver unfortunately --!hidden solver=old type A = {x: number, y: number, z: number?} type B = {x: number, y: number, z: number} local a1: A = {x = 1, y = 2} -- ok local b1: B = {x = 1, y = 2, z = 3} -- ok local a2: A = b1 -- ok local b2: B = a1 -- not ok ``` -------------------------------- ### Luau table.create for Pre-allocated Tables Source: https://context7.com/luau-lang/site/llms.txt Use `table.create` to pre-allocate space in a table, which can improve performance when the size is known. It can create an empty table with a capacity or a table filled with an initial value. ```luau -- Create empty table with capacity local largeArray = table.create(1000) for i = 1, 1000 do largeArray[i] = i * i end ``` ```luau -- Create table filled with initial value local zeros = table.create(10, 0) print(table.concat(zeros, ", ")) --> 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ``` ```luau -- Performance-optimized table building local function buildSquares(n: number): {number} local result = table.create(n) for i = 1, n do result[i] = i * i end return result end local squares = buildSquares(5) print(table.concat(squares, ", ")) --> 1, 4, 9, 16, 25 ``` -------------------------------- ### Get Buffer Length Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the total size of the buffer in bytes. ```luau function buffer.len(b: buffer): number ``` -------------------------------- ### Get Square Root - math.sqrt Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the square root of a number. ```luau function math.sqrt(n: number): number ``` -------------------------------- ### Get Hyperbolic Sine - math.sinh Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the hyperbolic sine of a number. ```luau function math.sinh(n: number): number ``` -------------------------------- ### Get Hyperbolic Cosine - math.cosh Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the hyperbolic cosine of a number. ```luau function math.cosh(n: number): number ``` -------------------------------- ### Get Intersection Components Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns an array of the types that are part of the intersection. ```luau intersectiontype:components() ``` -------------------------------- ### Fast Method Calls with `:` Syntax Source: https://github.com/luau-lang/site/blob/master/src/content/docs/guides/performance.md Use the colon syntax (`obj:Method`) for method calls, which is optimized by Luau. Avoid `obj.Method(obj)` syntax. Ensure `__index` in metatables points directly to a table for optimal performance. ```luau myObject:myMethod(arg1, arg2) ``` -------------------------------- ### Get Union Components Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns an array of the types that are part of the union. ```luau uniontype:components(): {type} ``` -------------------------------- ### Luau Table Utilities: concat, move, pack/unpack Source: https://context7.com/luau-lang/site/llms.txt Demonstrates table.concat for string joining, table.move for element transfer, and table.pack/unpack for variadic arguments and table expansion. ```luau -- Concatenate array elements into string local words = {"Hello", "World", "from", "Luau"} print(table.concat(words, " ")) --> Hello World from Luau print(table.concat(words, "-", 2, 3)) --> World-from ``` ```luau -- Move elements between tables local source = {1, 2, 3, 4, 5} local dest = {10, 20, 30} table.move(source, 2, 4, 4, dest) -- Copy source[2..4] to dest starting at index 4 print(table.concat(dest, ", ")) --> 10, 20, 30, 2, 3, 4 ``` ```luau -- Pack variadic arguments local function logArgs(...) local args = table.pack(...) print(`Received {args.n} arguments`) for i = 1, args.n do print(` [{i}] = {tostring(args[i])}`) end end logArgs("a", nil, "b", nil) -- Received 4 arguments -- [1] = a -- [2] = nil -- [3] = b -- [4] = nil ``` ```luau -- Unpack table to multiple values local coords = {10, 20, 30} local x, y, z = table.unpack(coords) print(x, y, z) --> 10 20 30 ``` -------------------------------- ### string.sub Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Extracts a substring from a string based on start and end positions. ```APIDOC ## string.sub ### Description Returns a substring of the input string with the byte range `[f..t]`; `t` defaults to `#s`, so a two-argument version returns a string suffix. ### Method `string.sub(s: string, f: number, t: number?): string` ``` -------------------------------- ### Singleton String and Boolean Types Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Demonstrates the use of singleton types for string literals ('Foo', 'Bar') and boolean literals (true, false). It shows valid assignments and type compatibility. ```luau local foo: "Foo" = "Foo" -- ok local bar: "Bar" = foo -- not ok local baz: string = foo -- ok local t: true = true -- ok local f: false = false -- ok ``` -------------------------------- ### Get Base-e Exponent - math.exp Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the base-e exponent of a number (e^n). ```luau function math.exp(n: number): number ``` -------------------------------- ### Support __len metamethod for tables Source: https://github.com/luau-lang/site/blob/master/src/content/news/2022-08-29-luau-recap-august-2022.md Demonstrates how tables now honor the `__len` metamethod and the `rawlen` function. Use this to define custom length behavior for tables. ```luau --!hidden FIXME: self should not need an annotation here when bidirectional typing works local my_cool_container = setmetatable({ items = { 1, 2 } }, { __len = function(self: { items: {number}}) return #self.items end }) print(#my_cool_container) --> 2 print(rawlen(my_cool_container)) --> 0 ``` -------------------------------- ### Get Function Generics Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns an array of the function's generic types. ```luau functiontype:generics(): {type} ``` -------------------------------- ### Create a Buffer Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Creates a new buffer of a specified size, with all bytes initialized to zero. The maximum size is 1GB. ```luau function buffer.create(size: number): buffer ``` -------------------------------- ### Module Path Resolution in Luau Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/considerations.md Demonstrates how Luau resolves module paths using `require`. Ensure module paths are statically resolvable for accurate type checking. ```luau --!file foo.luau local Bar = require("./bar") local baz1: Bar.Baz = 1 -- not ok local baz2: Bar.Baz = "foo" -- ok print(Bar.Quux) -- ok print(Bar.FakeProperty) -- not ok Bar.NewProperty = true -- not ok --!file bar.luau export type Baz = string local module = {} module.Quux = "Hello, world!" return module ``` -------------------------------- ### bit32.extract Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Extracts a specified number of bits from a number starting at a given position. ```APIDOC ## bit32.extract ### Description Extracts bits of `n` at position `f` with a width of `w`, and returns the resulting integer. `w` defaults to `1`, so a two-argument version of `extract` returns the bit value at position `f`. Bits are indexed starting at 0. Errors if `f` and `f+w-1` are not between 0 and 31. ### Method `bit32.extract(n, f, w?) ### Parameters - **n** (number) - The number from which to extract bits. - **f** (number) - The starting bit position (0-indexed). - **w** (number, optional) - The number of bits to extract. Defaults to 1. ### Return Value (number) - The integer value of the extracted bits. ``` -------------------------------- ### Define Types Using Type Packs Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Illustrates defining type aliases 'A', 'B', 'C', and 'D' using generic type packs, including variadic and generic type packs, and empty type packs. ```luau type A = (T) -> U... type B = A -- with a variadic type pack type C = A -- with a generic type pack type D = A -- with an empty type pack ``` -------------------------------- ### Get Table Length (Deprecated) Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the length of the table. Deprecated; use the # operator instead. ```luau function table.getn(t: {V}): number ``` -------------------------------- ### Get Sine - math.sin Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the sine of an angle in radians. Returns a value in the range [0, 1]. ```luau function math.sin(n: number): number ``` -------------------------------- ### Print arguments to standard output Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Prints all provided arguments to the standard output, separated by tabs. ```luau function print(args: ...any) ``` -------------------------------- ### Instantiate Signal Type with Specific Type Pack Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Demonstrates instantiating a generic 'Signal' type with a specific tuple type for its type pack and calling the generic 'call' function with matching arguments. ```luau type Signal = { f: (T, U...) -> (), data: T } local function call(s: Signal, ...: U...) end local signal: Signal = {} :: any call(signal, 1, 2, false) ``` -------------------------------- ### Get Cosine - math.cos Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the cosine of an angle in radians. Returns a value in the range [0, 1]. ```luau function math.cos(n: number): number ``` -------------------------------- ### Get Absolute Value - math.abs Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the absolute value of a number. Returns NaN if the input is NaN. ```luau function math.abs(n: number): number ``` -------------------------------- ### print Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md `print` outputs all provided arguments to the standard output, separated by tabs. ```APIDOC ## print ### Description Prints all arguments to the standard output, using Tab as a separator. ### Method N/A (Global Function) ### Endpoint N/A (Global Function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response None (This function prints to standard output) #### Response Example None ``` -------------------------------- ### Type Instance Properties and Methods Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Properties and methods available on `type` instances. ```APIDOC ### `type` instance `type` instances can have extra properties and methods described in subsections depending on its tag. #### `type.tag: "nil" | "unknown" | "never" | "any" | "boolean" | "number" | "string" | "singleton" | "negation" | "union" | "intersection" | "table" | "function" | "extern" | "thread" | "buffer"` An immutable property holding the type's tag. #### `__eq(arg: type): boolean` Overrides the `==` operator to return `true` if `self` is syntactically equal to `arg`. This excludes semantically equivalent types, `true | false` is unequal to `boolean`. #### `type:is(arg: "nil" | "unknown" | "never" | "any" | "boolean" | "number" | "string" | "singleton" | "negation" | "union" | "intersection" | "table" | "function" | "extern" | "thread" | "buffer")` Returns `true` if `self` has the argument as its tag. ``` -------------------------------- ### Extern Type Parent Write Type Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Gets the type for writing to the parent of an extern type instance. ```APIDOC ## Extern Type Parent Write Type ### Description Returns the type for writing to this extern type's parent, or returns `nil` if the parent doesn't exist. ### Method `externtype:writeparent()` ### Endpoint N/A (Method call on an extern type instance) ### Parameters None ### Request Example ```lua -- Assuming 'myExternType' is an instance of an extern type local parentWriteType = myExternType:writeparent() print(parentWriteType) ``` ### Response #### Success Response (200) - **parentWriteType** (type or nil) - The type for writing to the parent, or `nil` if the parent does not exist. #### Response Example ```lua -- Example output if parent exists and is a number type "number" -- Example output if parent does not exist nil ``` ``` -------------------------------- ### Extern Type Parent Read Type Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Gets the type for reading the parent of an extern type instance. ```APIDOC ## Extern Type Parent Read Type ### Description Returns the type of reading this extern type's parent, or returns `nil` if the parent doesn't exist. ### Method `externtype:readparent()` ### Endpoint N/A (Method call on an extern type instance) ### Parameters None ### Request Example ```lua -- Assuming 'myExternType' is an instance of an extern type local parentReadType = myExternType:readparent() print(parentReadType) ``` ### Response #### Success Response (200) - **parentReadType** (type or nil) - The type for reading the parent, or `nil` if the parent does not exist. #### Response Example ```lua -- Example output if parent exists and is a string type "string" -- Example output if parent does not exist nil ``` ``` -------------------------------- ### Luau Variadic Type Annotation Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Demonstrates how to use type annotations for variadic arguments (`...`) to specify the expected type of multiple arguments. ```luau local function f(...: number) end f(1, 2, 3) -- ok f(1, "string") -- not ok ``` -------------------------------- ### Get All Table Property Types Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns a table mapping property keys to their read and write types. ```luau tabletype:properties(): { [type]: { read: type?, write: type? } } ``` -------------------------------- ### Luau ComparisonPrecedence Lint Examples Source: https://github.com/luau-lang/site/blob/master/src/content/news/2022-08-29-luau-recap-august-2022.md Demonstrates cases where the `ComparisonPrecedence` lint fires due to ambiguous operator precedence with `not` and chained comparisons. Use parentheses or alternative operators to silence warnings. ```luau local x, y = 6, 7 -- not X == Y is equivalent to (not X) == Y; consider using X ~= Y, or wrap one of the expressions in parentheses to silence if not x == y then end -- not X ~= Y is equivalent to (not X) ~= Y; consider using X == Y, or wrap one of the expressions in parentheses to silence if not x ~= y then end -- not X <= Y is equivalent to (not X) <= Y; wrap one of the expressions in parentheses to silence if not x <= y then end -- X <= Y == Z is equivalent to (X <= Y) == Z; wrap one of the expressions in parentheses to silence if x <= y == 0 then end ``` -------------------------------- ### Get High-Precision Timestamp Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns a high-precision timestamp in seconds for measuring durations with sub-microsecond accuracy. The baseline is not defined. ```luau function os.clock(): number ``` -------------------------------- ### State Machine with coroutine.wrap Source: https://context7.com/luau-lang/site/llms.txt Implements a state machine using coroutine.wrap, simulating a traffic light. Each call to the wrapped function transitions the state. ```luau -- State machine local function trafficLight() return coroutine.wrap(function() while true do coroutine.yield("green", 30) coroutine.yield("yellow", 5) coroutine.yield("red", 25) end end) end local light = trafficLight() for i = 1, 6 do local color, duration = light() print(`{color} for {duration}s`) end ``` -------------------------------- ### Get Maximum Numeric Key Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the maximum numeric key of a table, or zero if no numeric keys exist. ```luau function table.maxn(t: {V}): number ``` -------------------------------- ### table.create Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Creates a new table with a specified number of elements, optionally pre-filled with a value. ```APIDOC ## table.create ### Description Creates a table with `n` elements; all of them (range `[1..n]`) are set to `v`. When `v` is nil or omitted, the returned table is empty but has preallocated space for `n` elements which can make subsequent insertions faster. Note that preallocation is only performed for the array portion of the table - using `table.create` on dictionaries is counter-productive. ### Method `table.create(n: number, v: V?): {V} ``` -------------------------------- ### Get Extern Type Metatable Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Retrieves the metatable associated with an extern type. Returns nil if no metatable is defined. ```luau externtype:metatable(): type? ``` -------------------------------- ### Pack Binary Data with string.pack Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-08-11-luau-recap-august-2020.md Use string.pack to serialize data into a compact binary format, reducing network traffic. Note that binary strings are not currently safe for DataStores. ```luau --!hidden mode=nocheck local characterStateFormat = "fffbbbB" local characterState = string.pack(characterStateFormat, posx, posy, posz, dirx * 127, diry * 127, dirz * 127, health) ``` -------------------------------- ### Get Function Parameters Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns the function's parameters, including ordered parameters and an optional variadic tail. ```luau functiontype:parameters(): { head: {type}?, tail: type? } ``` -------------------------------- ### Array-like Table Declaration Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/tables.md Illustrates the concise syntax for declaring array-like tables where keys are numbers. This is equivalent to `{[number]: string}` but more readable for common array patterns. ```luau local t = {"Hello", "world!"} -- {[number]: string} print(table.concat(t, ", ")) ``` -------------------------------- ### Create Table with Preallocated Space Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Creates a table with a specified number of elements, optionally initializing them to a given value. Preallocates space for the array portion for potential performance benefits. ```luau function table.create(n: number, v: V?): {V} ``` -------------------------------- ### Get Floating-Point Modulo - math.fmod Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the remainder of x modulo y, rounded towards zero. Returns NaN if y is zero. ```luau function math.fmod(x: number, y: number): number ``` -------------------------------- ### Luau Type Annotations Syntax Source: https://github.com/luau-lang/site/blob/master/src/content/news/2020-01-16-luau-type-checking-beta.md Demonstrates the new syntax for type annotations in Luau, including local variables, function parameters, return types, type aliases, and type casting with the 'as' keyword. ```luau local foo: number = 55 function is_empty(param: string) => boolean return 0 == param:len() end type Point = {x: number, y: number} local baz = quux as number ``` -------------------------------- ### Get Arc Tangent - math.atan Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Returns the arc tangent of a number in radians. Returns a value in the range [-pi/2, pi/2]. ```luau function math.atan(n: number): number ``` -------------------------------- ### Extern Type Indexer Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Gets the indexer definition for an extern type, including index, read, and write result types. ```APIDOC ## Extern Type Indexer ### Description Returns the extern type's indexer, or `nil` if it doesn't exist. The indexer defines how the type can be indexed. ### Method `externtype:indexer()` ### Endpoint N/A (Method call on an extern type instance) ### Parameters None ### Request Example ```lua -- Assuming 'myExternType' is an instance of an extern type local indexer = myExternType:indexer() print(indexer) ``` ### Response #### Success Response (200) - **indexer** (table or nil) - A table describing the indexer, or `nil` if it does not exist. - **index** (type) - The type of the index. - **readresult** (type) - The type of the result when reading via indexing. - **writeresult** (type) - The type of the result when writing via indexing. #### Response Example ```json { "index": "string", "readresult": "number", "writeresult": "boolean" } ``` ``` -------------------------------- ### Inlining with Constant Argument Propagation Source: https://github.com/luau-lang/site/blob/master/src/content/news/2025-12-19-luau-recap-runtime-2025.md Shows how the inlining cost model is updated per call to account for constant arguments. This allows large functions to collapse into smaller ones, making them more suitable for inlining, even when arguments are not literal values. ```luau --!hidden mode=nocheck local function getValue(name: string): number? if name == 'a' then return -1.0 elseif name == 'b' then return 2.0 * math.pi elseif name == 'c' then return custom else return nil end end -- For any name, function collapses into a single simple return statement with a low inline cost local v = getValue("b") ``` -------------------------------- ### Get Singleton Value Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md For singleton types, use the value() method to retrieve the actual literal value the type represents. ```luau singletontype:value(): boolean | nil | "string" ``` -------------------------------- ### Create a Luau Script Source: https://github.com/luau-lang/site/blob/master/src/content/docs/getting-started/intro.md This script demonstrates basic function definitions and calls in Luau's non-strict mode. It shows how Luau handles type mismatches without explicit annotations by not reporting errors. ```luau --!hidden mode=nonstrict function ispositive(x) return x > 0 end print(ispositive(1)) print(ispositive("2")) function isfoo(a) return a == "foo" end print(isfoo("bar")) print(isfoo(1)) ``` -------------------------------- ### Implement `simple_keyof` Type Function in Luau Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/type-functions.md This example shows how to implement a custom type function `simple_keyof` that takes a table type and returns a union of its property names. It includes basic type checking and handles cases where the input is not a table. This function runs during analysis time. ```luau type function simple_keyof(ty) -- Ignoring unions or intersections of tables for simplicity. 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, } --- keys = "age" | "name" type keys = simple_keyof ``` -------------------------------- ### Luau Tree Insertion Function Source: https://github.com/luau-lang/site/blob/master/src/content/docs/getting-started/syntax.md Example of a Luau function for inserting into a tree structure, utilizing `split` and `merge3` functions. ```luau local function tree_insert(tree, x) local lower, equal, greater = split(tree.root, x) if not equal then equal = { x = x, y = math.random(0, 2^31-1), left = nil, right = nil } end tree.root = merge3(lower, equal, greater) end ``` -------------------------------- ### Basic Faux OOP Structure in Luau Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/object-oriented-programs.md This code demonstrates a common object-oriented pattern in Luau without explicit type annotations. It shows the basic structure of a class with a constructor and methods, highlighting potential type inference issues with `self`. ```luau local Account = {} Account.__index = Account function Account.new(name, balance) local self = {} self.name = name self.balance = balance return setmetatable(self, Account) end -- The `self` type is different from the type returned by `Account.new` function Account:deposit(credit) self.balance += credit end -- The `self` type is different from the type returned by `Account.new` function Account:withdraw(debit) self.balance -= debit end local account = Account.new("Alexander", 500) ``` -------------------------------- ### Get a value from a table bypassing metatables Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Performs a table lookup for index `k` and returns the value, bypassing metatables and `__index`. ```luau function rawget(t: { [K]: V }, k: K): V? ``` -------------------------------- ### Luau Continue Statement Examples Source: https://context7.com/luau-lang/site/llms.txt Demonstrates skipping iterations in loops using the continue statement. Use to skip even numbers, invalid data, or diagonal elements in nested loops. ```luau -- Skip specific values for i = 1, 10 do if i % 2 == 0 then continue -- Skip even numbers end print(i) end -- 1 3 5 7 9 ``` ```luau -- Skip invalid data local data = {"valid", "", "also valid", nil, "more"} local results = {} for i, item in data do if not item or item == "" then continue end table.insert(results, item) end print(table.concat(results, ", ")) --> valid, also valid, more ``` ```luau -- Nested loops with continue for x = 1, 3 do for y = 1, 3 do if x == y then continue -- Skip diagonal end print(`({x}, {y})`) end end ``` -------------------------------- ### Producer-Consumer Coroutine Pattern Source: https://context7.com/luau-lang/site/llms.txt Implements a producer-consumer pattern using coroutines. The producer yields items, and the consumer resumes the producer to get them. ```luau -- Producer-consumer pattern local function producer() local items = {"apple", "banana", "cherry"} for _, item in items do coroutine.yield(item) end end local function consumer(prod) while coroutine.status(prod) ~= "dead" do local ok, item = coroutine.resume(prod) if ok and item then print(`Consumed: {item}`) end end end consumer(coroutine.create(producer)) -- Consumed: apple -- Consumed: banana -- Consumed: cherry ``` -------------------------------- ### Get Table Indexer Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns the table's indexer as a table, including read and write types, or nil if it doesn't exist. ```luau tabletype:indexer(): { index: type, readresult: type, writeresult: type } ``` -------------------------------- ### Table.create Usage Source: https://github.com/luau-lang/site/blob/master/src/content/news/2019-11-11-luau-recap-november-2019.md This function creates an array-like table quickly. It can optionally pre-fill elements with a specified value. ```lua local newTable = table.create(5, 0) -- newTable is now {0, 0, 0, 0, 0} ``` -------------------------------- ### Create Buffer from String Source: https://context7.com/luau-lang/site/llms.txt Creates a buffer initialized with the content of a string. Useful for converting string data to binary format. ```luau -- Create from string local strBuf = buffer.fromstring("Hello") print(buffer.len(strBuf)) --> 5 print(buffer.tostring(strBuf)) --> Hello ``` -------------------------------- ### Get Table Write Property Type Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns the type used for writing values to a table property, or nil if the property does not exist. ```luau tabletype:writeproperty(key: type): type? ``` -------------------------------- ### Get Table Read Property Type Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Returns the type used for reading values from a table property, or nil if the property does not exist. ```luau tabletype:readproperty(key: type): type? ``` -------------------------------- ### Connect Event Handler with Bidirectional Typechecking in Luau Source: https://github.com/luau-lang/site/blob/master/src/content/news/2021-09-30-luau-recap-september-2021.md Example of connecting an event handler using Luau's bidirectional typechecking. This allows the type system to infer argument types for callbacks based on the event signature. ```luau --!hidden mode=nocheck part.Touched:Connect(function(other) -- ... end) ``` -------------------------------- ### Get Generic Type Name Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md For generic types, use the name() method to retrieve the name assigned to the generic, or nil if it is unnamed. ```luau generictype:name(): string? ``` -------------------------------- ### Run Luau profiler Source: https://github.com/luau-lang/site/blob/master/src/content/docs/guides/profile.md Execute a Luau script with the `--profile` argument to generate profiling data. Ensure you are using an optimized build of the interpreter for accurate results. The output file is named `profile.out` by default. ```bash $ luau --profile tests/chess.lua OK 8902 rnbqkbnr/pppppppp/8/8/8/8/PPPPPPPP/RNBQKBNR w KQkq - 0 1 OK 2039 r3k2r/p1ppqpb1/bn2pnp1/3PN3/1p2P3/2N2Q1p/PPPBBPPP/R3K2R w KQkq - 0 0 OK 2812 8/2p5/3p4/KP5r/1R3p1k/8/4P1P1/8 w - - 0 0 OK 9467 r3k2r/Pppp1ppp/1b3nbN/nP6/BBP1P3/q4N2/Pp1P2PP/R2Q1RK1 w kq - 0 1 OK 1486 rnbq1k1r/pp1Pbppp/2p5/8/2B5/8/PPP1NnPP/RNBQK2R w KQ - 1 8 OK 2079 r4rk1/1pp1qppp/p1np1n2/2b1p1B1/2B1P1b1/P1NP1N2/1PP1QPPP/R4RK1 w - - 0 10 Profiler dump written to profile.out (total runtime 2.034 seconds, 20344 samples, 374 stacks) GC: 0.378 seconds (18.58%), mark 46.80%, remark 3.33%, atomic 1.93%, sweepstring 6.77%, sweep 41.16% ``` -------------------------------- ### Iterate Over UTF-8 Codepoints Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/library.md Provides an iterator to loop through each Unicode codepoint and its starting byte offset in a string. Ideal for character-by-character processing. ```luau function utf8.codes(s: string): ``` -------------------------------- ### Singleton Type Instance Methods Source: https://github.com/luau-lang/site/blob/master/src/content/docs/reference/types-library.md Methods specific to singleton type instances. ```APIDOC ### Singleton `type` instance #### `singletontype:value(): boolean | nil | "string"` Returns the singleton's actual value, like `true` for `types.singleton(true)`. ``` -------------------------------- ### Type Refinements in Luau Source: https://context7.com/luau-lang/site/llms.txt Demonstrates various ways to narrow down types using control flow analysis in Luau. Useful for ensuring type safety within conditional blocks. ```luau --!strict -- Truthy refinement local function processOptional(value: string?) if value then -- value is refined to string (not nil) print(value:upper()) end end -- Type guard refinement local function processUnknown(value: unknown) if type(value) == "string" then print(value:upper()) -- value is string elseif type(value) == "number" then print(value * 2) -- value is number elseif type(value) == "table" then print(#value) -- value is table end end -- Equality refinement local function processLiteral(value: string) if value == "admin" then -- value is refined to literal type "admin" print("Admin access granted") end end -- Combined refinements local function validate(data: {type: string, value: unknown}) if data.type == "number" and type(data.value) == "number" then return data.value * 2 elseif data.type == "string" and type(data.value) == "string" then return data.value:upper() end return nil end -- Assert refinement local function requireString(value: unknown): string assert(type(value) == "string", "Expected string") -- value is refined to string return value end ``` -------------------------------- ### Table.find Usage Source: https://github.com/luau-lang/site/blob/master/src/content/news/2019-11-11-luau-recap-november-2019.md This function quickly finds the numeric index of a given value within a table. An optional starting index can be provided. ```lua local list = {"a", "b", "c", "b"} print(table.find(list, "b")) -- Output: 2 print(table.find(list, "b", 3)) -- Output: 4 ``` -------------------------------- ### Luau `never` Type Example Source: https://github.com/luau-lang/site/blob/master/src/content/docs/types/basic-types.md Shows a scenario where type refinements lead to a variable being typed as `never`, indicating an impossible state. ```luau local function unknown(): unknown return 5 end local x = unknown() if typeof(x) == "number" and typeof(x) == "string" then print(x) -- x : never end ``` -------------------------------- ### Luau Signature Help for FindFirstChild Source: https://github.com/luau-lang/site/blob/master/src/content/news/2023-11-01-luau-recap-october-2023.md Shows the corrected signature help tooltip for the `game:FindFirstChild` function in Luau. Previously, it erroneously suggested a 'self' argument; now it correctly displays the expected signature. ```luau --!hidden mode=nocheck game:FindFirstChild( ```