### Luau Semantic Subtyping Example Source: https://luau.org/news/2022-11-01-luau-recap-september-october-2022 Demonstrates a type error in Luau that is resolved by the new semantic subtyping feature. The example shows how a multiplication operation between CFrame and Vector3/CFrame types is incorrectly flagged as an error due to syntax-driven subtyping, but is correctly handled by semantic subtyping. ```Luau 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! ``` ```Luau type Example1 = ((CFrame, CFrame) -> CFrame) & ((CFrame, Vector3) -> Vector3) ``` ```Luau type Example2 = (CFrame, Vector3 | CFrame) -> (Vector3 | CFrame) ``` -------------------------------- ### Luau ComparisonPrecedence Lint Examples Source: https://luau.org/news/2022-08-29-luau-recap-august-2022 Demonstrates cases where the `ComparisonPrecedence` lint in Luau will trigger, highlighting potential ambiguities in boolean and comparison operations. It suggests using parentheses or alternative operators to resolve these 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 ``` -------------------------------- ### Corrected Luau Type Annotation Example Source: https://luau.org/getting-started Presents a corrected Luau script where the function return type annotation is updated to match the actual return values, resolving a type mismatch error. It also shows how Luau can infer local variable types. ```luau --!strict function ispositive(x : number) : string if x > 0 then return "yes" else return "no" end end local result : string result = ispositive(1) ``` -------------------------------- ### Luau Type Mismatch Error Example Source: https://luau.org/getting-started Demonstrates a type mismatch error in Luau when a function's return type annotation does not match its actual return value. This highlights the importance of consistent type annotations. ```luau --!strict function ispositive(x : number) : boolean if x > 0 then return "yes" else return "no" end end local result : boolean result = ispositive(1) ``` -------------------------------- ### Luau Type Checking with Constraint Resolver Examples Source: https://luau.org/news/2021-06-30-luau-recap-june-2021 Demonstrates the Luau type checker's new constraint resolver capabilities for handling conditional expressions and type guards, including 'IsA' checks and type comparisons. ```luau function say_hello(name: string?) -- extra parentheses were enough to trip the old typechecker if (name) then print("Hello " .. name .. "!") else print("Hello mysterious stranger!") end end ``` ```luau function say_hello(name: string?, surname: string?) -- but now we handle that and more complex expressions as well if not (name and surname) then print("Hello mysterious stranger!") else print("Hello " .. name .. " " .. surname .. "!") end end ``` -------------------------------- ### Luau Table Literals: Unsealed Tables Example Source: https://luau.org/news/2022-07-07-luau-recap-june-2022 Shows how Luau now treats all table literals created with `{}` as unsealed within their scope. This allows properties to be added to tables created via literals or returned from functions, unlike previously where only empty table literals were unsealed. ```Luau local T = {} T.x = 5 -- OK local V = {x=5} V.y = 2 -- previously disallowed. Now OK. function mkTable() return {x = 5} end local U = mkTable() U.y = 2 -- Still disallowed: U is sealed ``` -------------------------------- ### Luau: Optimizing closure performance with local variables Source: https://luau.org/news/2020-02-25-luau-recap-february-2020 Shows an example of capturing local variables in Luau closures. Optimizations have made this process significantly faster and more memory-efficient, with closure creation potentially up to 2x faster and Roact benchmarks improving by 10%. ```luau local function createClosure(value) local capturedValue = value return function() print(capturedValue) end end local closure = createClosure("Hello") closure() ``` -------------------------------- ### Interact with the Operating System using Luau's os Library Source: https://luau.org/library The os library in Luau provides functionalities for interacting with the operating system, primarily focusing on time and date operations. Functions like `clock`, `date`, `difftime`, and `time` allow developers to get high-precision timestamps, format dates and times according to specified patterns, calculate time differences, and convert between date tables and Unix timestamps. ```Luau function os.clock(): number function os.date(s: string?, t: number?): table | string function os.difftime(a: number, b: number): number function os.time(t: table?): number ``` -------------------------------- ### Luau Width Subtyping for Table Interfaces Source: https://luau.org/news/2022-03-31-luau-recap-march-2022 Shows an example of width subtyping in Luau, where a more concrete table type with extra properties can be assigned to a variable expecting a less specific interface type. This allows modules to export functions using a public interface while internally using a richer concrete type. ```luau type Interface = { name: string, } type Concrete = { name: string, id: number, } local x: Concrete = { name = "foo", id = 123, } local function get(): Interface return x end ``` -------------------------------- ### Luau Function: find_first_if Example Source: https://luau.org/news/2022-07-07-luau-recap-june-2022 Demonstrates a Luau function `find_first_if` that iterates through a vector to find the index of the first element satisfying a given predicate function. It highlights a common Luau type inference issue related to multiple return types (number and nil) and how lower bounds calculation addresses this. ```Luau function find_first_if(vec, f) for i, e in ipairs(vec) do if f(e) then return i end end return nil end ``` -------------------------------- ### Luau Type Inference Fix for Function Calls Source: https://luau.org/news/2022-08-29-luau-recap-august-2022 Illustrates a bug fix in Luau's type system where widening was too aggressive with function calls returning singleton types. This example shows how the corrected type inference now properly handles assignments from such functions. ```luau function f(): "abc" | "def" return if math.random() > 0.5 then "abc" else "def" end -- previously reported that 'string' could not be converted into '"abc" | "def"' local x: "abc" | "def" = f() ``` -------------------------------- ### Calling Luau Generic Functions Source: https://luau.org/types/generics Illustrates how to call generic functions in Luau, where the type arguments are inferred by the type inference engine. Examples show calling the `reverse` function with arrays of numbers and strings, with Luau correctly inferring the generic type `T` for each call. ```luau local reverse = require("./reverse") local x: {number} = reverse({1, 2, 3}) local y: {string} = reverse({"a", "b", "c"}) ``` -------------------------------- ### Declare Singleton String and Boolean Types in Luau Source: https://luau.org/types/basic-types Demonstrates the use of singleton types in Luau, which represent a single specific value at runtime. Examples show declaring variables with singleton types like `"Foo"` and `true`, and how type compatibility works (e.g., a variable typed as `"Foo"` can be assigned to a `string` type, but not vice-versa). ```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 ``` -------------------------------- ### Implement Generic Functions in Luau Source: https://luau.org/news/2021-09-30-luau-recap-september-2021 This code demonstrates the implementation of generic functions in Luau, allowing for type parameters in function declarations and types. It showcases how to define functions that can operate on different types, enhancing code reusability and type safety. The examples include defining a `swap` function and a `mkPoint` function that returns a generic function. ```Luau type Point = { x: X, y: Y } function swap(p) return { x = p.y, y = p.x } end local p : Point = swap({ x = "hi", y = 37 }) local q : Point = swap({ x = "hi", y = true }) ``` ```Luau type Point = { x: X, y: Y } function swap(p : Point): Point return { x = p.y, y = p.x } end ``` ```Luau type Point = { x: X, y: Y } type Swapper = { swap : (Point) -> Point } ``` ```Luau function mkPoint(x) return function(y) return { x = x, y = y } end end ``` ```Luau type Point = { x: X, y: Y } function mkPoint(x : X) : (Y) -> Point return function(y : Y) : Point return { x = x, y = y } end end ``` -------------------------------- ### Create and Run a Basic Luau Script Source: https://luau.org/getting-started Demonstrates creating a simple Luau script with functions and printing output. This script can be run using the `luau` command-line tool. ```luau 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)) ``` -------------------------------- ### Get Byte Codes (Luau) Source: https://luau.org/library Retrieves the numeric byte codes for characters within a specified range of a string. Supports default start and end indices. ```Luau function string.byte(s: string, f: number?, t: number?): ...number ``` ``` -------------------------------- ### Get Buffer Size in Luau Source: https://luau.org/library Returns the total size of the buffer in bytes. ```Luau function buffer.len(b: buffer): number ``` -------------------------------- ### Table Creation and Finding Source: https://luau.org/library Functions for creating tables with preallocated space and finding elements within a table. ```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 `function` ### Parameters - **n** (number) - The number of elements to preallocate space for. - **v** (any, optional) - The initial value for the elements. ### Returns - **table** - A new table with preallocated space. ``` ```APIDOC ## table.find ### Description Find the first element in the table that is equal to `v` and returns its index; the traversal stops at the first `nil`. If the element is not found, `nil` is returned instead. The traversal starts at index `init` if specified, otherwise 1. ### Method `function` ### Parameters - **t** (table) - The table to search within. - **v** (any) - The value to search for. - **init** (number, optional) - The starting index for the search. Defaults to 1. ### Returns - **number?** - The index of the first occurrence of `v`, or nil if not found. ``` -------------------------------- ### Create Table with Preallocated Space (Luau) Source: https://luau.org/library Creates a new table with a specified number of elements, optionally initializing them with a given value. Preallocating space can improve performance for subsequent insertions into the array portion of the table. ```Luau function table.create(n: number, v: V?): {V} ``` -------------------------------- ### Get String Length (Luau) Source: https://luau.org/library Returns the number of bytes in a string. This is equivalent to the length operator (`#s`). ```Luau function string.len(s: string): number ``` ``` -------------------------------- ### String Packing and Unpacking Source: https://luau.org/library Functions for packing data into strings according to a format, calculating packed string size, and unpacking data from strings. ```APIDOC ## string.pack ### Description Encodes all input parameters according to the packing format and returns the resulting string. Luau uses fixed sizes for platform-dependent types. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **f** (string) - Required - The pack format string. - **args** (...any) - Required - The values to pack. ### Request Example ``` string.pack(">i4", 10, 20) ``` ### Response #### Success Response (200) - **packed_string** (string) - The resulting packed string. #### Response Example ``` "\x0a\x00\x00\x00\x14\x00\x00\x00" ``` ## string.packsize ### Description Returns the size of the resulting packed representation. The pack format can’t use variable-length format specifiers. Luau uses fixed sizes for platform-dependent types. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **f** (string) - Required - The pack format string. ### Request Example ``` string.packsize(">i4") ``` ### Response #### Success Response (200) - **size** (number) - The size of the packed string in bytes. #### Response Example ``` 8 ``` ## string.unpack ### Description Decodes the input string according to the packing format and returns all resulting values. Luau uses fixed sizes for platform-dependent types. ### Method N/A (Built-in function) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body - **f** (string) - Required - The pack format string. - **s** (string) - Required - The string to unpack. ### Request Example ``` string.unpack(">i4", "\x0a\x00\x00\x00\x14\x00\x00\x00") ``` ### Response #### Success Response (200) - **values** (...any) - The unpacked values. #### Response Example ``` 10, 20 ``` ``` -------------------------------- ### Table Length and Max Key Source: https://luau.org/library Functions to get the length and maximum numeric key of a table. ```APIDOC ## table.getn (Deprecated) ### Description Returns the length of table `t`. This function has been deprecated and is not recommended for use in new code; use `#t` instead. ### Method `function` ### Parameters - **t** (table) - The table to get the length of. ### Returns - **number** - The length of the table. ``` ```APIDOC ## table.maxn ### Description Returns the maximum numeric key of table `t`, or zero if the table doesn’t have numeric keys. ### Method `function` ### Parameters - **t** (table) - The table to find the maximum key of. ### Returns - **number** - The maximum numeric key, or 0 if none exists. ``` -------------------------------- ### Convert String to Buffer in Luau Source: https://luau.org/library Initializes a buffer with the content of a given string. The buffer's size will be equal to the length of the input string. ```Luau function buffer.fromstring(str: string): buffer ``` -------------------------------- ### Get Table Length (Luau) Source: https://luau.org/library Returns the length of a table. This function is deprecated; use the '#' operator instead. ```Luau function table.getn(t: {V}): number ``` -------------------------------- ### Pack Arguments into Table (Luau) Source: https://luau.org/library Collects all provided arguments into a table. The table will contain the arguments as array elements and an additional field 'n' indicating the number of arguments. This is useful for handling variable numbers of arguments. ```Luau function table.pack(args: ...V): { [number]: V, n: number } ``` -------------------------------- ### Structural Typing Example in Luau Source: https://luau.org/typecheck Luau employs a structural type system, comparing the 'shape' of tables to determine similarity. This example demonstrates how tables A and B are defined and compared. Type A allows an optional 'z' property, while Type B requires it. Assigning B to A is valid, but assigning A to B is not due to the missing 'z' in a2. ```luau 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 ``` -------------------------------- ### Get Metatable - Luau Source: https://luau.org/types-library Retrieves the metatable associated with a class. If no metatable is defined for the class, this function returns nil. ```luau classtype:metatable(): type? ``` -------------------------------- ### Create String from Byte Codes (Luau) Source: https://luau.org/library Constructs a string from a sequence of integer byte codes. Each input number must be within the range [0..255]. ```Luau function string.char(args: ...number): string ``` ``` -------------------------------- ### Extract Substring (Luau) Source: https://luau.org/library Returns a portion of the string specified by a starting and ending byte index. The end index defaults to the string's length. ```Luau function string.sub(s: string, f: number, t: number?): string ``` ``` -------------------------------- ### Enabling Native Codegen Preview in Luau Source: https://luau.org/news/2023-11-01-luau-recap-october-2023 Instructions on how to enable the native code generation preview in Luau. This involves passing the `--codegen` flag for open-source releases or using the `--!native` comment for manual annotation in Roblox Studio. ```shell -- To enable for open-source releases: luau --codegen ``` ```luau -- To enable for specific scripts in Roblox Studio: --!native ``` -------------------------------- ### Get Class Properties - Luau Source: https://luau.org/types-library Retrieves the properties of a class, including their read and write types. This function is essential for introspection of class structures. ```luau classtype:properties(): { [type]: { read: type?, write: type? } } ``` -------------------------------- ### Optimized String Method Calls in Luau Source: https://luau.org/news/2020-10-30-luau-recap-october-2020 Method calls on strings using the colon syntax (`:`) in Luau are now approximately 10% faster. While fully-qualified calls to the `string` library (e.g., `string.foo(str)`) are still recommended for clarity and potentially better optimization, this improvement offers a performance boost for common string manipulations. ```luau local str = "hello" local upperStr = str:upper() -- Now ~10% faster -- Recommended alternative for clarity and potential optimization: -- local upperStr = string.upper(str) ``` -------------------------------- ### Luau Improved Error Messages Source: https://luau.org/news/2019-11-11-luau-recap-november-2019 Examples of enhanced runtime and parse error messages in Luau, providing more specific details about the cause of the error. ```lua -- Runtime Error Example: -- attempt to index foo with 'Health' (was: attempt to index a nil value) -- attempt to perform arithmetic (add) on table and number -- Parse Error Example: -- Expected '(' when parsing function, got 'local' (was: syntax error near 'functionName') ``` -------------------------------- ### Luau Default Type Alias Parameters Source: https://luau.org/news/2022-02-28-luau-recap-february-2022 Demonstrates how to define type aliases in Luau with default type parameters, allowing for optional type arguments during instantiation. This improves flexibility when defining generic types. ```luau --!strict type FieldResolver = (T, Data) -> number local a: FieldResolver = ... local b: FieldResolver = ... ``` ```luau --!strict type EqComp = (l: T, r: U) -> boolean local a: EqComp = ... -- (l: number, r: number) -> boolean local b: EqComp = ... -- (l: number, r: string) -> boolean ``` ```luau --!strict type Process = (T) -> U... local a: Process = ... -- (number) -> ...string local b: Process = ... -- (number) -> (boolean, string) ``` ```luau --!strict type All = (T) -> U local a: All -- ok local b: All<> -- ok as well ``` -------------------------------- ### Luau Signature Help for FindFirstChild Source: https://luau.org/news/2023-11-01-luau-recap-october-2023 Illustrates a fix in Luau's signature help for the `FindFirstChild` method. Previously, it incorrectly suggested a `self` argument; now, it correctly displays the signature `FindFirstChild(name: string, recursive: boolean?): Instance`. ```luau game:FindFirstChild( ``` -------------------------------- ### Luau bit32 Count Leading Zeros Source: https://luau.org/library Counts the number of consecutive zero bits starting from the most significant bit of the 32-bit representation of `n`. Returns 32 if `n` is zero. ```Luau function bit32.countlz(n: number): number ``` -------------------------------- ### Match Pattern in String (Luau) Source: https://luau.org/library Attempts to find a pattern within a string, starting from an optional position. Returns pattern captures or the entire match if found, otherwise nil. ```Luau function string.match(s: string, p: string, init: number?): ...string? ``` ``` -------------------------------- ### Luau Subtyping with String and Table Types Source: https://luau.org/news/2022-08-29-luau-recap-august-2022 Demonstrates how Luau now correctly type-checks calls to functions expecting a table with a specific shape, even when a `string` is passed, provided the string has a compatible method (like `lower`). ```luau function my_cool_lower(t) return t:lower() end local s: string = my_cool_lower("HI") ``` -------------------------------- ### Split Number into Integer and Fractional Parts (Luau) Source: https://luau.org/library Separates a number into its integer and fractional components, preserving the sign of the original number. For example, math.modf(-1.5) returns -1 and -0.5. ```Luau function math.modf(n: number): (number, number) ``` -------------------------------- ### Implement __len Metamethod for Tables in Luau Source: https://luau.org/news/2022-08-29-luau-recap-august-2022 Demonstrates how to implement the `__len` metamethod for custom table-like structures in Luau. This allows tables to respect the `#` operator for length calculation. The `rawlen` function is also shown, which returns 0 for metatable-aware tables. ```luau 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 ``` -------------------------------- ### Array-like Table Indexers in Luau Source: https://luau.org/types/tables Demonstrates the use of table indexers, specifically for array-like tables where keys are numbers. It shows the concise `{T}` syntax for homogeneous arrays and the more explicit `{[number]: T}` syntax for tables with indexers and other fields. ```luau local t = {"Hello", "world!"} -- {[number]: string} print(table.concat(t, ", ")) ``` ```luau local t: { [number]: string, n: number } = { [1] = "Hello", [2] = "world!", n = 2 } ``` -------------------------------- ### Luau bit32 Count Trailing Zeros Source: https://luau.org/library Counts the number of consecutive zero bits starting from the least significant bit of the 32-bit representation of `n`. Returns 32 if `n` is zero. ```Luau function bit32.countrz(n: number): number ``` -------------------------------- ### Luau select function Source: https://luau.org/library The `select` function handles function arguments. When called with '#', it returns the count of arguments. Otherwise, it returns a subset of arguments starting from a specified index, which can be positive or negative. ```Luau function select(i: string, args: ...T): number function select(i: number, args: ...T): ...T ``` -------------------------------- ### Table Cloning Source: https://luau.org/library Creates a shallow copy of a table. ```APIDOC ## table.clone ### Description Creates a shallow copy of a table. ### Method `function` ### Parameters - **t** (table) - The table to clone. ### Returns - **table** - A new table that is a shallow copy of the input table. ``` -------------------------------- ### Get Maximum Numeric Key (Luau) Source: https://luau.org/library Returns the maximum numeric key present in a table. If the table has no numeric keys, it returns zero. This function is useful for understanding the numeric indexing of a table. ```Luau function table.maxn(t: {V}): number ``` -------------------------------- ### Luau String Interpolation with table.concat Source: https://luau.org/news/2023-02-02-luau-string-interpolation Demonstrates basic string interpolation in Luau using the `{}` syntax to embed the result of `table.concat`. This provides a cleaner way to format strings compared to `string.format`. ```luau local combos = {2, 7, 1, 8, 5} print(`The lock combination is {table.concat(combos)}. Again, {table.concat(combos, ", ")}.`) ``` -------------------------------- ### Get Indexer Read Result Type - Luau Source: https://luau.org/types-library Returns the type of the result when reading from the class via indexing. Returns nil if indexing is not supported or configured. ```luau classtype:readindexer(): { index: type, result: type }? ``` -------------------------------- ### Vector Creation Source: https://luau.org/library Functions to create new vector instances with specified component values. ```APIDOC ## Vector Creation ### Description Creates a new vector with the given component values. ### Method `vector.create(x: number, y: number, z: number): vector` `vector.create(x: number, y: number, z: number, w: number): vector` ### Parameters - `x` (number) - The value for the x-component. - `y` (number) - The value for the y-component. - `z` (number) - The value for the z-component. - `w` (number, optional) - The value for the w-component. Defaults to 0.0 in 4-wide mode if omitted. ``` -------------------------------- ### Set and Get Table Metatable in Luau Source: https://luau.org/types-library Functions to set and retrieve the metatable associated with a Luau table type. This is crucial for defining table behavior and inheritance. ```Luau tabletype:setmetatable(arg: type) tabletype:metatable(): type? ``` -------------------------------- ### Luau bit32 Extract Bits Source: https://luau.org/library Extracts a specified number of bits (`w`) from a number (`n`) starting at a given position (`f`). `w` defaults to 1. Errors if the bit range is invalid. ```Luau function bit32.extract(n: number, f: number, w: number?): number ``` -------------------------------- ### Add Type Annotations to Luau Functions Source: https://luau.org/getting-started Illustrates adding explicit type annotations to function arguments and return types in Luau. This enhances type safety and helps catch errors during static analysis. ```luau --!strict function ispositive(x : number) : boolean return x > 0 end local result : boolean result = ispositive(1) ``` -------------------------------- ### Get Indexer Information - Luau Source: https://luau.org/types-library Returns the indexer configuration for a class, including the index type and the types for read and write results. Returns nil if no indexer is defined. ```luau classtype:indexer(): { index: type, readresult: type, writeresult: type }? ``` -------------------------------- ### Get Parent Read Type - Luau Source: https://luau.org/types-library Returns the type for reading from the parent class. If the parent class does not exist, it returns nil. Useful for understanding inheritance chains. ```luau classtype:readparent(): type? ``` -------------------------------- ### Clone Table (Luau) Source: https://luau.org/library Creates a shallow copy of a given table. This means that the new table will contain copies of the references to the original table's elements, not deep copies of the elements themselves. ```Luau function table.clone(t: table): table ``` -------------------------------- ### Find Pattern in String (Luau) Source: https://luau.org/library Searches for a pattern within a string, optionally starting from a specific position and using plain string comparison. Returns match position, length, and captures, or nil if not found. ```Luau function string.find(s: string, p: string, init: number?, plain: boolean?): (number?, number?, ...string) ``` ``` -------------------------------- ### Luau Linter Warning for `table.create` with Shared Elements Source: https://luau.org/news/2022-01-27-luau-recap-january-2022 Highlights a new static analysis warning in Luau for `table.create(N, {})`. This warning is issued because the empty table `{}` will be shared across all entries, potentially leading to unexpected behavior. ```luau table.create(N, {}) ``` -------------------------------- ### Concatenate Table Elements (Luau) Source: https://luau.org/library Concatenates all elements of a string table with a specified separator. It allows specifying a range of indices to include in the concatenation. Defaults to the entire table if start and end indices are omitted. ```Luau function table.concat(a: {string}, sep: string?, f: number?, t: number?): string ``` -------------------------------- ### Table Packing and Unpacking Source: https://luau.org/library Functions for packing multiple values into a table and unpacking values from a table. ```APIDOC ## table.pack ### Description Returns a table that consists of all input arguments as array elements, and `n` field that is set to the number of inputs. ### Method `function` ### Parameters - **args** (...any) - Variable number of arguments to pack into a table. ### Returns - **table** - A table containing the packed arguments with an additional `n` field indicating the number of arguments. ``` ```APIDOC ## table.unpack ### Description Returns all values of `a` with indices in `[f..t]` range. `f` defaults to 1 and `t` defaults to `#a`. Note that if you want to unpack varargs packed with `table.pack` you have to specify the index fields because `table.unpack` doesn’t automatically use the `n` field that `table.pack` creates. Example usage for packed varargs: `table.unpack(args, 1, args.n)` ### Method `function` ### Parameters - **a** (table) - The table to unpack values from. - **f** (number, optional) - The starting index for unpacking. Defaults to 1. - **t** (number, optional) - The ending index for unpacking. Defaults to `#a`. ### Returns - **...any** - The unpacked values from the table. ``` -------------------------------- ### Luau Type Annotations: Variables, Functions, and Expressions Source: https://luau.org/news/2020-01-16-luau-type-checking-beta Demonstrates various ways to apply type annotations in Luau. This includes annotating local variables, function parameters, function return types, and using the 'as' keyword for type assertion on expressions. ```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 Indexer Write Result Type - Luau Source: https://luau.org/types-library Returns the type expected for writing to the class via indexing. Returns nil if writing via indexing is not supported or configured. ```luau classtype:writeindexer(): { index: type, result: type }? ``` -------------------------------- ### Get Parent Write Type - Luau Source: https://luau.org/types-library Returns the type for writing to the parent class. If the parent class does not exist, it returns nil. This complements `readparent` for full parent interaction. ```luau classtype:writeparent(): type? ``` -------------------------------- ### tostring Source: https://luau.org/library Converts the input object to a string. If the object has a `__tostring` metamethod, it will be used for the conversion. ```APIDOC ## tostring ### Description Converts the input object to string and returns the result. If the object has a metatable with `__tostring` field, that method is called to perform the conversion. ### Method `tostring(obj: any): string` ``` -------------------------------- ### Shorthand Array-Like Table Type Syntax in Luau Source: https://luau.org/news/2020-10-30-luau-recap-october-2020 Introduces a concise syntax for declaring array-like table types in Luau. Previously, developers had to use a verbose `{ [number]: type }` or define a global `Array` type. This update allows for a simpler `{type}` notation, aligning with Lua table literal syntax and improving readability. This shorthand is for homogeneous array-like tables; mixed tables still require the longer syntax. ```luau local arr: {string} = {"hello", "world"} local mixedTable: { [number]: string, n: number } = {"hello", n = 1} ``` -------------------------------- ### Luau Type Inference Example Source: https://luau.org/news/2020-01-16-luau-type-checking-beta Demonstrates Luau's type inference capabilities. When type annotations are omitted, Luau attempts to deduce the types of variables and functions based on their usage. ```luau --!strict local Counter = {count=0} function Counter:incr() self.count = 1 return self.count end print(Counter:incr()) -- ok print(Counter.incr()) -- Error! print(Counter.amount) -- Error! ``` -------------------------------- ### Create a Buffer in Luau Source: https://luau.org/library Creates a new buffer of a specified size, with all bytes initialized to zero. The maximum size for a buffer is 1GB (1,073,741,824 bytes). ```Luau function buffer.create(size: number): buffer ``` -------------------------------- ### Copy Buffer Data in Luau Source: https://luau.org/library Copies a specified number of bytes from a source buffer, starting at a source offset, to a target buffer at a target offset. Optional source offset, count, and target offset parameters are available. ```Luau function buffer.copy(target: buffer, targetOffset: number, source: buffer, sourceOffset: number?, count: number?): () ``` -------------------------------- ### Luau 'never' Type Example Source: https://luau.org/types/basic-types Illustrates the 'never' type in Luau, representing the bottom type. This type is useful when type refinements logically prove that a value cannot exist, such as in conditions that are always false. ```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 ``` -------------------------------- ### Generalized Iteration for Tables in Luau Source: https://luau.org/news/2022-06-01-luau-recap-may-2022 Demonstrates the extended Lua syntax for iterating directly over tables in Luau, simplifying iteration compared to traditional iterator functions like `pairs` or `ipairs`. This feature can be customized for tables or userdata by implementing the `__iter` metamethod. ```luau for k, v in {1, 4, 9} do assert(k * k == v) end ``` -------------------------------- ### Optimize Vector3.new Constructor in Luau Source: https://luau.org/news/2021-09-30-luau-recap-september-2021 This section details the optimization of the Vector3.new constructor in Luau, resulting in a performance increase of approximately 2x. No specific code examples are provided as this is a core language improvement. -------------------------------- ### Luau: Parsing error for incomplete statements Source: https://luau.org/news/2020-02-25-luau-recap-february-2020 Example of an incomplete statement in Luau, such as just a variable name without an assignment or operation. Luau now produces a more easily understandable parsing error for such cases. ```luau local myVariable -- Missing assignment or usage here ```