Dataset Viewer
Auto-converted to Parquet Duplicate
source
stringlengths
17
66
seed
stringclasses
1 value
crawled_at
stringdate
2026-03-29 11:32:02
2026-03-29 11:32:29
content
stringlengths
180
35.6k
tokens
int64
39
8.41k
content_hash
stringlengths
64
64
https://luau.org/
https://luau.org/
2026-03-29T11:32:02.962600+00:00
# Luau ![Hina, a Hawaiian monk seal and the official mascot of the Luau language](/_astro/mascot.iwZjauS8_1jdjiU.webp) # Luau Luau (lowercase *u*, /ˈlu.aʊ/) is a small, fast, and embeddable programming language based on Lua with a gradual type system. [Get Started](/getting-started/) [News](/news/) [Try Luau online](https://play.luau.org) # Try Luau! # Why Luau? Performance Luau is a high-performance managed language with a fast bytecode compiler and interpreter, and an optimized, incremental garbage collector. Its optional JIT compiler runs on x64 and arm64, and supports plugins that extend native code generation to any embedder-defined types. Safety Luau has a state-of-the-art gradual type system with features like [type refinements](./types/type-refinements) and [type functions](./types/type-functions). This system is powered by an ambitious and powerful type inference engine that aims to both rule out program errors, *and* provide autocomplete with minimal annotations. Accessibility Luau is designed to be easy-to-learn, and easy-to-use over time. The syntax of the language is small and easy to pick up, and the semantics of the language should be broadly unsurprising to most programmers, with recursive functions, conventional loops and branching, and so forth. Delightfulness Luau aims to be pleasant and productive to use, and to make programming as fun as it can be! Besides the language itself, we’re building a full suite of developer tools: package management, linting, code transformation, documentation generation, and servers for editing and debugging code. Embeddability Luau, like Lua before it, is designed with embedding in mind. The language features an extended version of Lua’s C API with better support for coroutines and yielding, code coverage, and more performant, tagged userdata. We’ve also carefully sandboxed Luau, limiting the exposed API surface by default and enabling embedders to safely support executing untrusted code from their users. Compatibility Whenever possible, Luau aims to be backwards-compatible with Lua 5.1 and at the same time to incorporate features from later revisions of Lua. However, Luau is not a full superset of later versions of Lua - we do not always agree with Lua design decisions, and have different use cases and constraints. All post-5.1 Lua features, along with their support status in Luau, [are documented here](compatibility).
539
22c2a99984fc77c6ae015fc7e14d9f90a976f16e1080716ebe98ee2b1058b0e1
https://luau.org/getting-started
https://luau.org/
2026-03-29T11:32:03.757058+00:00
# An introduction to Luau Luau is a fast, small, safe, gradually typed embeddable scripting language derived from Lua 5.1. Luau ships as a command line tool for running, analyzing, and linting your Luau scripts, and is also integrated with Roblox Studio. Roblox developers should also visit our [Creator Docs Luau Section](https://create.roblox.com/docs/luau). To get started with Luau, you can use the `luau` command line binary to run your code and `luau-analyze` to run static analysis (including type checking and linting). You can download these from [a recent release](https://github.com/luau-lang/luau/releases). ## Creating a script To create your own testing script, create a new file with `.luau` as the extension: You can now run the file using `luau test.luau` and analyze it using `luau-analyze test.luau`. Note that there are no warnings about calling `ispositive()` with a string, or calling `isfoo()` with a number. This is because Luau’s type checking uses non-strict mode by default, which only reports errors if it’s certain a program will error at runtime. ## Type checking Now modify the script to include `--!strict` at the top: We just mentioned `nonstrict` mode, where we only report errors if we can prove that a program will error at runtime. We also have `strict` mode, which will report errors if a program might error at runtime. In this case, Luau will use the `return x > 0` statement to infer that `ispositive()` is a function taking a number and returning a boolean. Note that in this case, we were able to determine the type of `ispositive` without the presence of any explicit type annotations. Based on Luau’s type inference, the analysis tool will now flag the incorrect call to `ispositive()`: ## Annotations You can add annotations to locals, arguments, and function return types. Among other things, annotations can help enforce that you don’t accidentally do something silly. Here’s how we would add annotations to `ispositive()`: Now we’ve explicitly told Luau that `ispositive()` accepts a number and returns a boolean. This wasn’t strictly (pun intended) necessary in this case, because Luau’s inference was able to deduce this already. But even in this case, there are advantages to explicit annotations. Imagine that later we decide to change `ispositive()` to return a string value: Oops — we’re returning string values, but we forgot to update the function return type. Since we’ve told Luau that `ispositive()` returns a boolean (and that’s how we’re using it), the call site isn’t flagged as an error. But because the annotation doesn’t match our code, we get a warning in the function body itself: The fix is simple; just change the annotation to declare the return type as a string: Well, almost - since we declared `result` as a boolean, the call site is now flagged: If we update the type of the local variable, everything is good. Note that we could also just let Luau infer the type of `result` by changing it to the single line version `local result = ispositive(1)`. ## Conclusions This has been a brief tour of the basic functionality of Luau, but there’s lots more to explore. If you’re interested in reading more, check out our main reference pages for [syntax](/syntax) and [typechecking](/types).
748
8e76ae8c1e986cb9193c0142f1db9cfbe580969db5cdd1995992db4d022f403e
https://luau.org/types/type-functions
https://luau.org/
2026-03-29T11:32:03.838279+00:00
# Type Functions Type functions are functions that run during analysis time and operate on types, instead of runtime values. They can use the [types](../../types-library) library to transform existing types or create new ones. Here’s a simplified implementation of the builtin type function `keyof`. It takes a table type and returns its property names as a [union](../unions-and-intersections#union-types) of [singletons](../basic-types#singleton-types-aka-literal-types). ### Type function environment In addition to the [types](../../types-library) library, type functions have access to: - `assert`, `error`, `print` - `next`, `ipairs`, `pairs` - `select`, `unpack` - `getmetatable`, `setmetatable` - `rawget`, `rawset`, `rawlen`, `raweq` - `tonumber`, `tostring` - `type`, `typeof` - `math` library - `table` library - `string` library - `bit32` library - `utf8` library - `buffer` library
231
fad496a7470485d7fad08ad65120a221484d593280ed3b47873969524992dfc1
https://luau.org/types/type-refinements
https://luau.org/
2026-03-29T11:32:03.848275+00:00
# Type Refinements When we check the type of any lvalue (a global, a local, or a property), what we’re doing is we’re refining the type, hence “type refinement.” The support for this is arbitrarily complex, so go at it! Here are all the ways you can refine: 1. Truthy test: `if x then` will refine `x` to be truthy. 2. Type guards: `if type(x) == "number" then` will refine `x` to be `number`. 3. Equality: `if x == "hello" then` will refine `x` to be a singleton type `"hello"`. And they can be composed with many of `and`/`or`/`not`. `not`, just like `~=`, will flip the resulting refinements, that is `not x` will refine `x` to be falsy. The `assert(..)` function may also be used to refine types instead of `if/then`. Using truthy test: Using `type` test: Using equality test: And as said earlier, we can compose as many of `and`/`or`/`not` as we wish with these refinements: `assert` can also be used to refine in all the same ways:
268
830f33274547e72242a858fb87b7d5ec1e2faad2d82afe2a245819fa90f7a82a
https://luau.org/news
https://luau.org/
2026-03-29T11:32:03.905831+00:00
# News The latest news from the Luau team! Stay up to date with new features, performance improvements, and language updates. [Luau Recap for 2025: Runtime Posted December 19, 2025](/news/2025-12-19-luau-recap-runtime-2025)[Recap: July 2024 Posted July 23, 2024](/news/2024-07-23-luau-recap-july-2024)[Recap: October 2023 Posted November 1, 2023](/news/2023-11-01-luau-recap-october-2023)[Recap: July 2023 Posted July 28, 2023](/news/2023-07-28-luau-recap-july-2023)[Recap: March 2023 Posted March 31, 2023](/news/2023-03-31-luau-recap-march-2023)[String Interpolation Posted February 2, 2023](/news/2023-02-02-luau-string-interpolation)[Recap: November 2022 Posted November 30, 2022](/news/2022-11-30-luau-recap-november-2022)[Luau origins and evolution Posted November 4, 2022](/news/2022-11-04-luau-origins-and-evolution)[Recap: September & October 2022 Posted November 1, 2022](/news/2022-11-01-luau-recap-september-october-2022)[Semantic Subtyping in Luau Posted October 31, 2022](/news/2022-10-31-luau-semantic-subtyping)[Recap: July & August 2022 Posted August 29, 2022](/news/2022-08-29-luau-recap-august-2022)[Recap: June 2022 Posted July 7, 2022](/news/2022-07-07-luau-recap-june-2022)[Recap: May 2022 Posted June 1, 2022](/news/2022-06-01-luau-recap-may-2022)[Recap: April 2022 Posted May 2, 2022](/news/2022-05-02-luau-recap-april-2022)[Recap: March 2022 Posted March 31, 2022](/news/2022-03-31-luau-recap-march-2022)[Recap: February 2022 Posted February 28, 2022](/news/2022-02-28-luau-recap-february-2022)[Recap: January 2022 Posted January 27, 2022](/news/2022-01-27-luau-recap-january-2022)[Recap: November 2021 Posted November 29, 2021](/news/2021-11-29-luau-recap-november-2021)[Luau Goes Open-Source Posted November 3, 2021](/news/2021-11-03-luau-goes-open-source)[Recap: October 2021 Posted October 31, 2021](/news/2021-10-31-luau-recap-october-2021)[Recap: September 2021 Posted September 30, 2021](/news/2021-09-30-luau-recap-september-2021)[Recap: August 2021 Posted August 31, 2021](/news/2021-08-31-luau-recap-august-2021)[Recap: July 2021 Posted July 30, 2021](/news/2021-07-30-luau-recap-july-2021)[Recap: June 2021 Posted June 30, 2021](/news/2021-06-30-luau-recap-june-2021)[Recap: May 2021 Posted May 31, 2021](/news/2021-05-31-luau-recap-may-2021)[Recap: April 2021 Posted April 30, 2021](/news/2021-04-30-luau-recap-april-2021)[Recap: March 2021 Posted March 29, 2021](/news/2021-03-29-luau-recap-march-2021)[Recap: February 2021 Posted March 1, 2021](/news/2021-03-01-luau-recap-february-2021)[Luau Type Checking Release Posted November 19, 2020](/news/2020-11-19-luau-type-checking-release)[Recap: October 2020 Posted October 30, 2020](/news/2020-10-30-luau-recap-october-2020)[Recap: August 2020 Posted August 11, 2020](/news/2020-08-11-luau-recap-august-2020)[Recap: June 2020 Posted June 20, 2020](/news/2020-06-20-luau-recap-june-2020)[Recap: May 2020 Posted May 18, 2020](/news/2020-05-18-luau-recap-may-2020)[Recap: February 2020 Posted February 25, 2020](/news/2020-02-25-luau-recap-february-2020)[Luau Type Checking Beta Posted January 16, 2020](/news/2020-01-16-luau-type-checking-beta)[Recap: November 2019 Posted November 11, 2019](/news/2019-11-11-luau-recap-november-2019)
1,351
fecd0cc7be6a9072b53d2fcea199fb19c5ce0ef1b8ad4d27f8788205efe3629d
https://luau.org/compatibility
https://luau.org/
2026-03-29T11:32:05.765620+00:00
# Compatibility with Lua Luau is based on Lua 5.1, and as such incorporates all features of 5.1, except for ones that had to be taken out due to sandboxing limitations. Because of backwards compatibility constraints, we don’t remove features deprecated by later versions (e.g. we still support `getfenv`/`setfenv`). Later Lua versions introduce new features into the language and new libraries/functions. Our overall goal is to incorporate features from the later versions of Lua when it makes sense for us to do so - the motivations behind some newer features are unclear or don’t apply to the domain Luau is used in, and many features carry costs that don’t always make sense to pay. The rest of this document describes the status of all features of Lua 5.2 and beyond, with the following classification: - ✔️ - the feature is available in Luau - ❌ - the feature is not available in Luau because we don’t believe it makes sense to include it - 😞 - the feature is not available in Luau because of compatibility/sandboxing concerns - 🔜 - the feature is not available in Luau yet but we’d like to include it and are possibly working on it - 🤷‍♀️ - the feature is not available in Luau yet; we don’t have strong opinions on it so it might make it at some point Please note that all of these decisions are not final, they are just our current stance. In some cases evolution of our VM may make a feature that was previously impractical to support due to performance complications feasible. In some cases a feature that didn’t have a strong use case gains one, so we can implement it. ## Implementation limits Luau has certain limitations around the number of local variables, registers, upvalues, constants and instructions. These limits are often different from the limits imposed by various versions of Lua, and are documented here without promising that future versions will adhere to these. Note that writing code that is close to any of these limits is dangerous because this code may become invalid as our codegen evolves. - Local variables: 200 per function (same as all versions of Lua, this includes function arguments) - Upvalues: 200 per function (up from 60 in Lua 5.1) - Registers: 255 per function (same as all versions of Lua, this includes local variables and function arguments) - Constants: 2^23 per function (up from 2^18 in Lua 5.1) - Instructions: 2^23 per function (up from 2^17 in Lua 5.1, although in both cases the limit only applies to control flow) - Nested functions: 2^15 per function (down from 2^18 in Lua 5.1) - Stack depth: 20000 Lua calls per Lua thread, 200 C calls per C thread (e.g. `coroutine.resume`/`pcall` nesting is limited to 200) Note that Lua 5.3 has a larger upvalue limit (255) and a larger constant limit (2^26); existing Luau limits are likely sufficient for reasonable use cases. ## Lua 5.1 Since several features were removed from Lua 5.1 for sandboxing reasons, this table lists them for completeness. | feature | notes | | --- | --- | | `io`, `os`, `package` and `debug` library | note that some functions in `os`/`debug` are still present | | `loadfile`, `dofile` | removed for sandboxing, no direct file access | | `loadstring` bytecode and `string.dump` | exposing bytecode is dangerous for sandboxing reasons | | `newproxy` can only be called with nil or boolean | extra flexibility removed for sandboxing | Sandboxing challenges are [covered in the dedicated section](../sandbox). ## Lua 5.2 | feature | status | notes | | --- | --- | --- | | yieldable pcall/xpcall | ✔️ | | | yieldable xpcall error handler | ❌ | no strong use cases, VM complexity and performance implications | | yieldable metamethods | ❌ | significant performance implications | | ephemeron tables | ❌ | this complicates and slows down the garbage collector esp. for large weak tables | | emergency garbage collector | 🤷‍ | Luau runs in environments where handling memory exhaustion in emergency situations is not tenable | | goto statement | ❌ | this complicates the compiler, makes control flow unstructured and doesn’t address a significant need | | finalizers for tables | ❌ | no `__gc` support due to sandboxing and performance/complexity | | no more fenv for threads or functions | 😞 | we love this, but it breaks compatibility | | tables honor the `__len` metamethod | ✔️ | | | hex and `z` escapes in strings | ✔️ | | | support for hexadecimal floats | 🤷‍♀️ | no strong use cases | | order metamethods (`__lt`/`__le`) are called for unrelated metatables | ❌ | no strong use cases and more complicated semantics, compatibility and performance implications | | empty statement | 🤷‍♀️ | less useful in Lua than in JS/C#/C/C++ | | `break` statement may appear in the middle of a block | 🤷‍♀️ | we’d like to do it consistently for `break`/`return`/`continue` but there be dragons | | arguments for function called through `xpcall` | ✔️ | | | optional base in `math.log` | ✔️ | | | optional separator in `string.rep` | 🤷‍♀️ | no strong use cases | | new metamethods `__pairs` and `__ipairs` | ❌ | superseded by `__iter` | | frontier patterns | ✔️ | | | `%g` in patterns | ✔️ | | | `0` in patterns | ✔️ | | | `bit32` library | ✔️ | | | `string.gsub` is stricter about using `%` on special characters only | ✔️ | | | light C functions | 😞 | this changes semantics of fenv on C functions and has complex implications wrt runtime performance | | NaN keys are supported for tables with `__newindex` | ✔️ | | Two things that are important to call out here are various new metamethods for tables and yielding in metamethods. In both cases, there are performance implications to supporting this - our implementation is *very* highly tuned for performance, so any changes that affect the core fundamentals of how Lua works have a price. To support yielding in metamethods we’d need to make the core of the VM more involved, since almost every single “interesting” opcode would need to learn how to be resumable - which also complicates future JIT/AOT story. Metamethods in general are important for extensibility, but very challenging to deal with in implementation, so we err on the side of not supporting any new metamethods unless a strong need arises. For `__pairs`/`__ipairs`, we felt that extending library functions to enable custom containers wasn’t the right choice. Instead we revisited iteration design to allow for self-iterating objects via `__iter` metamethod, which results in a cleaner iteration design that also makes it easier to iterate over tables. As such, we have no plans to support `__pairs`/`__ipairs` as all use cases for it can now be solved by `__iter`. Ephemeron tables may be implemented at some point since they do have valid uses and they make weak tables semantically cleaner, however the cleanup mechanism for these is expensive and complicated, and as such this can only be considered after the pending GC rework is complete. ## Lua 5.3 | feature | status | notes | | --- | --- | --- | | `u` escapes in strings | ✔️ | | | integers (64-bit by default) | ❌ | backwards compatibility and performance implications | | bitwise operators | ❌ | `bit32` library covers this in absence of 64-bit integers | | basic utf-8 support | ✔️ | we include `utf8` library and other UTF8 features | | functions for packing and unpacking values (string.pack/unpack/packsize) | ✔️ | | | floor division | ✔️ | | | `ipairs` and the `table` library respect metamethods | ❌ | no strong use cases, performance implications | | new function `table.move` | ✔️ | | | `collectgarbage("count")` now returns only one result | ✔️ | | | `coroutine.isyieldable` | ✔️ | | | stricter error checking for `table.insert`/`table.remove` | 😞 | we love this, but it breaks compatibility | | `__eq` metamethod is called for unrelated metatables | ❌ | backwards compatibility and typechecking implications | It’s important to highlight integer support and bitwise operators. For Luau, it’s rare that a full 64-bit integer type is necessary - double-precision types support integers up to 2^53 (in Lua which is used in embedded space, integers may be more appealing in environments without a native 64-bit FPU). However, there’s a *lot* of value in having a single number type, both from performance perspective and for consistency. Notably, Lua doesn’t handle integer overflow properly, so using integers also carries compatibility implications. If integers are taken out of the equation, bitwise operators make less sense, as integers aren’t a first class feature; additionally, `bit32` library is more fully featured (includes commonly used operations such as rotates and arithmetic shift; bit extraction/replacement is also more readable). Adding operators along with metamethods for all of them increases complexity, which means this feature isn’t worth it on the balance. Common arguments for this include a more familiar syntax, which, while true, gets more nuanced as `^` isn’t available as a xor operator, and arithmetic right shift isn’t expressible without yet another operator, and performance, which in Luau is substantially better than in Lua because `bit32` library uses VM builtins instead of expensive function calls. ## Lua 5.4 | feature | status | notes | | --- | --- | --- | | new generational mode for garbage collection | 🤷‍♀️ | we’ve implemented other optimizations to garbage collection | | to-be-closed variables | ❌ | the syntax is inconsistent with how we’d like to do attributes long-term; no strong use cases in our domain | | const variables | ❌ | available through `const var = value` syntax | | new implementation for `math.random` | ✔️ | our RNG is based on PCG, unlike Lua 5.4 which uses Xoroshiro | | optional `init` argument to `string.gmatch` | 🤷‍♀️ | no strong use cases | | new functions `lua_resetthread` and `coroutine.close` | ✔️ | | | coercions string-to-number moved to the string library | 😞 | we love this, but it breaks compatibility | | new format `%p` in `string.format` | 🤷‍♀️ | no strong use cases | | `utf8` library accepts codepoints up to 2^31 | 🤷‍♀️ | no strong use cases | | The use of the `__lt` metamethod to emulate `__le` has been removed | ❌ | breaks compatibility and complicates comparison overloading story | | When finalizing objects, Lua will call `__gc` metamethods that are not functions | ❌ | no `__gc` support due to sandboxing and performance/complexity | | function `print` calls `__tostring` instead of `tostring` to format its arguments | ✔️ | | | decoding functions in the utf8 library do not accept surrogates | ✔️ | | Taking syntax aside (which doesn’t feel idiomatic or beautiful), `<close>` isn’t very useful in Luau - its dominant use case is for code that works with external resources like files or sockets, but we don’t provide such APIs - and has a very large complexity cost, evidences by a lot of bug fixes since the initial implementation in 5.4 work versions. `<const>` in Luau doesn’t matter for performance - our multi-pass compiler is already able to analyze the usage of the variable to know if it’s modified or not and extract all performance gains from it - so the only use here is for code readability, where the `<const>` syntax is… suboptimal. Const variables are available in Luau through a `const var = value` syntax, which is backwards compatible through a context-sensitive keyword (similar to `type`). ## Lua 5.5 | feature | status | notes | | --- | --- | --- | | declarations for global variables | ❌ | no strong use cases, mistakes are caught by typechecker | | named vararg tables | 🤷‍♀️ | | | for-loop variables are read only | ❌ | breaks compatibility | | floats are printed in decimal with enough digits to be read back correctly | ✔️ | | | `table.create(arraysize, recordsize)` | ❌ | breaks compatibility | | `utf8.offset` returns also final position of character | 🤷‍♀️ | | | external strings | ❌ | not compatible with internal object structure; | | new functions `luaL_openselectedlibs` and `luaL_makeseed` | 🤷‍♀️ | | ## Differences from Lua We have a few behavior deviations from Lua 5.x that come from either a different implementation, or our desire to clean up small inconsistencies in the language/libraries: - Tail calls are not supported to simplify implementation, make debugging/stack traces more predictable and allow deep validation of caller identity for security - Order of table assignment in table literals follows program order in mixed tables (Lua 5.x assigns array elements first in some cases) - Equality comparisons call `__eq` metamethod even when objects are rawequal (which matches other metamethods like `<=` and facilitates NaN checking) - `function()` expressions may reuse a previously created closure in certain scenarios (when all upvalues captured are the same) for efficiency, which changes object identity but doesn’t change call semantics — this is different from Lua 5.1 but similar to Lua 5.2/5.3 - `os.time` returns UTC timestamp when called with a table for consistency
3,109
2a3a92b775697730e74d3be24104ef78b9f7f398aa0a3c1f26924ba4430aca9b
https://luau.org/why
https://luau.org/
2026-03-29T11:32:05.773672+00:00
# Why Luau? Around 2006, [Roblox](https://www.roblox.com) started using Lua 5.1 as a scripting language for games. Over the years the runtime had to be tweaked to provide a safe, secure sandboxed environment; we gradually started accumulating small library changes and tweaks. Over the course of the last few years, instead of using Web-based stack for our player-facing application, Lua-based in-game UI and Qt-based editor UI, we’ve started consolidating a lot of the efforts and developing all of these using Roblox engine and Lua as a scripting language. Having grown a substantial internal codebase that needed to be correct and performant, and with the focus shifting a bit from novice game developers to professional studios building games on Roblox and our own teams of engineers building applications, there was a need to improve performance and quality of the code we were writing. Unlike mainline Lua, we also could not afford to do major breaking changes to the language (hence the 5.1 language baseline that remained unchanged for more than a decade). While faster implementations of Lua 5.1 like LuaJIT were available, they didn’t meet our needs in terms of portability, ease of change and they didn’t address the problem of developing robust code at scale. All of these motivated us to start reshaping Lua 5.1 that we started from into a new, derivative language that we call Luau. Our focus is on making the language more performant and feature-rich, and make it easier to write robust code through a combination of linting and type checking using a gradual type system. ## Complete rewrite? A very large part of Luau codebase is written from scratch. We needed a set of tools to be able to write language analysis tools; Lua has a parser that is integrated with the bytecode compiler, which makes it unsuitable for complex semantic analysis. For bytecode compilation, while a single pass compiler can deliver better compilation throughput and be simpler than a full frontend/backend, it significantly limits the optimizations that can be done at the bytecode level. Luau compiler and analysis tools are thus written from scratch, closely following the syntax and semantics of Lua. Our compiler is not single-pass, and instead relies on a set of analysis passes that run over the AST to produce efficient bytecode, followed by some post-process optimizations. As for the runtime, we had to rewrite the interpreter from scratch to get substantially faster performance; using a combination of techniques pioneered by LuaJIT and custom optimizations that are able to improve performance by taking control over the entire stack (language, compiler, interpreter, virtual machine), we’re able to get close to LuaJIT interpreter performance while using C as an implementation language. The garbage collector and the core libraries represent more of an incremental change, where we used Lua 5.1 as a baseline but we’re continuing to rewrite these as well with performance in mind. While Luau initially didn’t include a JIT/AOT, native code generation has since been implemented for x64/arm64 platform as an optional component.
622
bd9deccc783d8888a77bdc060f9e07284936c90d09b3f979ed450afeb4f69224
https://luau.org/performance
https://luau.org/
2026-03-29T11:32:05.836279+00:00
# How we make Luau fast One of main goals of Luau is to enable high performance code, with gameplay code being the main use case. This can be viewed as two separate goals: - Make idiomatic code that wasn’t tuned faster - Enable even higher performance through careful tuning Both of these goals are important - it’s insufficient to just focus on the highly tuned code, and all things being equal we prefer to raise all boats by implementing general optimizations. However, in some cases it’s important to be aware of optimizations that Luau does and doesn’t do. Worth noting is that Luau is focused on, first and foremost, stable high performance code in interpreted context. This is because JIT compilation is not available on many platforms Luau runs on, and AOT compilation would only work for code that Roblox ships (and even that does not always work). This is in stark contrast with LuaJIT that, while providing an excellent interpreter as well, focuses a lot of the attention on JIT (with many optimizations unavailable in the interpreter). Having said that, Luau has been updated to include an optional JIT component for x64 and arm64 platforms. This component can compile a selected set of functions, including limiting compilation to functions or modules marked explicitly by the user. While functions can be compiled at any time, automated JIT compilation decisions based on statistics/tracing are not performed. Luau JIT takes into account the type annotations present in the source code to specialize code paths and at this time, doesn’t include runtime analysis of the types/values flowing through the program. The rest of this document goes into some optimizations that Luau employs and how to best leverage them when writing code. The document is not complete - a lot of optimizations are transparent to the user and involve detailed low-level tuning of various parts that is not described here - and all of this is subject to change without notice, as it doesn’t affect the semantics of valid code. ## Fast bytecode interpreter Luau features a very highly tuned portable bytecode interpreter. It’s similar to Lua interpreter in that it’s written in C, but it’s highly tuned to yield efficient assembly when compiled with Clang and latest versions of MSVC. On some workloads it can match the performance of LuaJIT interpreter which is written in highly specialized assembly. We are continuing to tune the interpreter and the bytecode format over time; while extra performance can be extracted by rewriting the interpreter in assembly, we’re unlikely to ever do that as the extra gains at this point are marginal, and we gain a lot from C in terms of portability and being able to quickly implement new optimizations. Of course the interpreter isn’t typical C code - it uses many tricks to achieve extreme levels of performance and to coerce the compiler to produce efficient assembly. Due to a better bytecode design and more efficient dispatch loop it’s noticeably faster than Lua 5.x (including Lua 5.4 which made some of the changes similar to Luau, but doesn’t come close). The bytecode design was partially inspired by excellent LuaJIT interpreter. Most computationally intensive scripts only use the interpreter core loop and builtins, which on x64 compiles into ~16 KB, thus leaving half of the instruction cache for other infrequently called code. ## Optimizing compiler Unlike Lua and LuaJIT, Luau uses a multi-pass compiler with a frontend that parses source into an AST and a backend that generates bytecode from it. This carries a small penalty in terms of compilation time, but results in more flexible code and, crucially, makes it easier to optimize the generated bytecode. > Note: Compilation throughput isn’t the main focus in Luau, but our compiler is reasonably fast; with all currently implemented optimizations enabled, it compiles 950K lines of Luau code in 1 second on a single core of a desktop Ryzen 5900X CPU, producing bytecode and debug information. While bytecode optimizations are limited due to the flexibility of Luau code (e.g. `a * 1` may not be equivalent to `a` if `*` is overloaded through metatables), even in absence of type information Luau compiler can perform some optimizations such as “deep” constant folding across functions and local variables, perform upvalue optimizations for upvalues that aren’t mutated, do analysis of builtin function usage, optimize the instruction sequences for multiple variable assignments, and some peephole optimizations on the resulting bytecode. The compiler can also be instructed to use more aggressive optimizations by enabling optimization level 2 (`-O2` in CLI tools), some of which are documented further on this page. Most bytecode optimizations are performed on individual statements or functions, however the compiler also does a limited amount of interprocedural optimizations; notably, calls to local functions can be optimized with the knowledge of the argument count or number of return values involved. Interprocedural optimizations are limited to a single module due to the compilation model. Luau compiler is also able to use type information to do further optimizations. Because we control the entire stack (unlike e.g. TypeScript where the type information is discarded completely before reaching the VM), we have more flexibility there and can make some tradeoffs during codegen even if the type system isn’t completely sound. For example, it might be reasonable to assume that in presence of known types, we can infer absence of side effects for arithmetic operations and builtins - if the runtime types mismatch due to intentional violation of the type safety through global injection, the code will still be safely sandboxed. Type information is currently limited to small peephole optimizations, but it has a potential to unlock optimizations such as common subexpression elimination and allocation hoisting in the future, without having to rely on a JIT. These future optimizations opportunities are speculative pending further research. ## Epsilon-overhead debugger It’s important for Luau to have stable and predictable performance. Something that comes up in Lua-based environments often is the use of line hooks to implement debugging (both for breakpoints and for stepping). This is problematic because the support for hooks is typically not free in general, but importantly once the hook is enabled, calling the hook has a considerable overhead, and the hook itself may be very costly to evaluate since it will need to associate the script:line pair with the breakpoint information. Luau does not support hooks at all, and relies on first-class support for breakpoints (using bytecode patching) and single-stepping (using a custom interpreter loop) to implement debugging. As a result, the presence of breakpoints doesn’t slow the script execution down - the only noticeable discrepancy between running code under a debugger and without a debugger should be in cases where breakpoints are evaluated and skipped based on breakpoint conditions, or when stepping over long-running fragments of code. ## Inline caching for table and global access Table access for field lookup is optimized in Luau using a mechanism that blends inline caching (classically used in Java/JavaScript VMs) and HREFs (implemented in LuaJIT). Compiler can predict the hash slot used by field lookup, and the VM can correct this prediction dynamically. As a result, field access can be very fast in Luau, provided that: - The field name is known at compile time. To make sure this is the case, `table.field` notation is recommended, although the compiler will also optimize `table["field"]` when the expression is known to be a constant string. - The field access doesn’t use metatables. The fastest way to work with tables in Luau is to store fields directly inside the table, and store methods in the metatable (see below); access to “static” fields in classic OOP designs is best done through `Class.StaticField` instead of `object.StaticField`. - The object structure is usually uniform. While it’s possible to use the same function to access tables of different shape - e.g. `function getX(obj) return obj.x end` can be used on any table that has a field `"x"` - it’s best to not vary the keys used in the tables too much, as it defeats this optimization. The same optimization is applied to the custom globals declared in the script, although it’s best to avoid these altogether by using locals instead. Still, this means that the difference between `function` and `local function` is less pronounced in Luau. ## Importing global access chains While global access for library functions can be optimized in a similar way, this optimization breaks down when the global table is using sandboxing through metatables, and even when globals aren’t sandboxed, `math.max` still requires two table accesses. It’s always possible to “localize” the global accesses by using `local max = math.max`, but this is cumbersome - in practice it’s easy to forget to apply this optimization. To avoid relying on programmers remembering to do this, Luau implements a special optimization called “imports”, where most global chains such as `math.max` are resolved when the script is loaded instead of when the script is executed. This optimization relies on being able to predict the shape of the environment table for a given function; this is possible due to global sandboxing, however this optimization is invalid in some cases: - `loadstring` can load additional code that runs in context of the caller’s environment - `getfenv`/`setfenv` can directly modify the environment of any function The use of any of these functions performs a dynamic deoptimization, marking the affected environment as “impure”. The optimizations are only in effect on functions with “pure” environments - because of this, the use of `loadstring`/`getfenv`/`setfenv` is not recommended. Note that `getfenv` deoptimizes the environment even if it’s only used to read values from the environment. > Note: Luau still supports these functions as part of our backwards compatibility promise, although we’d love to switch to Lua 5.2’s `_ENV` as that mechanism is cleaner and doesn’t require costly dynamic deoptimization. ## Fast method calls Luau specializes method calls to improve their performance through a combination of compiler, VM and binding optimizations. Compiler emits a specialized instruction sequence when methods are called through `obj:Method` syntax (while this isn’t idiomatic anyway, you should avoid `obj.Method(obj)`). When the object in question is a Lua table, VM performs some voodoo magic based on inline caching to try to quickly discover the implementation of this method through the metatable. For this to be effective, it’s crucial that `__index` in a metatable points to a table directly. For performance reasons it’s strongly recommended to avoid `__index` functions as well as deep `__index` chains; an ideal object in Luau is a table with a metatable that points to itself through `__index`. When the object in question is a reflected userdata, a special mechanism called “namecall” is used to minimize the interop cost. In classical Lua binding model, `obj:Method` is called in two steps, retrieving the function object (`obj.Method`) and calling it; both steps are often implemented in C++, and the method retrieval needs to use a method object cache - all of this makes method calls slow. Luau can directly call the method by name using the “namecall” extension, and an optimized reflection layer can retrieve the correct method quickly through more voodoo magic based on string interning and custom Luau features that aren’t exposed through Luau scripts. As a result of both optimizations, common Lua tricks of caching the method in a local variable aren’t very productive in Luau and aren’t recommended either. ## Specialized builtin function calls Due to global sandboxing and the ability to dynamically deoptimize code running in impure environments, in pure environments we go beyond optimizing the interpreter and optimize many built-in functions through a “fastcall” mechanism. For this mechanism to work, function call must be “obvious” to the compiler - it needs to call a builtin function directly, e.g. `math.max(x, 1)`, although it also works if the function is “localized” (`local max = math.max`); this mechanism doesn’t work for indirect function calls unless they were inlined during compilation, and doesn’t work for method calls (so calling `string.byte` is more efficient than `s:byte`). The mechanism works by directly invoking a highly specialized and optimized implementation of a builtin function from the interpreter core loop without setting up a stack frame and omitting other work; additionally, some fastcall specializations are partial in that they don’t support all types of arguments, for example all `math` library builtins are only specialized for numeric arguments, so calling `math.abs` with a string argument will fall back to the slower implementation that will do string->number coercion. As a result, builtin calls are very fast in Luau - they are still slightly slower than core instructions such as arithmetic operations, but only slightly so. The set of fastcall builtins is slowly expanding over time and as of this writing contains `assert`, `type`, `typeof`, `rawget`/`rawset`/`rawequal`, `getmetatable`/`setmetatable`, `tonumber`/`tostring`, all functions from `math` (except `noise` and `random`/`randomseed`) and `bit32`, and some functions from `string` and `table` library. Some builtin functions have partial specializations that reduce the cost of the common case further. Notably: - `assert` is specialized for cases when the assertion return value is not used and the condition is truthy; this helps reduce the runtime cost of assertions to the extent possible - `bit32.extract` is optimized further when field and width selectors are constant - `select` is optimized when the second argument is `...`; in particular, `select(x, ...)` is O(1) when using the builtin dispatch mechanism even though it’s normally O(N) in variadic argument count. Some functions from `math` library like `math.floor` can additionally take advantage of advanced SIMD instruction sets like SSE4.1 when available. In addition to runtime optimizations for builtin calls, many builtin calls, as well as constants like `math.pi`/`math.huge`, can also be constant-folded by the bytecode compiler when using aggressive optimizations (level 2); this currently applies to most builtin calls with constant arguments and a single return value. For builtin calls that can not be constant folded, compiler assumes knowledge of argument/return count (level 2) to produce more efficient bytecode instructions. ## Optimized table iteration Luau implements a fully generic iteration protocol; however, for iteration through tables in addition to generalized iteration (`for .. in t`) it recognizes three common idioms (`for .. in ipairs(t)`, `for .. in pairs(t)` and `for .. in next, t`) and emits specialized bytecode that is carefully optimized using custom internal iterators. As a result, iteration through tables typically doesn’t result in function calls for every iteration; the performance of iteration using generalized iteration, `pairs` and `ipairs` is comparable, so generalized iteration (without the use of `pairs`/`ipairs`) is recommended unless the code needs to be compatible with vanilla Lua or the specific semantics of `ipairs` (which stops at the first `nil` element) is required. Additionally, using generalized iteration avoids calling `pairs` when the loop starts which can be noticeable when the table is very short. Iterating through array-like tables using `for i=1,#t` tends to be slightly slower because of extra cost incurred when reading elements from the table. ## Optimized table length Luau tables use a hybrid array/hash storage, like in Lua; in some sense “arrays” don’t truly exist and are an internal optimization, but some operations, notably `#t` and functions that depend on it, like `table.insert`, are defined by the Luau/Lua language to allow internal optimizations. Luau takes advantage of that fact. Unlike Lua, Luau guarantees that the element at index `#t` is stored in the array part of the table. This can accelerate various table operations that use indices limited by `#t`, and this makes `#t` worst-case complexity O(logN), unlike Lua where the worst case complexity is O(N). This also accelerates computation of this value for small tables like `{ [1] = 1 }` since we never need to look at the hash part. The “default” implementation of `#t` in both Lua and Luau is a binary search. Luau uses a special branch-free (depending on the compiler…) implementation of the binary search which results in 50+% faster computation of table length when it needs to be computed from scratch. Additionally, Luau can cache the length of the table and adjust it following operations like `table.insert`/`table.remove`; this means that in practice, `#t` is almost always a constant time operation. ## Creating and modifying tables Luau implements several optimizations for table creation. When creating object-like tables, it’s recommended to use table literals (`{ ... }`) and to specify all table fields in the literal in one go instead of assigning fields later; this triggers an optimization inspired by LuaJIT’s “table templates” and results in higher performance when creating objects. When creating array-like tables, if the maximum size of the table is known up front, it’s recommended to use `table.create` function which can create an empty table with preallocated storage, and optionally fill it with a given value. When the exact table shape isn’t known, Luau compiler can still predict the table capacity required in case the table is initialized with an empty literal (`{}`) and filled with fields subsequently. For example, the following code creates a correctly sized table implicitly: When appending elements to tables, it’s recommended to use `table.insert` (which is the fastest method to append an element to a table if the table size is not known). In cases when a table is filled sequentially, however, it can be more efficient to use a known index for insertion - together with preallocating tables using `table.create` this can result in much faster code, for example this is the fastest way to build a table of squares: ## Native vector math Luau uses tagged value storage - each value contains a type tag and the data that represents the value of a given type. Because of the need to store 64-bit double precision numbers *and* 64-bit pointers, we don’t use NaN tagging and have to pay the cost of 16 bytes per value. We take advantage of this to provide a native value type that can store a 32-bit floating point vector with 3 components. This type is fundamental to game computations and as such it’s important to optimize the storage and the operations with that type - our VM implements first class support for all math operations and component manipulation, which essentially means we have native 3-wide SIMD support. For code that uses many vector values this results in significantly smaller GC pressure and significantly faster execution, and gives programmers a mechanism to hand-vectorize numeric code if need be. ## Optimized upvalue storage Lua implements upvalues as garbage collected objects that can point directly at the thread’s stack or, when the value leaves the stack frame (and is “closed”), store the value inside the object. This representation is necessary when upvalues are mutated, but inefficient when they aren’t - and 90% or more of upvalues aren’t mutated in typical Lua code. Luau takes advantage of this by reworking upvalue storage to prioritize immutable upvalues - capturing upvalues that don’t change doesn’t require extra allocations or upvalue closing, resulting in faster closure allocation, faster execution, faster garbage collection and faster upvalue access due to better memory locality. Note that “immutable” in this case only refers to the variable itself - if the variable isn’t assigned to it can be captured by value, even if it’s a table that has its contents change. When upvalues are mutable, they do require an extra allocated object; we carefully optimize the memory consumption and access cost for mutable upvalues to reduce the associated overhead. ## Closure caching With optimized upvalue storage, creating new closures (function objects) is more efficient but still requires allocating a new object every time. This can be problematic for cases when functions are passed to algorithms like `table.sort` or functions like `pcall`, as it results in excessive allocation traffic which then leads to more work for garbage collector. To make closure creation cheaper, Luau compiler implements closure caching - when multiple executions of the same function expression are guaranteed to result in the function object that is semantically identical, the compiler may cache the closure and always return the same object. This changes the function identity which may affect code that uses function objects as table keys, but preserves the calling semantics - compiler will only do this if calling the original (cached) function behaves the same way as a newly created function would. The heuristics used for this optimization are subject to change; currently, the compiler will cache closures that have no upvalues, or all upvalues are immutable (see previous section) and are declared at the module scope, as the module scope is (almost always) evaluated only once. ## Fast memory allocator Similarly to LuaJIT, but unlike vanilla Lua, Luau implements a custom allocator that is highly specialized and tuned to the common allocation workloads we see. The allocator design is inspired by classic pool allocators as well as the excellent `mimalloc`, but through careful domain-specific tuning it beats all general purpose allocators we’ve tested, including `rpmalloc`, `mimalloc`, `jemalloc`, `ptmalloc` and `tcmalloc`. This doesn’t mean that memory allocation in Luau is free - it’s carefully optimized, but it still carries a cost, and a high rate of allocations requires more work from the garbage collector. The garbage collector is incremental, so short of some edge cases this rarely results in visible GC pauses, but can impact the throughput since scripts will interrupt to perform “GC assists” (helping clean up the garbage). Thus for high performance Luau code it’s recommended to avoid allocating memory in tight loops, by avoiding temporary table and userdata creation. In addition to a fast allocator, all frequently used structures in Luau have been optimized for memory consumption, especially on 64-bit platforms, compared to Lua 5.1 baseline. This helps to reduce heap memory footprint and improve performance in some cases by reducing the memory bandwidth impact of garbage collection. ## Optimized libraries While the best performing code in Luau spends most of the time in the interpreter, performance of the standard library functions is critical to some applications. In addition to specializing many small and simple functions using the builtin call mechanism, we spend extra care on optimizing all library functions and providing additional functions beyond the Lua standard library that help achieve good performance with idiomatic code. Functions from the `table` library like `insert`, `remove` and `move` have been tuned for performance on array-like tables, achieving 3x and more performance compared to un-tuned versions, and Luau provides additional functions like `table.create` and `table.find` to achieve further speedup when applicable. Our implementation of `table.sort` is using `introsort` algorithm which results in guaranteed worst case `NlogN` complexity regardless of the input, and, together with the array-like specializations, helps achieve ~4x speedup on average. For `string` library, we use a carefully tuned dynamic string buffer implementation; it is optimized for smaller strings to reduce garbage created during string manipulation, and for larger strings it allows to produce a large string without extra copies, especially in cases where the resulting size is known ahead of time. Additionally, functions like `format` have been tuned to avoid the overhead of `sprintf` where possible, resulting in further speedups. ## Improved garbage collector pacing Luau uses an incremental garbage collector which does a little bit of work every so often, and at no point does it stop the world to traverse the entire heap. The runtime will make sure that the collector runs interspersed with the program execution as the program allocates additional memory, which is known as “garbage collection assists”, and can also run in response to explicit garbage collection invocation via `lua_gc`. In interactive environments such as video game engines it’s possible, and even desirable, to request garbage collection every frame to make sure assists are minimized, since that allows scheduling the garbage collection to run concurrently with other engine processing that doesn’t involve script execution. Inspired by excellent work by Austin Clements on Go’s garbage collector pacer, we’ve implemented a pacing algorithm that uses a proportional–integral–derivative controller to estimate internal garbage collector tunables to reach a target heap size, defined as a percentage of the live heap data (which is more intuitive and actionable than Lua 5.x “GC pause” setting). Luau runtime also estimates the allocation rate making it easy (given uniform allocation rates) to adjust the per-frame garbage collection requests to do most of the required GC work outside of script execution. ## Reduced garbage collector pauses While Luau uses an incremental garbage collector, once per each collector cycle it runs a so-called “atomic” step. While all other GC steps can do very little work by only looking at a few objects at a given time, which means that the collector can have arbitrarily short pauses, the “atomic” step needs to traverse some amount of data that, in some cases, may scale with the application heap. Since atomic step is indivisible, it can result in occasional pauses on the order of tens of milliseconds, which is problematic for interactive applications. We’ve implemented a series of optimizations to help reduce the atomic step. Normally objects that have been modified after the GC marked them in an incremental mark phase need to be rescanned during atomic phase, so frequent modifications of existing tables may result in a slow atomic step. To address this, we run a “remark” step where we traverse objects that have been modified after being marked once more (incrementally); additionally, the write barrier that triggers for object modifications changes the transition logic during remark phase to reduce the probability that the object will need to be rescanned. Another source of scalability challenges is coroutines. Writes to coroutine stacks don’t use a write barrier, since that’s prohibitively expensive as they are too frequent. This means that coroutine stacks need to be traversed during atomic step, so applications with many coroutines suffer large atomic pauses. To address this, we implement incremental marking of coroutines: marking a coroutine makes it “inactive” and resuming a coroutine (or pushing extra objects on the coroutine stack via C API) makes it “active”. Atomic step only needs to traverse active coroutines again, which reduces the cost of atomic step by effectively making coroutine collection incremental as well. While large tables can be a problem for incremental GC in general since currently marking a single object is indivisible, large weak tables are a unique challenge because they also need to be processed during atomic phase, and the main use case for weak tables - object caches - may result in tables with large capacity but few live objects in long-running applications that exhibit bursts of activity. To address this, weak tables in Luau can be marked as “shrinkable” by including `s` as part of `__mode` string, which results in weak tables being resized to the optimal capacity during GC. This option may result in missing keys during table iteration if the table is resized while iteration is in progress and as such is only recommended for use in specific circumstances. ## Optimized garbage collector sweeping The incremental garbage collector in Luau runs three phases for each cycle: mark, atomic and sweep. Mark incrementally traverses all live objects, atomic finishes various operations that need to happen without mutator intervention (see previous section), and sweep traverses all objects in the heap, reclaiming memory used by dead objects and performing minor fixup for live objects. While objects allocated during the mark phase are traversed in the same cycle and thus may get reclaimed, objects allocated during the sweep phase are considered live. Because of this, the faster the sweep phase completes, the less garbage will accumulate; and, of course, the less time sweeping takes the less overhead there is from this phase of garbage collection on the process. Since sweeping traverses the whole heap, we maximize the efficiency of this traversal by allocating garbage-collected objects of the same size in 16 KB pages, and traversing each page at a time, which is otherwise known as a paged sweeper. This ensures good locality of reference as consecutively swept objects are contiguous in memory, and allows us to spend no memory for each object on sweep-related data or allocation metadata, since paged sweeper doesn’t need to be able to free objects without knowing which page they are in. Compared to linked list based sweeping that Lua/LuaJIT implement, paged sweeper is 2-3x faster, and saves 16 bytes per object on 64-bit platforms. ## Function inlining and loop unrolling By default, the bytecode compiler performs a series of optimizations that result in faster execution of the code, but they preserve both execution semantics and debuggability. For example, a function call is compiled as a function call, which may be observable via `debug.traceback`; a loop is compiled as a loop, which may be observable via `lua_getlocal`. To help improve performance in cases where these restrictions can be relaxed, the bytecode compiler implements additional optimizations when optimization level 2 is enabled (which requires using `-O2` switch when using Luau CLI), namely function inlining and loop unrolling. Only loops with loop bounds known at compile time, such as `for i=1,4 do`, can be unrolled. The loop body must be simple enough for the optimization to be profitable; compiler uses heuristics to estimate the performance benefit and automatically decide if unrolling should be performed. Only local functions (defined either as `local function foo` or `local foo = function`) can be inlined. The function body must be simple enough for the optimization to be profitable; compiler uses heuristics to estimate the performance benefit and automatically decide if each call to the function should be inlined instead. Additionally recursive invocations of a function can’t be inlined at this time, and inlining is completely disabled for modules that use `getfenv`/`setfenv` functions. In both cases, in addition to removing the overhead associated with function calls or loop iteration, these optimizations can additionally benefit by enabling additional optimizations, such as constant folding of expressions dependent on loop iteration variable or constant function arguments, or using more efficient instructions for certain expressions when the inputs to these instructions are constants.
6,321
432a2aefd303b74f2e83dea42a0bb1e2b8aa72fd7d760996f856dba6ff04e278
https://luau.org/lint
https://luau.org/
2026-03-29T11:32:05.864226+00:00
# Luau's linter Luau comes with a set of linting passes, that help make sure that the code is correct and consistent. Unlike the type checker, that models the behavior of the code thoroughly and points toward type mismatches that are likely to result in runtime errors, the linter is more opinionated and produces warnings that can often be safely ignored, although it’s recommended to keep the code clean of the warnings. Linter produces many different types of warnings; many of these are enabled by default, and can be suppressed by declaring `--!nolint NAME` at the top of the file. In dire situations `--!nolint` at the top of the file can be used to completely disable all warnings (note that the type checker is still active, and requires a separate `--!nocheck` declaration). The rest of this page documents all warnings produced by the linter; each warning has a name and a numeric code, the latter is used when displaying warnings. Note that the in-browser version of Luau on this website does not currently use the linter. ## UnknownGlobal (1) By default, variables in Luau are global (this is inherited from Lua 5.x and can’t be changed because of backwards compatibility). This means that typos in identifiers are invisible to the parser, and often break at runtime. For this reason, the linter considers all globals that aren’t part of the builtin global table and aren’t explicitly defined in the script “unknown”: Note that injecting globals via `setfenv` can produce this warning in correct code; global injection is incompatible with type checking and has performance implications so we recommend against it and in favor of using `require` with correctly scoped identifiers. Users should also note that this lint is separate from Luau’s type system and is only enabled in `nocheck`. In `nonstrict` and `strict` modes, unknown globals are caught by the type checker instead, and this lint will always be silenced automatically. ## DeprecatedGlobal (2) Some global names exist for compatibility but their use is discouraged. This mostly affects globals introduced by Roblox, and since they can have problematic behavior or can break in the future, this warning highlights their uses: ## GlobalUsedAsLocal (3) The UnknownGlobal lint can catch typos in globals that are read, but can’t catch them in globals that are assigned to. Because of this, and to discourage the use of globals in general, linter detects cases when a global is only used in one function and can be safely converted to a local variable. Note that in some cases this requires declaring the local variable in the beginning of the function instead of where it’s being assigned to. ## LocalShadow (4) In Luau, it is valid to shadow locals and globals with a local variable, including doing it in the same function. This can result in subtle bugs, since the shadowing may not be obvious to the reader. This warning detects cases where local variables shadow other local variables in the same function, or global variables used in the script. ## SameLineStatement (5) Luau doesn’t require the use of semicolons and doesn’t automatically insert them at line breaks. When used wisely this results in code that is easy to read and understand, however it can cause subtle issues and hard to understand code when abused by using many different statements on the same line. This warning highlights cases where code should either be broken into multiple lines, or use `;` as a visual guide. ## MultiLineStatement (6) An opposite problem is having statements that span multiple lines. This is good for readability when the code is indented properly, but when it’s not it results in code that’s hard to understand, as its easy to confuse the next line for a separate statement. ## LocalUnused (7) This warning is one of the few warnings that highlight unused variables. Local variable declarations that aren’t used may indicate a bug in the code (for example, there could be a typo in the code that uses the wrong variable) or redundant code that is no longer necessary (for example, calling a function to get its result and never using this result). This warning warns about locals that aren’t used; if the locals are not used intentionally they can be prefixed with `_` to silence the warning: ## FunctionUnused (8) While unused local variables could be useful for debugging, unused functions usually contain dead code that was meant to be removed. Unused functions clutter code, can be a result of typos similar to local variables, and can mislead the reader into thinking that some functionality is supported. ## ImportUnused (9) In Luau, there’s no first-class module system that’s part of the syntax, but `require` function acts as an import statement. When a local is initialized with a `require` result, and the local is unused, this is classified as “unused import”. Removing unused imports improves code quality because it makes it obvious what the dependencies of the code are: ## BuiltinGlobalWrite (10) While the sandboxing model of Luau prevents overwriting built-in globals such as `table` for the entire program, it’s still valid to reassign these globals - this results in “global shadowing”, where the script’s global table contains a custom version of `table` after writing to it. This is problematic because it disables some optimizations, and can result in misleading code. When shadowing built-in globals, use locals instead. ## PlaceholderRead (11) `_` variable name is commonly used as a placeholder to discard function results. The linter follows this convention and doesn’t warn about the use of `_` in various cases where a different name would cause a warning otherwise. To make sure the placeholder is only used to write values to it, this warning detects the cases where it’s read instead: ## UnreachableCode (12) In some cases the linter can detect code that is never executed, because all execution paths through the function exit the function or the loop before reaching it. Such code is misleading because it’s not always obvious to the reader that it never runs, and as such it should be removed. ## UnknownType (13) Luau provides several functions to get the value type as a string (`type`, `typeof`), and some Roblox APIs expose class names through string arguments (`Instance.new`). This warning detects incorrect use of the type names by checking the string literals used in type comparisons and function calls. ## ForRange (14) When using a numeric for, it’s possible to make various mistakes when specifying the for bounds. For example, to iterate through the table backwards, it’s important to specify the negative step size. This warning detects several cases where the numeric for only runs for 0 or 1 iterations, or when the step doesn’t divide the size of the range evenly. ## UnbalancedAssignment (15) Assignment statements and local variable declarations in Luau support multiple variables on the left side and multiple values on the right side. The number of values doesn’t need to match; when the right side has more values, the extra values are discarded, and then the left side has more variables the extra variables are set to `nil`. However, this can result in subtle bugs where a value is omitted mistakenly. This warning warns about cases like this; if the last expression on the right hand side returns multiple values, the warning is not emitted. ## ImplicitReturn (16) In Luau, there’s a subtle difference between returning no values from a function and returning `nil`. In many contexts these are equivalent, but when the results are passed to a variadic function (perhaps implicitly), the difference can be observed - for example, `print(foo())` prints nothing if `foo` returns no values, and `nil` if it returns `nil`. To help write code that has consistent behavior, linter warns about cases when a function implicitly returns no values, if there are cases when it explicitly returns a result. For code like this it’s recommended to use explicit `return` or `return nil` at the end of the function (these have different semantics, so the correct version to use depends on the function): ## DuplicateLocal (17) Luau syntax allows to use the same name for different parameters of a function as well as different local variables declared in the same statement. This is error prone, even if it’s occasionally useful, so a warning is emitted in cases like this, unless the duplicate name is the placeholder `_`: ## FormatString (18) Luau has several library functions that expect a format string that specifies the behavior for the function. These format strings follow a specific syntax that depends on the question; mistakes in these strings can lead to runtime errors or unexpected behavior of the code. To help make sure that the strings used for these functions are correct, linter checks calls to `string.format`, `string.pack`, `string.packsize`, `string.unpack`, `string.match`, `string.gmatch`, `string.find`, `string.gsub` and `os.date` and issues warnings when the call uses a literal string with an incorrect format: Note that with the exception of `string.format` this only works when the function is called via the library, not via the method call (so prefer `string.match(s, "pattern")` to `s:match("pattern")`). ## TableLiteral (19) Table literals are often used in Luau to create objects or specify data. The syntax for table literals is rich but invites mistakes, for example it allows duplicate keys or redundant index specification for values already present in the list form. This warning is emitted for cases where some entries in the table literal are ignored at runtime as they’re duplicate: ## UninitializedLocal (20) It’s easy to forget to initialize a local variable and then proceed to use it regardless. This can happen due to a typo, or sometimes it can happen because the original variable definition is shadowed. When a local variable doesn’t have an initial value and is used without ever being assigned to, this warning is emitted: ## DuplicateFunction (21) This warning is emitted when a script defines two functions with the same name in the same scope. The warning is not produced when the functions are defined in different scopes because this is much more likely to be intentional. ## DeprecatedApi (22) This warning is emitted when a script accesses a method or field that is marked as deprecated. Use of deprecated APIs is discouraged since they may have performance or correctness issues, may result in unexpected behavior, and could be removed in the future. ## TableOperations (23) To manipulate array-like tables, Luau provides a set of functions as part of the standard `table` library. To help use these functions correctly, this warning is emitted when one of these functions is used incorrectly or can be adjusted to be more performant. In addition, when type information is present, this warning will be emitted when `#` or `ipairs` is used on a table that has no numeric keys or indexers. This helps avoid common bugs like using `#t == 0` to check if a dictionary is empty. ## DuplicateCondition (24) When checking multiple conditions via `and/or` or `if/elseif`, a copy & paste error may result in checking the same condition redundantly. This almost always indicates a bug, so a warning is emitted when use of a duplicate condition is detected. ## MisleadingAndOr (25) In Lua, there is no first-class ternary operator but it can be emulated via `a and b or c` pattern. However, due to how boolean evaluation works, if `b` is `false` or `nil`, the resulting expression evaluates to `c` regardless of the value of `a`. Luau solves this problem with the `if a then b else c` expression; a warning is emitted for and-or expressions where the first alternative is `false` or `nil` because it’s almost always a bug. The code above can be rewritten as follows to avoid the warning and the associated bug: ## CommentDirective (26) Luau uses comments that start from `!` to control certain aspects of analysis, for example setting type checking mode via `--!strict` or disabling individual lints with `--!nolint`. Unknown directives are ignored, for example `--!nostrict` doesn’t have any effect on the type checking process as the correct spelling is `--!nonstrict`. This warning flags comment directives that are ignored during processing: ## IntegerParsing (27) Luau parses hexadecimal and binary literals as 64-bit integers before converting them to Luau numbers. As a result, numbers that exceed 2^64 are silently truncated to 2^64, which can result in unexpected program behavior. This warning flags literals that are truncated: Luau numbers are represented as double precision IEEE754 floating point numbers; they can represent integers up to 2^53 exactly, but larger integers may lose precision. This warning also flags literals that are parsed with a precision loss: ## ComparisonPrecedence (28) Because of operator precedence rules, not X == Y parses as (not X) == Y; however, often the intent was to invert the result of the comparison. This warning flags erroneous conditions like that, as well as flagging cases where two comparisons happen in a row without any parentheses:
2,730
0dccc626753c8734606c81e0824f30ff93cd8763f435b8148c50016e02bcb55a
https://luau.org/sandbox
https://luau.org/
2026-03-29T11:32:05.891891+00:00
# Embedding a sandboxed Luau virtual machine Luau is safe to embed. Broadly speaking, this means that even in the face of untrusted (and in Roblox case, actively malicious) code, the language and the standard library don’t allow unsafe access to the underlying system, and don’t have known bugs that allow escaping out of the sandbox (e.g. to gain native code execution through ROP gadgets et al). Additionally, the VM provides extra features to implement isolation of privileged code from unprivileged code and protect one from the other; this is important if the embedding environment decides to expose some APIs that may not be safe to call from untrusted code, for example because they do provide controlled access to the underlying system or risk PII exposure through fingerprinting etc. This safety is achieved through a combination of removing features from the standard library that are unsafe, adding features to the VM that make it possible to implement sandboxing and isolation, and making sure the implementation is safe from memory safety issues using fuzzing. Of course, since the entire stack is implemented in C++, the sandboxing isn’t formally proven - in theory, compiler or the standard library can have exploitable vulnerabilities. In practice these are very rare and usually found and fixed quickly. While implementing the stack in a safer language such as Rust would make it easier to provide these guarantees, to our knowledge (based on prior art) this would make it difficult to reach the level of performance required. ## Library Parts of the Lua 5.x standard library are unsafe. Some of the functions provide access to the host operating system, including process execution and file reads. Some functions lack sufficient memory safety checks. Some functions are safe if all code is untrusted, but can break the isolation barrier between trusted and untrusted code. The following libraries and global functions have been removed as a result: - `io.` library has been removed entirely, as it gives access to files and allows running processes - `package.` library has been removed entirely, as it gives access to files and allows loading native modules - `os.` library has been cleaned up from file and environment access functions (`execute`, `exit`, etc.). The only supported functions in the library are `clock`, `date`, `difftime` and `time`. - `debug.` library has been removed to a large extent, as it has functions that aren’t memory safe and other functions break isolation; the only supported functions are `traceback` and `info` (which is similar to `debug.getinfo` but has a slightly different interface). - `dofile` and `loadfile` allowed access to file system and have been removed. To achieve memory safety, access to function bytecode has been removed. Bytecode is hard to validate and using untrusted bytecode may lead to exploits. Thus, `loadstring` doesn’t work with bytecode inputs, and `string.dump`/`load` have been removed as they aren’t necessary anymore. When embedding Luau, bytecode should be encrypted/signed to prevent MITM attacks as well, as the VM assumes that the bytecode was generated by the Luau compiler (which never produces invalid/unsafe bytecode). Finally, to make isolation possible within the same VM, the following global functions have reduced functionality: - `collectgarbage` only works with `"count"` argument, as modifying the state of GC can interfere with the expectations of other code running in the process. As such, `collectgarbage()` became an inferior version of `gcinfo()` and is deprecated. - `newproxy` only works with `true`/`false`/`nil` arguments. - `module` allowed overriding global packages and was removed as a result. > Note: `getfenv`/`setfenv` result in additional isolation challenges, as they allow injecting globals into scripts on the call stack. Ideally, these should be disabled as well, but unfortunately Roblox community relies on these for various reasons. This can be mitigated by limiting interaction between trusted and untrusted code, and/or using separate VMs. ## Environment The modification to the library functions are sufficient to make embedding safe, but aren’t sufficient to provide isolation within the same VM. It should be noted that to achieve guaranteed isolation, it’s advisable to load trusted and untrusted code into separate VMs; however, even within the same VM Luau provides additional safety features to make isolation cheaper. When initializing the default globals table, the tables are protected from modification: - All libraries (`string`, `math`, etc.) are marked as readonly - The string metatable is marked as readonly - The global table itself is marked as readonly This is using the VM feature that is not accessible from scripts, that prevents all writes to the table, including assignments, `rawset` and `setmetatable`. This makes sure that globals can’t be monkey-patched in place, and can only be substituted through `setfenv`. By itself this would mean that code that runs in Luau can’t use globals at all, since assigning globals would fail. While this is feasible, in Roblox we solve this by creating a new global table for each script, that uses `__index` to point to the builtin global table. This safely sandboxes the builtin globals while still allowing writing globals from each script. This also means that short of exposing special shared globals from the host, all scripts are isolated from each other. ## `__gc` Lua 5.1 exposes a `__gc` metamethod for userdata, which can be used on proxies (`newproxy`) to hook into garbage collector. Later versions of Lua extend this mechanism to work on tables. This mechanism is bad for performance, memory safety and isolation: - In Lua 5.1, `__gc` support requires traversing userdata lists redundantly during garbage collection to filter out finalizable objects - In later versions of Lua, userdata that implement `__gc` are split into separate lists; however, finalization prolongs the lifetime of the finalized objects which results in less prompt memory reclamation, and two-step destruction results in extra cache misses for userdata - `__gc` runs during garbage collection in context of an arbitrary thread which makes the thread identity mechanism used in Roblox to support trusted Luau code invalid - Objects can be removed from weak tables *after* being finalized, which means that accessing these objects can result in memory safety bugs, unless all exposed userdata methods guard against use-after-gc. - If `__gc` method ever leaks to scripts, they can call it directly on an object and use any method exposed by that object after that. This means that `__gc` and all other exposed methods must support memory safety when called on a destroyed object. Because of these issues, Luau does not support `__gc`. Instead it uses tag-based destructors that can perform additional memory cleanup during userdata destruction; crucially, these are only available to the host (so they can never be invoked manually), and they run right before freeing the userdata memory block which is both optimal for performance, and guaranteed to be memory safe. For monitoring garbage collector behavior the recommendation is to use weak tables instead. ## Interrupts In addition to preventing API access, it can be important for isolation to limit the memory and CPU usage of code that runs inside the VM. By default, no memory limits are imposed on the running code, so it’s possible to exhaust the address space of the host; this is easy to configure from the host for Luau allocations, but of course with a rich API surface exposed by the host it’s hard to eliminate this as a possibility. Memory exhaustion doesn’t result in memory safety issues or any particular risk to the system that’s running the host process, other than the host process getting terminated by the OS. Limiting CPU usage can be equally challenging with a rich API. However, Luau does provide a VM-level feature to try to contain runaway scripts which makes it possible to terminate any script externally. This works through a global interrupt mechanism, where the host can setup an interrupt handler at any point, and any Luau code is guaranteed to call this handler “eventually” (in practice this can happen at any function call or at any loop iteration). This still leaves the possibility of a very long running script open if the script manages to find a way to call a single C function that takes a lot of time, but short of that the interruption is very prompt. Roblox sets up the interrupt handler using a watchdog that: - Limits the runtime of any script in Studio to 10 seconds (configurable through Studio settings) - Upon client shutdown, interrupts execution of every running script 1 second after shutdown
1,772
514410ccca384947fd4fd84024f2e2e8ca01e616c5a64d4ac931159de5d5793f
https://luau.org/syntax
https://luau.org/
2026-03-29T11:32:05.917502+00:00
# Luau syntax by example Luau uses the baseline [syntax of Lua 5.1](https://www.lua.org/manual/5.1/manual.html#2). For detailed documentation, please refer to the Lua manual, this is an example: Note that future versions of Lua extend the Lua 5.1 syntax with more features; Luau does support string literal extensions but does not support other 5.x additions; for details please refer to [compatibility section](../compatibility). The rest of this document documents additional syntax used in Luau. ## String literals Luau implements support for hexadecimal (`x`), Unicode (`u`) and `z` escapes for string literals. This syntax follows [Lua 5.3 syntax](https://www.lua.org/manual/5.3/manual.html#3.1): - `xAB` inserts a character with the code 0xAB into the string - `u{ABC}` inserts a UTF8 byte sequence that encodes U+0ABC character into the string (note that braces are mandatory) - `z` at the end of the line inside a string literal ignores all following whitespace including newlines, which can be helpful for breaking long literals into multiple lines. ## Number literals In addition to basic integer and floating-point decimal numbers, Luau supports: - Hexadecimal integer literals, `0xABC` or `0XABC` - Binary integer literals, `0b01010101` or `0B01010101` - Decimal separators in all integer literals, using `_` for readability: `1_048_576`, `0xFFFF_FFFF`, `0b_0101_0101` Note that Luau only has a single number type, a 64-bit IEEE754 double precision number (which can represent integers up to 2^53 exactly), and larger integer literals are stored with precision loss. ## Continue statement In addition to `break` in all loops, Luau supports `continue` statement. Similar to `break`, `continue` must be the last statement in the block. Note that unlike `break`, `continue` is not a keyword. This is required to preserve backwards compatibility with existing code; so this is a `continue` statement: Whereas this is a function call: When used in `repeat..until` loops, `continue` can not skip the declaration of a local variable if that local variable is used in the loop condition; code like this is invalid and won’t compile: ## Compound assignments Luau supports compound assignments with the following operators: `+=`, `-=`, `*=`, `/=`, `//=`, `%=`, `^=`, `..=`. Just like regular assignments, compound assignments are statements, not expressions: Compound assignments only support a single value on the left and right hand side; additionally, the function calls on the left hand side are only evaluated once: Compound assignments call the arithmetic metamethods (`__add` et al) and table indexing metamethods (`__index` and `__newindex`) as needed - for custom types no extra effort is necessary to support them. ## Type annotations To support gradual typing, Luau supports optional type annotations for variables and functions, as well as declaring type aliases. Types can be declared for local variables, function arguments and function return types using `:` as a separator: In addition, the type of any expression can be overridden using a type cast `::`: There are several simple builtin types: `any` (represents inability of the type checker to reason about the type), `nil`, `boolean`, `number`, `string` and `thread`. Function types are specified using the arguments and return types, separated with `->`: To return no values or more than one, you need to wrap the return type position with parentheses, and then list your types there. Note that function types are specified without the argument names in the examples above, but it’s also possible to specify the names (that are not semantically significant but can show up in documentation and autocomplete): Table types are specified using the table literal syntax, using `:` to separate keys from values: When the table consists of values keyed by numbers, it’s called an array-like table and has a special short-hand syntax, `{T}` (e.g. `{string}`). Additionally, the type syntax supports type intersections (`((number) -> string) & ((boolean) -> string)`) and unions (`(number | boolean) -> string`). An intersection represents a type with values that conform to both sides at the same time, which is useful for overloaded functions; a union represents a type that can store values of either type - `any` is technically a union of all possible types. It’s common in Lua for function arguments or other values to store either a value of a given type or `nil`; this is represented as a union (`number | nil`), but can be specified using `?` as a shorthand syntax (`number?`). In addition to declaring types for a given value, Luau supports declaring type aliases via `type` syntax: The right hand side of the type alias can be a type definition or a `typeof` expression; `typeof` expression doesn’t evaluate its argument at runtime. By default type aliases are local to the file they are declared in. To be able to use type aliases in other modules using `require`, they need to be exported: An exported type can be used in another module by prefixing its name with the require alias that you used to import the module. For more information please refer to [typechecking documentation](../types). ## If-then-else expressions In addition to supporting standard if *statements*, Luau adds support for if *expressions*. Syntactically, `if-then-else` expressions look very similar to if statements. However instead of conditionally executing blocks of code, if expressions conditionally evaluate expressions and return the value produced as a result. Also, unlike if statements, if expressions do not terminate with the `end` keyword. Here is a simple example of an `if-then-else` expression: `if-then-else` expressions may occur in any place a regular expression is used. The `if-then-else` expression must match `if <expr> then <expr> else <expr>`; it can also contain an arbitrary number of `elseif` clauses, like `if <expr> then <expr> elseif <expr> then <expr> else <expr>`. Note that in either case, `else` is mandatory. Here’s is an example demonstrating `elseif`: **Note:** In Luau, the `if-then-else` expression is preferred vs the standard Lua idiom of writing `a and b or c` (which roughly simulates a ternary operator). However, the Lua idiom may return an unexpected result if `b` evaluates to false. The `if-then-else` expression will behave as expected in all situations. ## Generalized iteration Luau uses the standard Lua syntax for iterating through containers, `for vars in values`, but extends the semantics with support for generalized iteration. In Lua, to iterate over a table you need to use an iterator like `next` or a function that returns one like `pairs` or `ipairs`. In Luau, you can simply iterate over a table: Further, iteration can be extended for tables or userdata by implementing the `__iter` metamethod which is called before the iteration begins, and should return an iterator function like `next` (or a custom one): The default iteration order for tables is specified to be consecutive for elements `1..#t` and unordered after that, visiting every element; similarly to iteration using `pairs`, modifying the table entries for keys other than the current one results in unspecified behavior. ## String interpolation Luau adds an additional way to define string values that allows you to place runtime expressions directly inside specific spots of the literal. This is a more ergonomic alternative over using `string.format` or `("literal"):format`. To use string interpolation, use a backtick string literal: Any expression can be used inside `{}`: Inside backtick string literal, `\` is used to escape `` ` ``, `{`, `\` itself and a newline: ### Restrictions and limitations The sequence of two opening braces {{“`{{`”}} is rejected with a parse error. This restriction is made to prevent developers using other programming languages with a similar feature from trying to attempt that as a way to escape a single `{` and getting unexpected results in Luau. Luau currently does not support backtick string literals in type annotations, therefore `` type Foo = `Foo` `` is invalid syntax. Unlike single and double-quoted string literals, backtick string literals must always be wrapped in parentheses for function calls: ## Floor division (`//`) Luau supports floor division, including its operator (`//`), its compound assignment operator (`//=`), and overloading metamethod (`__idiv`), as an ergonomic alternative to `math.floor`. For numbers, `a // b` is equal to `math.floor(a / b)`: Note that it’s possible to get `inf`, `-inf`, or `NaN` with floor division; when `b` is `0`, `a // b` results in positive or negative infinity, and when both `a` and `b` are `0`, `a // b` results in NaN. For native vectors, `c // d` applies `math.floor` to each component of the vector `c`. Therefore `c // d` is equivalent to `vector.create(math.floor(c.x / d), math.floor(c.y / b), math.floor(c.z / b))`. Floor division syntax and semantics follow from [Lua 5.3](https://www.lua.org/manual/5.3/manual.html#3.4.1) where applicable.
2,038
f093f5481f5fda480ba73cad65adaa727d6113005d374299059880db38793d77
https://luau.org/types/basic-types
https://luau.org/
2026-03-29T11:32:08.583073+00:00
# Primitives and Simple Types ## Builtin types The Luau VM supports 10 primitive types: 1. `nil` 2. `string` 3. `number` 4. `boolean` 5. `table` 6. `function` 7. `thread` 8. `userdata` 9. `vector` 10. `buffer` Most of these can be specified by their name and written directly in type annotations: Some types have special syntax: - `table` and `function` are not represented by name, but have their dedicated syntax as covered in this [syntax document](../../syntax) - `userdata` is represented by [concrete types](../roblox-types), and - `vector` is not representable by name at all The type checker also provides the builtin types [`unknown`](#unknown-type), [`never`](#never-type), and [`any`](#any-type). #### Special behavior with `nil` There’s a special case where we intentionally avoid inferring `nil` for local variables. This allows you to declare variables first and assign values to them later — if we inferred `nil`, you wouldn’t be able to assign other types to these variables. ### `unknown` type `unknown` is also said to be the *top* type, that is it’s a union of all types. Unlike `any`, `unknown` will not allow itself to be used as a different type! In order to turn a variable of type `unknown` into a different type, you must apply [type refinements](../types/refinements.md) on that variable. ### `never` type `never` is also said to be the *bottom* type, meaning there doesn’t exist a value that inhabits the type `never`. In fact, it is the *dual* of `unknown`. `never` is useful in many scenarios, and one such use case is when type refinements proves it impossible: ### `any` type `any` is just like `unknown`, except that it allows itself to be used as an arbitrary type without further checks or annotations. Essentially, it’s an opt-out from the type system entirely. ## Function types Let’s start with something simple. In strict mode, the inferred type of this function `f` is `<A>(A) -> A` (take a look at [generics](../generics)), whereas in nonstrict we infer `(any) -> any`. We know this is true because `f` can take anything and then return that. If we used `x` with another concrete type, then we would end up inferring that. Similarly, we can infer the types of the parameters with ease. By passing a parameter into *anything* that also has a type, we are saying “this and that has the same type.” ## Variadic types Luau permits assigning a type to the `...` variadic symbol like any other parameter: `f` accepts any number of `number` values. In type annotations, this is written as `...T`: ## Type packs Multiple function return values as well as the function variadic parameter use a type pack to represent a list of types. When a type alias is defined, generic type pack parameters can be used after the type parameters: > Keep in mind that `...T` is a variadic type pack (many elements of the same type `T`), while `U...` is a generic type pack that can contain zero or more types and they don’t have to be the same. It is also possible for a generic function to reference a generic type pack from the generics list: Generic types with type packs can be instantiated by providing a type pack: There are also other ways to instantiate types with generic type pack parameters: Trailing type pack argument can also be provided without parentheses by specifying variadic type arguments: Type pack parameters are not limited to a single one, as many as required can be specified: ## Singleton types (aka literal types) Luau’s type system also supports singleton types, which means it’s a type that represents one single value at runtime. At this time, both string and booleans are representable in types. > We do not currently support numbers as types. For now, this is intentional. This happens all the time, especially through [type refinements](../type-refinements) and is also incredibly useful when you want to enforce program invariants in the type system! See [tagged unions](../unions-and-intersections/#tagged-unions) for more information.
935
a5b825ecc658e2b4c9fc7ba07c2ff87ea6dd8a362f1f5ab495325fb3337396ff
https://luau.org/types/generics
https://luau.org/
2026-03-29T11:32:08.636747+00:00
# Generics and Polymorphism The type inference engine was built from the ground up to recognize generics. A generic is simply a type parameter in which another type could be slotted in. It’s extremely useful because it allows the type inference engine to remember what the type actually is, unlike `any`. ## Generic functions As well as generic type aliases like `Pair<T>`, Luau supports generic functions. These are functions that, as well as their regular data parameters, take type parameters. For example, a function which reverses an array is: The type of this function is that it can reverse an array, and return an array of the same type. Luau can infer this type, but if you want to be explicit, you can declare the type parameter `T`, for example: When a generic function is called, Luau infers type arguments, for example Generic types are used for built-in functions as well as user functions, for example the type of two-argument `table.insert` is: Note: Functions don’t support having defaults assigned to generics, meaning the following is invalid
224
a75a5636e19419d99537d17538399accd51a4c1ea853b655fe258ae50ef14527
https://luau.org/guides/profile
https://luau.org/
2026-03-29T11:32:08.648325+00:00
# Profiling your Luau code One of main goals of Luau is to enable high performance code. To help with that goal, we are relentlessly optimizing the compiler and runtime - but ultimately, performance of their code is in developers’ hands, and is a combination of good algorithm design and implementation that adheres to the strengths of the language. To help write efficient code, Luau provides a built-in profiler that samples the execution of the program and outputs a profiler dump that can be converted to an interactive flamegraph. To run the profiler, make sure you have an optimized build of the interpreter (otherwise profiling results are going to be very skewed) and run it with `--profile` argument: The resulting `profile.out` file can be converted to an SVG file by running `perfgraph.py` script that is part of Luau repository: This produces an SVG file that can be opened in a browser (the image below is clickable): [![profile.svg](/images/chess-profile.svg)](/images/chess-profile.svg) In a flame graph visualization, the individual bars represent function calls, the width represents how much of the total program runtime they execute, and the nesting matches the call stack encountered during program execution. This is a fantastic visualization technique that allows you to hone in on the specific bottlenecks affecting your program performance, optimize those exact bottlenecks, and then re-generate the profile data and visualizer, and look for the next set of true bottlenecks (if any). Hovering your mouse cursor over individual sections will display detailed function information in the status bar and in a tooltip. If you want to Search for a specific named function, use the Search field in the upper right, or press Ctrl+F. Notice that some of the bars in the screenshot don’t have any text. In some cases, there isn’t enough room in the size of the bar to display the name. You can hover your mouse over those bars to see the name and source location of the function in the tool tip, or double-click to zoom in on that part of the flame graph. Some tooltips will have a source location for the function you’re hovering over, but no name. Those are anonymous functions, or functions that were not declared in a way that allows Luau compiler to track the name. To fill in more names, you may want to make these changes to your code: `local myFunc = function() --[[ work ]] end` -> `local function myFunc() --[[ work ]] end` Even without these changes, you can hover over a given bar with no visible name and see it’s source location. As any sampling profiler, this profiler relies on gathering enough information for the resulting output to be statistically meaningful. It may miss short functions if they aren’t called often enough. By default the profiler runs at 10 kHz, this can be customized by passing a different parameter to `--profile=`. Note that higher frequencies result in higher profiling overhead and longer program execution, potentially skewing the results. This profiler doesn’t track leaf C functions and instead attributes the time spent there to calling Luau functions. As a result, when thinking about why a given function is slow, consider not just the work it does immediately but also the library functions it calls. This profiler tracks time consumed by Luau thread stacks; when a thread calls another thread via `coroutine.resume`, the time spent is not attributed to the parent thread that’s waiting for resume results. This limitation will be removed in the future.
722
7f638f2603cefaf2b5e3cd87a64031194f4800e2bf97c6bb6c3ff312a7c4861a
https://luau.org/types/unions-and-intersections
https://luau.org/
2026-03-29T11:32:08.666317+00:00
# Union and Intersection Types ## Union types A union type represents *one of* the types in this set. If you try to pass a union onto another thing that expects a *more specific* type, it will fail. For example, what if this `string | number` was passed into something that expects `number`, but the passed in value was actually a `string`? Note: it’s impossible to be able to call a function if there are two or more function types in this union. ### Tagged unions Tagged unions are just union types! In particular, they’re union types of tables where they have at least *some* common properties but the structure of the tables are different enough. Here’s one example: This `Result<T, E>` type can be discriminated by using type refinements on the property `type`, like so: Which works out because `value: T` exists only when `type` is in actual fact `"ok"`, and `error: E` exists only when `type` is in actual fact `"err"`. ## Intersection types An intersection type represents *all of* the types in this set. It’s useful for two main things: to join multiple tables together, or to specify overloadable functions. Note: it’s impossible to create an intersection type of some primitive types, e.g. `string & number`, or `string & boolean`, or other variations thereof. Note: Luau still does not support user-defined overloaded functions. Some of Roblox and Lua 5.1 functions have different function signature, so inherently requires overloaded functions.
327
29d45b15298e685b887b431cfbf123705973bc514e11e3abaaa5633caea45790
https://luau.org/types/tables
https://luau.org/
2026-03-29T11:32:08.679420+00:00
# Table Types From the type checker perspective, each table can be in one of three states. They are: `unsealed table`, `sealed table`, and `generic table`. This is intended to represent how the table’s type is allowed to change. ### Unsealed tables An unsealed table is a table which supports adding new properties, which updates the tables type. Unsealed tables are created using table literals. This is one way to accumulate knowledge of the shape of this table. However, if this local were written as `local t: { x: number } = { x = 1 }`, it ends up sealing the table, so the two assignments henceforth will not be ok. Furthermore, once we exit the scope where this unsealed table was created in, we seal it. Unsealed tables are *exact* in that any property of the table must be named by the type. Since Luau treats missing properties as having value `nil`, this means that we can treat an unsealed table which does not mention a property as if it mentioned the property, as long as that property is optional. ### Sealed tables A sealed table is a table that is now locked down. This occurs when the table type is spelled out explicitly via a type annotation, or if it is returned from a function. Sealed tables are *inexact* in that the table may have properties which are not mentioned in the type. As a result, sealed tables support *width subtyping*, which allows a table with more properties to be used as a table with fewer properties. ### Generic tables This typically occurs when the symbol does not have any annotated types or were not inferred anything concrete. In this case, when you index on a parameter, you’re requesting that there is a table with a matching interface. ## Table indexers These are particularly useful for when your table is used similarly to an array. Luau supports a concise declaration for array-like tables, `{T}` (for example, `{string}` is equivalent to `{[number]: string}`); the more explicit definition of an indexer is still useful when the key isn’t a number, or when the table has other fields like `{ [number]: string, n: number }`.
454
6aecb6a9ce8d4b112416b6019521e01c0c36df7afd6a7c41bfb5361e1679711f
https://luau.org/types
https://luau.org/
2026-03-29T11:32:08.686353+00:00
# An introduction to Luau types Luau supports a gradual type system through the use of type annotations and type inference. These types are used to provide warnings, errors, and suggestions for our developers. Type checking helps you find bugs early - while you’re writing code - rather than discovering when your program crashes at runtime. ## Type inference modes Luau offers three different modes that control how strictly it checks your types. You can set the mode by adding one of the following to the top of your file: - `--!nocheck`, - `--!nonstrict` (default), and - `--!strict` ##### `--!nocheck` `nocheck` mode completely disables the type inference engine for the file. With this mode enabled, we don’t provide any feedback on the types, so scripts with errors (like following example that tries to add a `string` and a `number`) will not raise a typecheck error, even though the program errors when executed. Try pressing the `Check` and `Run` buttons to try out this snippet: If, instead, you want to catch these kinds of errors before running your code, you can enable type checking with the `--!nonstrict` or `--!strict` modes. Both of these modes analyze your types and provide helpful feedback, but they differ slightly in how strictly they enforce type safety. ##### `--!nonstrict` In `nonstrict` mode, the type checker is more forgiving: if we can’t figure out what type something is early on, we infer the type could be anything (the `any` type) and let you proceed without errors. This means that if we define a variable without initializing it or specifying its type: The type checker can’t tell what type `foo` should be when it’s first declared, so in `nonstrict` mode it infers `any` - allowing the addition to proceed without warnings, even though it will error at runtime. ##### `--!strict` In `strict` mode, Luau is smarter about tracking types across statements. Given the previous example now in `strict` mode: We see an error! The type checker sees `foo = 1` on line 4 and infers that `foo` must be a `number`. Then, when you try to add `"hello "` and `foo`, `strict` mode catches our error of trying to add a `string` and a `number`, which isn’t allowed. (tip: hover over the erroneous lines to see the error message!) ## Structural type system Luau’s type system is structural by default, which is to say that we inspect the shape of two tables to see if they are similar enough. This was chosen because Lua 5.1 is inherently structural. Take, for example, these two tables `A` and `B`: ## Type annotations While Luau’s type system can infer many types, you can also annotate types using a colon (`:`) followed by the type: ## Type casts Sometimes, you might want to specify the type of an expression when the automatically inferred type is too generic. In these cases, you can use a type cast with the `::` operator to tell Luau what type something should be. For example, consider the following table constructor where the intent is to store a table of names: Inserting a number into `names` ought to cause a type error, but doesn’t. In order to specify the type of the `names` table, we can use a typecast: Now, inserting a number raises a type error, informing the user that there is an `invalid 'number' to 'string' conversion`. ### Type cast rules Type casts themselves are also type checked to ensure that one of the conversion operands is the subtype of the other or `any`: This prevents unsafe casts between incompatible types. #### Type casts with multiple return values When typecasting a variadic or the result of a function with multiple returns, only the first value will be preserved, and the rest discarded:
827
57b422bda0f687bb32b8bd6034a6220713097fc240b89a43f77b5fd6a64d169b
https://luau.org/types/considerations
https://luau.org/
2026-03-29T11:32:11.317612+00:00
# Additional Considerations ## Module interactions Let’s say that we have two modules, `Foo` and `Bar`. Luau will try to resolve the paths if it can find any `require` in any scripts. In this case, when you say `./bar`, Luau will resolve it as: relative to this script, go to my sibling script named Bar. There are some caveats here though. For instance, the require path must be resolvable statically, otherwise Luau cannot accurately type check it. ### Cyclic module dependencies Cyclic module dependencies can cause problems for the type checker. In order to break a module dependency cycle a typecast of the module to `any` may be used:
145
baef40ddd1f529bac9c0efda866830e806d4d5d0d37ef2aead7aae5ab730a952
https://luau.org/types/object-oriented-programs
https://luau.org/
2026-03-29T11:32:11.386879+00:00
# Object-Oriented Programming ## Adding types for faux object oriented programs One common pattern we see with existing Lua/Luau code is the following object-oriented code. While Luau is capable of inferring a decent chunk of this code, it cannot pin down on the types of `self` when it spans multiple methods. For example, the type of `Account.new` is `<a, b>(name: a, balance: b) -> { ..., name: a, balance: b, ... }` (snipping out the metatable). For better or worse, this means you are allowed to call `Account.new(5, "hello")` as well as `Account.new({}, {})`. In this case, this is quite unfortunate, so your first attempt may be to add type annotations to the parameters `name` and `balance`. There’s the next problem: the type of `self` is not shared across methods of `Account`, this is because you are allowed to explicitly opt for a different value to pass as `self` by writing `account.deposit(another_account, 50)`. As a result, the type of `Account:deposit` is `<a, b>(self: { balance: a }, credit: b) -> ()`. Consequently, Luau cannot infer the result of the `+` operation from `a` and `b`, so a type error is reported. We can see there’s a lot of problems happening here. This is a case where you’ll have to provide some guidance to Luau in the form of annotations today, but the process is straightforward and without repetition. You first specify the type of *data* you want your class to have, and then you define the class type separately with `setmetatable` (either via `typeof`, or in the New Type Solver, the `setmetatable` type function). From then on, you can explicitly annotate the `self` type of each method with your class type! Note that while the definition is written e.g. `Account.deposit`, you can still call it as `account:deposit(...)`. Based on feedback, we plan to restrict the types of all functions defined with `:` syntax to [share their self types](https://rfcs.luau.org/shared-self-types.html). This will enable future versions of this code to work without any explicit `self` annotations because it amounts to having type inference make precisely the assumptions we are encoding with annotations here --- namely, that the type of the constructors and the method definitions is intended by the developer to be the same.
524
d969ee68fb99f84f9a6594ba9010fdceb2e8b2a912546bb7b59b77599ea38c1e
https://luau.org/grammar
https://luau.org/
2026-03-29T11:32:11.403721+00:00
# Syntax Grammar This is the complete syntax grammar for Luau in EBNF. More information about the terminal nodes STRING and NUMBER is available in the [syntax section](../syntax).
39
319521766722a45709bd0fda051e44ff6b0cced4b4ed7bf25ac799bf72b4c840
https://luau.org/types-library
https://luau.org/
2026-03-29T11:32:11.451467+00:00
# Type Function Library The `types` library is used to create and transform types, and can only be used within [type functions](../types/type-functions). ### `types` library properties The [any](../types/basic-types#any-type) `type`. The [unknown](../types/basic-types#unknown-type) `type`. The [never](../types/basic-types#never-type) `type`. The boolean `type`. The [buffer](../library#buffer-library) `type`. The number `type`. The string `type`. The thread `type`. ## `types` library functions Returns the [singleton](../types/basic-types#singleton-types-aka-literal-types) type of the argument. Returns an immutable negation of the argument type. Returns a version of the given type that is now optional. - If the given type is a [union type](../types/unions-and-intersections#union-types), `nil` will be added unconditionally as a component. - Otherwise, the result will be a union of the given type and the `nil` type. Returns an immutable [union](../types/unions-and-intersections#union-types) of two or more arguments. Returns an immutable [intersection](../types/unions-and-intersections#intersection-types) of two or more arguments. Returns a fresh, mutable table `type`. Property keys must be string singleton `type`s. The table’s metatable is set if one is provided. Returns a fresh, mutable function `type`, using the ordered parameters of `head` and the variadic tail of `tail`. Returns a deep copy of the argument type. Creates a [generic](../types/generics#generic-functions) named `name`. If `ispack` is `true`, the result is a [generic pack](../types/basic-types#type-packs). ### `type` instance `type` instances can have extra properties and methods described in subsections depending on its tag. An immutable property holding the type’s tag. Overrides the `==` operator to return `true` if `self` is syntactically equal to `arg`. This excludes semantically equivalent types, `true | false` is unequal to `boolean`. Returns `true` if `self` has the argument as its tag. ### Singleton `type` instance Returns the singleton’s actual value, like `true` for `types.singleton(true)`. ### Generic `type` instance Returns the name of the [generic](../types/generics#generic-functions) or `nil` if it has no name. Returns `true` if the [generic](../types/generics#generic-functions) is a [pack](../types/basic-types#type-packs), or `false` otherwise. ### Table `type` instance Sets the type of the property for the given `key`, using the same type for both reading from and writing to the table. - `key` is expected to be a string singleton type, naming the property. - `value` will be set as both the `read type` and `write type` of the property. - If `value` is `nil`, the property is removed. Sets the type for reading from the property named by `key`, leaving the type for writing this property as-is. - `key` is expected to be a string singleton type, naming the property. - `value` will be set as the `read type`, the `write type` will be unchanged. - If `key` is not already present, only a `read type` will be set, making the property read-only. - If `value` is `nil`, the property is removed. Sets the type for writing to the property named by `key`, leaving the type for reading this property as-is. - `key` is expected to be a string singleton type, naming the property. - `value` will be set as the `write type`, the `read type` will be unchanged. - If `key` is not already present, only a `write type` will be set, making the property write-only. - If `value` is `nil`, the property is removed. Returns the type used for reading values from this property, or `nil` if the property doesn’t exist. Returns the type used for writing values to this property, or `nil` if the property doesn’t exist. Returns a table mapping property keys to their read and write types. Sets the table’s indexer, using the same type for reads and writes. Sets the type resulting from reading from this table via indexing. Sets the type for writing to this table via indexing. Returns the table’s indexer as a table, or `nil` if it doesn’t exist. Returns the table’s indexer using the result’s read type, or `nil` if it doesn’t exist. Returns the table’s indexer using the result’s write type, or `nil` if it doesn’t exist. Sets the table’s metatable. Gets the table’s metatable, or `nil` if it doesn’t exist. ### Function `type` instance Sets the function’s parameters, with the ordered parameters in `head` and the variadic tail in `tail`. Returns the function’s parameters, with the ordered parameters in `head` and the variadic tail in `tail`. Sets the function’s return types, with the ordered parameters in `head` and the variadic tail in `tail`. Returns the function’s return types, with the ordered parameters in `head` and the variadic tail in `tail`. Returns an array of the function’s [generic](../types/generics#generic-functions) `type`s. Sets the function’s [generic](../types/generics#generic-functions) `type`s. ### Negation `type` instance Returns the `type` being negated. ### Union `type` instance Returns an array of the [unioned](../types/unions-and-intersections#union-types) types. ### Intersection `type` instance Returns an array of the [intersected](../types/unions-and-intersections#intersection-types) types. ### Class `type` instance Returns the properties of the class with their respective `read` and `write` types. Returns the type of reading this class’ parent, or returns `nil` if the parent class doesn’t exist. Returns the type for writing to this class’ parent, or returns `nil` if the parent class doesn’t exist. Returns the class’ metatable, or `nil` if it doesn’t exist. Returns the class’ indexer, or `nil` if it doesn’t exist. Returns result type of reading from the class via indexing, or `nil` if it doesn’t exist. Returns the type for writing to the class via indexing, or `nil` if it doesn’t exist.
1,407
ba5338fe3ffdeb2169bbde778203988d908cf8b2809ac092b6b75fc1c0c0aa66
https://luau.org/types/roblox-types
https://luau.org/
2026-03-29T11:32:11.479596+00:00
# Foreign Types from the Embedder Roblox supports a rich set of classes and data types, [documented here](https://developer.roblox.com/en-us/api-reference). All of them are readily available for the type checker to use by their name (e.g. `Part` or `RaycastResult`). When one type inherits from another type, the type checker models this relationship and allows to cast a subclass to the parent class implicitly, so you can pass a `Part` to a function that expects an `Instance`. All enums are also available to use by their name as part of the `Enum` type library, e.g. `local m: Enum.Material = part.Material`. We can automatically deduce what calls like `Instance.new` and `game:GetService` are supposed to return: Finally, Roblox types can be refined using `IsA`: Note that many of these types provide some properties and methods in both lowerCase and UpperCase; the lowerCase variants are deprecated, and the type system will ask you to use the UpperCase variants instead.
220
f556a7d92df211cd4145756786b970639855e69654ec486067e71856ba0f700e
https://luau.org/library
https://luau.org/
2026-03-29T11:32:11.574184+00:00
# Standard Library Luau comes equipped with a standard library of functions designed to manipulate the built-in data types. Note that the library is relatively minimal and doesn’t expose ways for scripts to interact with the host environment - it’s expected that embedding applications provide extra functionality on top of this and limit or sandbox the system access appropriately, if necessary. For example, Roblox provides [a rich API to interact with the 3D environment and limited APIs to interact with external services](https://developer.roblox.com/en-us/api-reference). This page documents the available builtin libraries and functions. All of these are accessible by default by any script, assuming the host environment exposes them (which is usually a safe assumption outside of extremely constrained environments). ## Global functions While most library functions are provided as part of a library like `table`, a few global functions are exposed without extra namespacing. `assert` checks if the value is truthy; if it’s not (which means it’s `false` or `nil`), it raises an error. The error message can be customized with an optional parameter. Upon success the function returns the `value` argument. `error` raises an error with the specified object. Note that errors don’t have to be strings, although they often are by convention; various error handling mechanisms like `pcall` preserve the error type. When `level` is specified, the error raised is turned into a string that contains call frame information for the caller at level `level`, where `1` refers to the function that called `error`. This can be useful to attribute the errors to callers, for example `error("Expected a valid object", 2)` highlights the caller of the function that called `error` instead of the function itself in the callstack. `gcinfo` returns the total heap size in kilobytes, which includes bytecode objects, global tables as well as the script-allocated objects. Note that Luau uses an incremental garbage collector, and as such at any given point in time the heap may contain both reachable and unreachable objects. The number returned by `gcinfo` reflects the current heap consumption from the operating system perspective and can fluctuate over time as garbage collector frees objects. Returns the environment table for target function; when `target` is not a function, it must be a number corresponding to the caller stack index, where 1 means the function that calls `getfenv`, and the environment table is returned for the corresponding function from the call stack. When `target` is omitted it defaults to `1`, so `getfenv()` returns the environment table for the calling function. Returns the metatable for the specified object; when object is not a table or a userdata, the returned metatable is shared between all objects of the same type. Note that when metatable is protected (has a `__metatable` key), the value corresponding to that key is returned instead and may not be a table. Given the table `t`, returns the next key-value pair after `i` in the table traversal order, or nothing if `i` is the last key. When `i` is `nil`, returns the first key-value pair instead. Creates a new untyped userdata object; when `mt` is true, the new object has an empty metatable that can be modified using `getmetatable`. Prints all arguments to the standard output, using Tab as a separator. Returns true iff `a` and `b` have the same type and point to the same object (for garbage collected types) or are equal (for value types). Performs a table lookup with index `k` and returns the resulting value, if present in the table, or nil. This operation bypasses metatables/`__index`. Returns the raw length of the table or string. If it is a string, this operation is identical to `#str` or `string.len(str)`. This operation bypasses metatables/`__len`. Assigns table field `k` to the value `v`. This operation bypasses metatables/`__newindex`. When called with `'#'` as the first argument, returns the number of remaining parameters passed. Otherwise, returns the subset of parameters starting with the specified index. Index can be specified from the start of the arguments (using 1 as the first argument), or from the end (using -1 as the last argument). Changes the environment table for target function to `env`; when `target` is not a function, it must be a number corresponding to the caller stack index, where 1 means the function that calls `setfenv`, and the environment table is returned for the corresponding function from the call stack. Changes metatable for the given table. Note that unlike `getmetatable`, this function only works on tables. If the table already has a protected metatable (has a `__metatable` field), this function errors. Converts the input string to the number in base `base` (default 10) and returns the resulting number. If the conversion fails (that is, if the input string doesn’t represent a valid number in the specified base), returns `nil` instead. 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. Returns the type of the object, which is one of `"nil"`, `"boolean"`, `"number"`, `"vector"`, `"string"`, `"table"`, `"function"`, `"userdata"`, `"thread"`, or `"buffer"`. Returns the type of the object; for userdata objects that have a metatable with the `__type` field *and* are defined by the host (not `newproxy`), returns the value for that key. For custom userdata objects, such as ones returned by `newproxy`, this function returns `"userdata"` to make sure host-defined types can not be spoofed. Returns the triple (generator, state, nil) that can be used to traverse the table using a `for` loop. The traversal results in key-value pairs for the numeric portion of the table; key starts from 1 and increases by 1 on each iteration. The traversal terminates when reaching the first `nil` value (so `ipairs` can’t be used to traverse array-like tables with holes). Returns the triple (generator, state, nil) that can be used to traverse the table using a `for` loop. The traversal results in key-value pairs for all keys in the table, numeric and otherwise, but doesn’t have a defined order. Calls function `f` with parameters `args`. If the function succeeds, returns `true` followed by all return values of `f`. If the function raises an error, returns `false` followed by the error object. Note that `f` can yield, which results in the entire coroutine yielding as well. Calls function `f` with parameters `args`. If the function succeeds, returns `true` followed by all return values of `f`. If the function raises an error, calls `e` with the error object as an argument, and returns `false` followed by the first return value of `e`. Note that `f` can yield, which results in the entire coroutine yielding as well. `e` can neither yield nor error - if it does raise an error, `xpcall` returns with `false` followed by a special error message. Returns all values of `a` with indices in `[f..t]` range. `f` defaults to 1 and `t` defaults to `#a`. Note that this is equivalent to `table.unpack`. ## math library Returns the absolute value of `n`. Returns NaN if the input is NaN. Returns the arc cosine of `n`, expressed in radians. Returns a value in `[0, pi]` range. Returns NaN if the input is not in `[-1, +1]` range. Returns the arc sine of `n`, expressed in radians. Returns a value in `[-pi/2, +pi/2]` range. Returns NaN if the input is not in `[-1, +1]` range. Returns the arc tangent of `y/x`, expressed in radians. The function takes into account the sign of both arguments in order to determine the quadrant. Returns a value in `[-pi, pi]` range. Returns the arc tangent of `n`, expressed in radians. Returns a value in `[-pi/2, pi-2]` range. Rounds `n` upwards to the next integer boundary. Returns the hyperbolic cosine of `n`. Returns the cosine of `n`, which is an angle in radians. Returns a value in `[0, 1]` range. Converts `n` from radians to degrees and returns the result. Returns the base-e exponent of `n`, that is `e^n`. Rounds `n` downwards to previous integer boundary. Returns the remainder of `x` modulo `y`, rounded towards zero. Returns NaN if `y` is zero. Splits the number into a significand (a number in `[-1, +1]` range) and binary exponent such that `n = s * 2^e`, and returns `s, e`. Given the significand and a binary exponent, returns a number `s * 2^e`. Linearly interpolated between number value `a` and `b` using factor `t`, generally returning the result of `a + (b - a) * t`. When `t` is exactly `1`, the value of `b` will be returned instead to ensure that when `t` is on the interval `[0, 1]`, the result of `lerp` will be on the interval `[a, b]`. Returns a value that represents `x` mapped linearly from the input range (`inmin` to `inmax`) to the output range (`outmin` to `outmax`). Returns base-10 logarithm of the input number. Returns NaN if the input is negative, and negative infinity if the input is 0. Equivalent to `math.log(n, 10)`. Returns logarithm of the input number in the specified base; base defaults to `e`. Returns NaN if the input is negative, and negative infinity if the input is 0. Returns the maximum number of the input arguments. The function requires at least one input and will error if zero parameters are passed. If one of the inputs is a NaN, the result may or may not be a NaN. Returns the minimum number of the input arguments. The function requires at least one input and will error if zero parameters are passed. If one of the inputs is a NaN, the result may or may not be a NaN. Returns the integer and fractional part of the input number. Both the integer and fractional part have the same sign as the input number, e.g. `math.modf(-1.5)` returns `-1, -0.5`. Returns `x` raised to the power of `y`. Converts `n` from degrees to radians and returns the result. Returns a random number using the global random number generator. A zero-argument version returns a number in `[0, 1]` range. A one-argument version returns a number in `[1, n]` range. A two-argument version returns a number in `[min, max]` range. The input arguments are truncated to integers, so `math.random(1.5)` always returns 1. Reseeds the global random number generator; subsequent calls to `math.random` will generate a deterministic sequence of numbers that only depends on `seed`. Returns a hyperbolic sine of `n`. Returns the sine of `n`, which is an angle in radians. Returns a value in `[0, 1]` range. Returns the square root of `n`. Returns NaN if the input is negative. Returns the hyperbolic tangent of `n`. Returns the tangent of `n`, which is an angle in radians. Returns 3D Perlin noise value for the point `(x, y, z)` (`y` and `z` default to zero if absent). Returns a value in `[-1, 1]` range. Returns `n` if the number is in `[min, max]` range; otherwise, returns `min` when `n < min`, and `max` otherwise. If `n` is NaN, may or may not return NaN. The function errors if `min > max`. Returns `-1` if `n` is negative, `1` if `n` is positive, and `0` if `n` is zero or NaN. Rounds `n` to the nearest integer boundary. If `n` is exactly halfway between two integers, rounds `n` away from 0. ## table library Concatenate all elements of `a` with indices in range `[f..t]` together, using `sep` as a separator if present. `f` defaults to 1 and `t` defaults to `#a`. Iterates over all elements of the table in unspecified order; for each key-value pair, calls `f` and returns the result of `f` if it’s non-nil. If all invocations of `f` returned `nil`, returns no values. This function has been deprecated and is not recommended for use in new code; use `for` loop instead. Iterates over numeric keys of the table in `[1..#t]` range in order; for each key-value pair, calls `f` and returns the result of `f` if it’s non-nil. If all invocations of `f` returned `nil`, returns no values. This function has been deprecated and is not recommended for use in new code; use `for` loop instead. Returns the length of table `t`. This function has been deprecated and is not recommended for use in new code; use `#t` instead. Returns the maximum numeric key of table `t`, or zero if the table doesn’t have numeric keys. When using a two-argument version, appends the value to the array portion of the table (equivalent to `t[#t+1] = v`). When using a three-argument version, inserts the value at index `i` and shifts values at indices after that by 1. `i` should be in `[1..#t]` range. Removes element `i` from the table and shifts values at indices after that by 1. If `i` is not specified, removes the last element of the table. `i` should be in `[1..#t]` range. Returns the value of the removed element, or `nil` if no element was removed (e.g. table was empty). Sorts the table `t` in ascending order, using `f` as a comparison predicate: `f` should return `true` iff the first parameter should be before the second parameter in the resulting table. When `f` is not specified, builtin less-than comparison is used instead. The comparison predicate must establish a strict weak ordering - sort results are undefined otherwise. Returns a table that consists of all input arguments as array elements, and `n` field that is set to the number of inputs. 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)` Copies elements in range `[f..t]` from table `a` to table `tt` if specified and `a` otherwise, starting from the index `d`. 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. 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. Removes all elements from the table while preserving the table capacity, so future assignments don’t need to reallocate space. Given a non-frozen table, freezes it such that all subsequent attempts to modify the table or assign its metatable raise an error. If the input table is already frozen or has a protected metatable, the function raises an error; otherwise it returns the input table. Note that the table is frozen in-place and is not being copied. Additionally, only `t` is frozen, and keys/values/metatable of `t` don’t change their state and need to be frozen separately if desired. Returns `true` iff the input table is frozen. Returns a copy of the input table that has the same metatable, same keys and values, and is not frozen even if `t` was. The copy is shallow: implementing a deep recursive copy automatically is challenging, and often only certain keys need to be cloned recursively which can be done after the initial clone by modifying the resulting table. ## string library Returns the numeric code of every byte in the input string with indices in range `[f..t]`. `f` defaults to 1 and `t` defaults to `f`, so a two-argument version of this function returns a single number. If the function is called with a single argument and the argument is out of range, the function returns no values. Returns the string that contains a byte for every input number; all inputs must be integers in `[0..255]` range. Tries to find an instance of pattern `p` in the string `s`, starting from position `init` (defaults to 1). When `plain` is true, the search is using raw (case-sensitive) string equality, otherwise `p` should be a [string pattern](https://www.lua.org/manual/5.3/manual.html#6.4.1). If a match is found, returns the position of the match and the length of the match, followed by the pattern captures; otherwise returns `nil`. Returns a formatted version of the input arguments using a [printf-style format string](https://en.cppreference.com/w/c/io/fprintf) `s`. The following format characters are supported: - `c`: expects an integer number and produces a character with the corresponding character code - `d`, `i`, `u`: expects an integer number and produces the decimal representation of that number - `o`: expects an integer number and produces the octal representation of that number - `x`, `X`: expects an integer number and produces the hexadecimal representation of that number, using lower case or upper case hexadecimal characters - `e`, `E`, `f`, `g`, `G`: expects a number and produces the floating point representation of that number, using scientific or decimal representation - `q`: expects a string and produces the same string quoted using double quotation marks, with escaped special characters if necessary - `s`: expects a string and produces the same string verbatim The formats support modifiers `-`, `+`, space, `#` and `0`, as well as field width and precision modifiers - with the exception of `*`. Produces an iterator function that, when called repeatedly explicitly or via `for` loop, produces matches of string `s` with [string pattern](https://www.lua.org/manual/5.3/manual.html#6.4.1) `p`. For every match, the captures within the pattern are returned if present (if a pattern has no captures, the entire matching substring is returned instead). For every match of [string pattern](https://www.lua.org/manual/5.3/manual.html#6.4.1) `p` in `s`, replace the match according to `f`. The substitutions stop after the limit of `maxs`, and the function returns the resulting string followed by the number of substitutions. When `f` is a string, the substitution uses the string as a replacement. When `f` is a table, the substitution uses the table element with key corresponding to the first pattern capture, if present, and entire match otherwise. Finally, when `f` is a function, the substitution uses the result of calling `f` with call pattern captures, or entire matching substring if no captures are present. Returns the number of bytes in the string (equivalent to `#s`). Returns a string where each byte corresponds to the lower-case ASCII version of the input byte in the source string. Tries to find an instance of pattern `p` in the string `s`, starting from position `init` (defaults to 1). `p` should be a [string pattern](https://www.lua.org/manual/5.3/manual.html#6.4.1). If a match is found, returns all pattern captures, or entire matching substring if no captures are present, otherwise returns `nil`. Returns the input string `s` repeated `n` times. Returns an empty string if `n` is zero or negative. Returns the string with the order of bytes reversed compared to the original. Note that this only works if the input is a binary or ASCII string. 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. Returns a string where each byte corresponds to the upper-case ASCII version of the input byte in the source string. Splits the input string using `sep` as a separator (defaults to `","`) and returns the resulting substrings. If separator is empty, the input string is split into separate one-byte strings. Given a [pack format string](https://www.lua.org/manual/5.3/manual.html#6.4.2), encodes all input parameters according to the packing format and returns the resulting string. Note that Luau uses fixed sizes for all types that have platform-dependent size in Lua 5.x: short is 16 bit, long is 64 bit, integer is 32-bit and size\_t is 32 bit for the purpose of string packing. Given a [pack format string](https://www.lua.org/manual/5.3/manual.html#6.4.2), returns the size of the resulting packed representation. The pack format can’t use variable-length format specifiers. Note that Luau uses fixed sizes for all types that have platform-dependent size in Lua 5.x: short is 16 bit, long is 64 bit, integer is 32-bit and size\_t is 32 bit for the purpose of string packing. Given a [pack format string](https://www.lua.org/manual/5.3/manual.html#6.4.2), decodes the input string according to the packing format and returns all resulting values. Note that Luau uses fixed sizes for all types that have platform-dependent size in Lua 5.x: short is 16 bit, long is 64 bit, integer is 32-bit and size\_t is 32 bit for the purpose of string packing. ## coroutine library Returns a new coroutine that, when resumed, will run function `f`. Returns the currently running coroutine, or `nil` if the code is running in the main coroutine (depending on the host environment setup, main coroutine may never be used for running code). Returns the status of the coroutine, which can be `"running"`, `"suspended"`, `"normal"` or `"dead"`. Dead coroutines have finished their execution and can not be resumed, but their state can still be inspected as they are not dead from the garbage collector point of view. Creates a new coroutine and returns a function that, when called, resumes the coroutine and passes all arguments along to the suspension point. When the coroutine yields or finishes, the wrapped function returns with all values returned at the suspension point. Yields the currently running coroutine and passes all arguments along to the code that resumed the coroutine. The coroutine becomes suspended; when the coroutine is resumed again, the resumption arguments will be forwarded to `yield` which will behave as if it returned all of them. Returns `true` iff the currently running coroutine can yield. Yielding is prohibited when running inside metamethods like `__index` or C functions like `table.foreach` callback, with the exception of `pcall`/`xpcall`. Resumes the coroutine and passes the arguments along to the suspension point. When the coroutine yields or finishes, returns `true` and all values returned at the suspension point. If an error is raised during coroutine resumption, this function returns `false` and the error object, similarly to `pcall`. Closes the coroutine which puts coroutine in the dead state. The coroutine must be dead or suspended - in particular it can’t be currently running. If the coroutine that’s being closed was in an error state, returns `false` along with an error object; otherwise returns `true`. After closing, the coroutine can’t be resumed and the coroutine stack becomes empty. ## bit32 library All functions in the `bit32` library treat input numbers as 32-bit unsigned integers in `[0..4294967295]` range. The bit positions start at 0 where 0 corresponds to the least significant bit. Shifts `n` by `i` bits to the right (if `i` is negative, a left shift is performed instead). The most significant bit of `n` is propagated during the shift. When `i` is larger than 31, returns an integer with all bits set to the sign bit of `n`. When `i` is smaller than `-31`, 0 is returned. Performs a bitwise `and` of all input numbers and returns the result. If the function is called with no arguments, an integer with all bits set to 1 is returned. Returns a bitwise negation of the input number. Performs a bitwise `or` of all input numbers and returns the result. If the function is called with no arguments, zero is returned. Performs a bitwise `xor` (exclusive or) of all input numbers and returns the result. If the function is called with no arguments, zero is returned. Perform a bitwise `and` of all input numbers, and return `true` iff the result is not 0. If the function is called with no arguments, `true` is returned. 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. Rotates `n` to the left by `i` bits (if `i` is negative, a right rotate is performed instead); the bits that are shifted past the bit width are shifted back from the right. Shifts `n` to the left by `i` bits (if `i` is negative, a right shift is performed instead). When `i` is outside of `[-31..31]` range, returns 0. Replaces bits of `n` at position `f` and width `w` with `r`, and returns the resulting integer. `w` defaults to `1`, so a three-argument version of `replace` changes one bit at position `f` to `r` (which should be 0 or 1) and returns the result. Bits are indexed starting at 0. Errors if `f` and `f+w-1` are not between 0 and 31. Rotates `n` to the right by `i` bits (if `i` is negative, a left rotate is performed instead); the bits that are shifted past the bit width are shifted back from the left. Shifts `n` to the right by `i` bits (if `i` is negative, a left shift is performed instead). When `i` is outside of `[-31..31]` range, returns 0. Returns the number of consecutive zero bits in the 32-bit representation of `n` starting from the left-most (most significant) bit. Returns 32 if `n` is zero. Returns the number of consecutive zero bits in the 32-bit representation of `n` starting from the right-most (least significant) bit. Returns 32 if `n` is zero. Returns `n` with the order of the bytes swapped. ## utf8 library Strings in Luau can contain arbitrary bytes; however, in many applications strings representing text contain UTF8 encoded data by convention, that can be inspected and manipulated using `utf8` library. Returns the byte offset of the Unicode codepoint number `n` in the string, starting from the byte position `i`. When the character is not found, returns `nil` instead. Returns a number for each Unicode codepoint in the string with the starting byte offset in `[i..j]` range. `i` defaults to 1 and `j` defaults to `i`, so a two-argument version of this function returns the Unicode codepoint that starts at byte offset `i`. Creates a string by concatenating Unicode codepoints for each input number. Returns the number of Unicode codepoints with the starting byte offset in `[i..j]` range, or `nil` followed by the first invalid byte position if the input string is malformed. `i` defaults to 1 and `j` defaults to `#s`, so `utf8.len(s)` returns the number of Unicode codepoints in string `s` or `nil` if the string is malformed. Returns an iterator that, when used in `for` loop, produces the byte offset and the codepoint for each Unicode codepoints that `s` consists of. ## os library Returns a high-precision timestamp (in seconds) that doesn’t have a defined baseline, but can be used to measure duration with sub-microsecond precision. Returns the table or string representation of the time specified as `t` (defaults to current time) according to `s` format string. When `s` starts with `!`, the result uses UTC, otherwise it uses the current timezone. If `s` is equal to `*t` (or `!*t`), a table representation of the date is returned, with keys `sec`/`min`/`hour` for the time (using 24-hour clock), `day`/`month`/`year` for the date, `wday` for week day (1..7), `yday` for year day (1..366) and `isdst` indicating whether the timezone is currently using daylight savings. Otherwise, `s` is interpreted as a [date format string](https://www.cplusplus.com/reference/ctime/strftime/), with the valid specifiers including any of `aAbBcdHIjmMpSUwWxXyYzZ` or `%`. `s` defaults to `"%c"` so `os.date()` returns the human-readable representation of the current date in local timezone. Calculates the difference in seconds between `a` and `b`; provided for compatibility only. Please use `a - b` instead. When called without arguments, returns the current date/time as a Unix timestamp. When called with an argument, expects it to be a table that contains `sec`/`min`/`hour`/`day`/`month`/`year` keys and returns the Unix timestamp of the specified date/time in UTC. ## debug library Given a stack frame or a function, and a string that specifies the requested information, returns the information about the stack frame or function. Each character of `s` results in additional values being returned in the same order as the characters appear in the string: - `s` returns source path for the function - `l` returns the line number for the stack frame or the line where the function is defined when inspecting a function object - `n` returns the name of the function, or an empty string if the name is not known - `f` returns the function object itself - `a` returns the number of arguments that the function expects followed by a boolean indicating whether the function is variadic or not For example, `debug.info(2, "sln")` returns source file, current line and function name for the caller of the current function. Produces a stringified callstack of the given thread, or the current thread, starting with level `level`. If `msg` is specified, then the resulting callstack includes the string before the callstack output, separated with a newline. The format of the callstack is human-readable and subject to change. ## buffer library Buffer is an object that represents a fixed-size mutable block of memory. All operations on a buffer are provided using the ‘buffer’ library functions. Many of the functions accept an offset in bytes from the start of the buffer. Offset of 0 from the start of the buffer memory block accesses the first byte. All offsets, counts and sizes should be non-negative integer numbers. If the bytes that are accessed by any read or write operation are outside the buffer memory, an error is thrown. Creates a buffer of the requested size with all bytes initialized to 0. Size limit is 1GB or 1,073,741,824 bytes. Creates a buffer initialized to the contents of the string. The size of the buffer equals to the length of the string. Returns the buffer data as a string. Returns the size of the buffer in bytes. Used to read the data from the buffer by reinterpreting bytes at the offset as the type in the argument and converting it into a number. Available types: | Function | Type | Range | | --- | --- | --- | | readi8 | signed 8-bit integer | [-128, 127] | | readu8 | unsigned 8-bit integer | [0, 255] | | readi16 | signed 16-bit integer | [-32,768, 32,767] | | readu16 | unsigned 16-bit integer | [0, 65,535] | | readi32 | signed 32-bit integer | [-2,147,483,648, 2,147,483,647] | | readu32 | unsigned 32-bit integer | [0, 4,294,967,295] | | readf32 | 32-bit floating-point number | Single-precision IEEE 754 number | | readf64 | 64-bit floating-point number | Double-precision IEEE 754 number | Floating-point numbers are read and written using a format specified by IEEE 754. If a floating-point value matches any of bit patterns that represent a NaN (not a number), returned value might be converted to a different quiet NaN representation. Read and write operations use the little endian byte order. Integer numbers are read and written using two’s complement representation. Used to write data to the buffer by converting the number into the type in the argument and reinterpreting it as individual bytes. Ranges of acceptable values can be seen in the table above. When writing integers, the number is converted using `bit32` library rules. Values that are out-of-range will take less significant bits of the full number. For example, writing 43,981 (0xabcd) using writei8 function will take 0xcd and interpret it as an 8-bit signed number -51. It is still recommended to keep all numbers in range of the target type. Results of converting special number values (inf/nan) to integers are platform-specific. Used to read a string of length ‘count’ from the buffer at specified offset. Used to write data from a string into the buffer at a specified offset. If an optional ‘count’ is specified, only ‘count’ bytes are taken from the string. Count cannot be larger than the string length. Used to read a range of `bitCount` bits from the buffer, at specified offset `bitOffset`, into an unsigned integer. `bitCount` must be in `[0, 32]` range. Used to write `bitCount` bits from `value` into the buffer at specified offset `bitOffset`. `bitCount` must be in `[0, 32]` range. Copy ‘count’ bytes from ‘source’ starting at offset ‘sourceOffset’ into the ‘target’ at ‘targetOffset’. It is possible for ‘source’ and ‘target’ to be the same. Copying an overlapping region inside the same buffer acts as if the source region is copied into a temporary buffer and then that buffer is copied over to the target. If ‘sourceOffset’ is nil or is omitted, it defaults to 0. If ‘count’ is ‘nil’ or is omitted, the whole ‘source’ data starting from ‘sourceOffset’ is copied. Sets the ‘count’ bytes in the buffer starting at the specified ‘offset’ to the ‘value’. If ‘count’ is ‘nil’ or is omitted, all bytes from the specified offset until the end of the buffer are set. ## vector library This library implements functionality for the vector type in addition to the built-in primitive operator support. Default configuration uses vectors with 3 components (`x`, `y`, and `z`). If the *4-wide mode* is enabled by setting the `LUA_VECTOR_SIZE` VM configuration to 4, vectors get an additional `w` component. Individual vector components can be accessed using the fields `x` or `X`, `y` or `Y`, `z` or `Z`, and `w` or `W` in 4-wide mode. Since vector values are immutable, writes to individual components are not supported. Constant vectors with all components set to 0 and 1 respectively. Includes the fourth component in *4-wide mode*. Creates a new vector with the given component values. The first constructor sets the fourth (`w`) component to 0.0 in *4-wide mode*. Calculates the magnitude of a given vector. Includes the fourth component in *4-wide mode*. Computes the normalized version (unit vector) of a given vector. Includes the fourth component in *4-wide mode*. Computes the cross product of two vectors. Ignores the fourth component in *4-wide mode* and returns the 3-dimensional cross product. Computes the dot product of two vectors. Includes the fourth component in *4-wide mode*. Computes the angle between two vectors in radians. The axis, if specified, is used to determine the sign of the angle. Ignores the fourth component in *4-wide mode* and returns the 3-dimensional angle. Applies `math.floor` to every component of the input vector. Includes the fourth component in *4-wide mode*. Applies `math.ceil` to every component of the input vector. Includes the fourth component in *4-wide mode*. Applies `math.abs` to every component of the input vector. Includes the fourth component in *4-wide mode*. Applies `math.sign` to every component of the input vector. Includes the fourth component in *4-wide mode*. Applies `math.clamp` to every component of the input vector. Includes the fourth component in *4-wide mode*. Applies `math.max` to the corresponding components of the input vectors. Includes the fourth component in *4-wide mode*. Equivalent to `vector.create(math.max((...).x), math.max((...).y), math.max((...).z), math.max((...).w))`. Applies `math.min` to the corresponding components of the input vectors. Includes the fourth component in *4-wide mode*. Equivalent to `vector.create(math.min((...).x), math.min((...).y), math.min((...).z), math.min((...).w))`.
8,408
6aef50d03ccf4727b75c3900e932bf47ea2b02b14028107c09ae3781c6790ef7
https://luau.org/news/2024-07-23-luau-recap-july-2024
https://luau.org/
2026-03-29T11:32:14.064941+00:00
# Recap: July 2024 July 23, 2024 Hello everyone! While the Luau team is actively working on a big rewrite of the type inference and type checking engines (more news about that in the near future), we wanted to go over other changes and updates since our last recap back in October. ## Official Luau mascot Luau has recently adopted a Hawaiian monk seal mascot named Hina, after the Hawaiian goddess of the moon. Please welcome Hina the Seal! ![Hina the Seal](/_astro/mascot.iwZjauS8_Z1W5x4L.webp) ## Native Code Generation We are happy to announce that the native code feature is out from the ‘Preview’ state and is fully supported for X64 (Intel/AMD) or A64 (ARM) processor architectures. As a refresher, native code generation is the feature that allows Luau scripts that have been previously executed by interpreting bytecode inside the Luau VM to instead compile to machine code that the CPU understands and executes directly. Since the release of the Preview, we have worked on improving code performance, memory use of the system, correctness and stability. Some highlights: - Improved performance of the [bit32 library](https://luau-lang.org/library#bit32-library) functions - Improved performance of numerical loops - Optimized table array and property lookups - Added native support for new [buffer type](https://luau-lang.org/library#buffer-library) operations - Code optimizations based on knowing which types are returned from operations - Code optimizations based on function argument type annotations - This includes support for [SIMD operations](https://en.wikipedia.org/wiki/Single_instruction,_multiple_data) for annotated vector arguments There are many other small improvements in generated code performance and size and we have plans for additional optimizations. ### Native function attribute For a better control of what code runs natively, we have introduced new syntax for function attributes: This is the first attribute to become available and we are working on the ability to mark functions as deprecated using the `@deprecated` attribute. More on that [here](https://github.com/luau-lang/rfcs/blob/2335ab6db9353223fad0065294d15fdcd127c4ea/docs/syntax-attribute-functions-deprecated.md). ### Type information for runtime optimizations Native code generation works on any code without having to modify it. In certain situations, this means that the native compiler cannot be sure about the types involved in the operation. Consider a simple function, working on a few values: Native compiler assumes that operations are most likely being performed on numbers and generates the appropriate fast path. But what if the function is actually called with a vector type? To handle this, a slower path was generated to handle any other potential type of the argument. Because this path is not chosen as the first possible option, extra checking overhead prevents code from running as fast as it can. When we announced the last update, we had already added some support for following the types used as arguments. > ***NOTE:*** `vector` type is not enabled by default, check out `defaultOptions` and `setupVectorHelpers` functions in `Conformance.test.cpp` file as an example of the `vector` library setup. Since then, we have extended this to support type information on locals, following complex types and even inferring results of additional operations. As can be seen, often it’s enough to annotate the type of the data structure and correct fast-path vector code will be generated from that without having to specify the type of each local or temporary. > ***NOTE:*** Advanced inference and operation lowering is enabled by using custom `HostIrHooks` callbacks. Check out ‘Vector’ test with ‘IrHooks’ option in `Conformance.test.cpp` and `ConformanceIrHooks.h` file for an example of the setup. Note that support for native lowering hooks allows generation of CPU code that is multiple times faster than a generic metatable call. Even when native compiler doesn’t have a specific optimization for a type, if the type can be resolved, shorter code sequences are generated and more optimizations can be made between separate operations. > ***NOTE:*** `HostIrHooks` callbacks also enable type inference and lowering for your custom userdata types. Check out ‘NativeUserdata’ test with ‘IrHooks’ option in `Conformance.test.cpp` and `ConformanceIrHooks.h` file for an example of the setup. ## Runtime changes ### Stricter `utf8` library validation `utf8` library will now correctly validate UTF-8 and reject inputs that have surrogates. `utf8.len` will return `nil` followed by the byte offset, `utf8.codepoint` and `utf8.codes` will error. This matches how other kinds of input errors were previously handled by those functions. Strings that are validated using `utf8.len` will now always work properly with `utf8.nfcnormalize` and `utf8.graphemes` functions. Custom per-character validation logic is no longer required to check if a string is valid under `utf8` requirements. ### Imprecise integer number warning Luau stores numbers as 64-bit floating-point values. Integer values up to 2^53 are supported, but higher numbers might experience rounding. For example, both 10000000000000000 and 9223372036854775808 are larger than 2^53, but match the rounding, while 10000000000000001 gets rounded down to 10000000000000000. In cases where rounding takes place, you will get a warning message. If the large value is intended and rounding can be ignored, just add “.0” to the number to remove the warning: ### Leading `|` and `&` in types It is now possible to start your union and intersection types with a symbol. This can help align the type components more cleanly: You can find more information and examples in [the proposal](https://github.com/luau-lang/rfcs/blob/leading-bar-ampersand/docs/syntax-leading-bar-and-ampersand.md) ## Analysis Improvements While our main focus is on a type-checking engine rewrite that is nearing completion, we have fixed some of the issues in the current one. - Relational operator errors are more conservative now and generate less false positive errors - It is not an error to iterate over table properties when indexer is not part of the type - Type packs with cycles are now correctly described in error messages - Improved error message when value that is not a function is being used in a call - Fixed stability issues which caused Studio to crash - Improved performance for code bases with large number of scripts and complex types ## Runtime Improvements When converting numbers to strings in scientific notation, we will now skip the trailing ’.’. For example, `tostring(1e+30)` now outputs ‘1e+30’ instead of ‘1.e+30’. This improves compatibility with data formats like JSON. But please keep in mind that unless you are using JSON5, Luau can still output ‘inf’ and ‘nan’ numbers which might not be supported. - Construction of tables with 17-32 properties or 33-64 array elements is now 30% faster. - `table.concat` method is now 2x faster when the separator is not used and 40% faster otherwise. - `table.maxn` method is now 5-14x faster. - vector constants are now stored in the constant table and avoid runtime construction. - Operations like 5/x and 5-x with any constant on the left-hand-side are now performed faster, one less minor thing to think about! - It is no longer possible to crash the server on a hang in the `string` library methods. ## Luau as a supported language on GitHub Lastly, if you have open-source or even private projects on GitHub which use Luau, you might be happy to learn that Luau now has official support on GitHub for `.luau` file extension. This includes recognizing files as using Luau programming language and having support for syntax highlighting. A big thanks goes to our [open source community](https://github.com/luau-lang/luau) for their generous contributions including pushing for broader Luau support: - [birds3345](https://github.com/birds3345) - [bjornbytes](https://github.com/bjornbytes) - [Gskartwii](https://github.com/Gskartwii) - [jackdotink](https://github.com/jackdotink) - [JohnnyMorganz](https://github.com/JohnnyMorganz) - [khvzak](https://github.com/khvzak) - [kostadinsh](https://github.com/kostadinsh) - [mttsner](https://github.com/mttsner) - [mxruben](https://github.com/mxruben) - [petrihakkinen](https://github.com/petrihakkinen) - [zeux](https://github.com/zeux)
1,896
1f0084f3fd52ee0dabdeac6536dcccbd58c3bafd46ee7906a754006176802d91
https://luau.org/news/2023-11-01-luau-recap-october-2023
https://luau.org/
2026-03-29T11:32:14.090002+00:00
# Recap: October 2023 November 1, 2023 We’re still quite busy working on some big type checking updates that we hope to talk about soon, but we have a few equally exciting updates to share in the meantime! Let’s dive in! ## Floor Division Luau now has a floor division operator. It is spelled `//`: For numbers, `a // b` is equivalent to `math.floor(a / b)`, and you can also overload this operator by implementing the `__idiv` metamethod. The syntax and semantics are borrowed from Lua 5.3 (although Lua 5.3 has an integer type while we don’t, we tried to match the behavior to be as close as possible). ## Native Codegen Preview We are actively working on our new native code generation module that can significantly improve the performance of compute-dense scripts by compiling them to X64 (Intel/AMD) or A64 (ARM) machine code and executing that natively. We aim to support all AArch64 hardware with the current focus being Apple Silicon (M1-M3) chips, and all Intel/AMD hardware that supports AVX1 (with no planned support for earlier systems). When the hardware does not support native code generation, any code that would be compiled as native just falls back to the interpreted execution. When working with [open-source releases](https://github.com/luau-lang/luau/releases), binaries now have native code generation support compiled in by default; you need to pass `--codegen` command line flag to enable it. If you use Luau as a library in a third-party application, you would need to manually link `Luau.CodeGen` library and call the necessary functions to compile specific modules as needed - or keep using the interpreter if you want to! If you work in Roblox Studio, we have integrated native code generation preview [as a beta feature](https://devforum.roblox.com/t/luau-native-code-generation-preview-studio-beta/2572587), which currently requires manual annotation of select scripts with `--!native` comment. Our goal for the native code generation is to help reach ultimate performance for code that needs to process data very efficiently, but not necessarily to accelerate every line of code, and not to replace the interpreter. We remain committed to maximizing interpreted execution performance, as not all platforms will support native code generation, and it’s not always practical to use native code generation for large code bases because it has a larger memory impact than bytecode. We intend for this to unlock new performance opportunities for complex features and algorithms, e.g. code that spends a lot of time working with numbers and arrays, but not to dramatically change performance on UI code or code that spends a lot of its time calling Lua functions like `table.sort`, or external C functions (like Roblox engine APIs). Importantly, native code generation does not change our behavior or correctness expectations. Code compiled natively should give the same results when it executes as non-native code (just take a little less time), and it should not result in any memory safety or sandboxing issues. If you ever notice native code giving a different result from non-native code, please submit a bug report. We continue to work on many code size and performance improvements; here’s a short summary of what we’ve done in the last couple of months, and there’s more to come! - Repeated access to table fields with the same object and name are now optimized (e.g. `t.x = t.x + 5` is faster) - Numerical `for` loops are now compiled more efficiently, yielding significant speedups on hot loops - Bit operations with constants are now compiled more efficiently on X64 (for example, `bit32.lshift(x, 1)` is faster); this optimization was already in place for A64 - Repeated access to array elements with the same object and index is now faster in certain cases - Performance of function calls has been marginally improved on X64 and A64 - Fix code generation for some `bit32.extract` variants where we could produce incorrect results - `table.insert` is now faster when called with two arguments as it’s compiled directly to native code - To reduce code size, module code outside of functions is not compiled natively unless it has loops ## Analysis Improvements The `break` and `continue` keywords can now be used in loop bodies to refine variables. This was contributed by a community member - thank you, [AmberGraceSoftware](https://github.com/AmberGraceSoftware)! When type information is present, we will now emit a warning when `#` or `ipairs` is used on a table that has no numeric keys or indexers. This helps avoid common bugs like using `#t == 0` to check if a dictionary is empty. Finally, some uses of `getfenv`/`setfenv` are now flagged as deprecated. We do not plan to remove support for `getfenv`/`setfenv` but we actively discourage its use as it disables many optimizations throughout the compiler, runtime, and native code generation, and interferes with type checking and linting. ## Autocomplete Improvements We used to have a bug that would arise in the following situation: If you placed the cursor after the `""` and before `then` in the conditional, we used to suggest `Left` and `Right` even though they are not valid completions at that position. This is now fixed. We’ve also added a complete suggestion for anonymous functions if one would be valid at the requested position. For example: You will see a completion suggestion `function (anonymous autofilled)`. Selecting that will cause the following to be inserted into your code: We also fixed some confusing editor feedback in the following case: ## Runtime Improvements - `string.format`’s handling of `%*` and `%s` is now 1.5-2x faster - `tonumber` and `tostring` are now 1.5x and 2.5x faster respectively when working on primitive types - Compiler now recognizes `math.pi` and `math.huge` and performs constant folding on the expressions that involve these at `-O2`; for example, `math.pi*2` is now free. - Compiler now optimizes `if...then...else` expressions into AND/OR form when possible (for example, `if x then x else y` now compiles as `x or y`) - We had a few bugs around `repeat..until` statements when the `until` condition referred to local variables defined in the loop body. These bugs have been fixed. - Fix an oversight that could lead to `string.char` and `string.sub` generating potentially unlimited amounts of garbage and exhausting all available memory. - We had a bug that could cause the compiler to unroll loops that it really shouldn’t. This could result in massive bytecode bloat. It is now fixed. ## luau-lang on GitHub If you’ve been paying attention to our GitHub projects, you may have noticed that we’ve moved `luau` repository to a new [luau-lang GitHub organization](https://github.com/luau-lang)! This is purely an organizational change but it’s helping us split a few repositories for working with documentation and RFCs and be more organized with pull requests in different areas. Make sure to update your bookmarks and [star our main repository](https://github.com/luau-lang/luau) if you haven’t already! Lastly, a big thanks to our [open source community](https://github.com/luau-lang/luau) for their generous contributions: - [MagelessMayhem](https://github.com/MagelessMayhem) - [cassanof](https://github.com/cassanof) - [LoganDark](https://github.com/LoganDark) - [j-hui](https://github.com/j-hui) - [xgqt](https://github.com/xgqt) - [jdpatdiscord](https://github.com/jdpatdiscord) - [Someon1e](https://github.com/Someon1e) - [AmberGraceSoftware](https://github.com/AmberGraceSoftware) - [RadiantUwU](https://github.com/RadiantUwU) - [SamuraiCrow](https://github.com/SamuraiCrow)
1,747
8f0b70aa8a3c2885c83c619110c93a368bf784adb4cc061db55c050862b69c6f
https://luau.org/news/2023-07-28-luau-recap-july-2023
https://luau.org/
2026-03-29T11:32:14.100982+00:00
# Recap: July 2023 July 28, 2023 Our team is still spending a lot of time working on upcoming replacement for our type inference engine as well as working on native code generation to improve runtime performance. However, we also worked on unrelated improvements during this time that are summarized here. ## Analysis improvements Indexing table intersections using `x["prop"]` syntax has been fixed and no longer reports a false positive error: Generic `T...` type is now convertible to `...any` variadic parameter. This solves issues people had with variadic functions and variadic argument: We have also improved our general typechecking performance by ~17% and by additional ~30% in modules with complex types. Other fixes include: - Fixed issue with type `T?` not being convertible to `T | T` or `T?` which could’ve generated confusing errors - Return type of `os.date` is now inferred as `DateTypeResult` when argument is “\*t” or ”!\*t” ## Runtime improvements Out-of-memory exception handling has been improved. `xpcall` handlers will now actually be called with a “not enough memory” string and whatever string/object they return will be correctly propagated. Other runtime improvements we’ve made: - Performance of `table.sort` was improved further. It now guarantees N\*log(N) time complexity in the worst case - Performance of `table.concat` was improved by ~5-7% - Performance of `math.noise` was improved by ~30% - Inlining of functions is now possible even when they used to compute their own arguments - Improved logic for determining whether inlining a function or unrolling a loop is profitable ## Autocomplete improvements An issue with exported types not being suggested is now fixed. ## Debugger improvements We have fixed the search for the closest executable breakpoint line. This simplified example shows the issue: ## Thanks A very special thanks to all of our open source contributors: - [Petri Häkkinen](https://github.com/petrihakkinen) - [JohnnyMorganz](https://github.com/JohnnyMorganz) - [Gael](https://github.com/TheGreatSageEqualToHeaven) - [Jan](https://github.com/Jan200101) - [Alex Orlenko](https://github.com/khvzak) - [mundusnine](https://github.com/mundusnine) - [Ben Mactavsin](https://github.com/BenMactavsin) - [RadiatedExodus](https://github.com/RealEthanPlayzDev) - [Lodinu Kalugalage](https://github.com/imlodinu) - [MagelessMayhem](https://github.com/MagelessMayhem) - [Someon1e](https://github.com/Someon1e)
599
84eba13bfaa20aa40b3d28c2a607dc7b8ac8d1d75ab1e0ce3240f2a052744bf6
https://luau.org/news/2025-12-19-luau-recap-runtime-2025
https://luau.org/
2026-03-29T11:32:14.123054+00:00
# Luau Recap for 2025: Runtime December 19, 2025 Hello everyone! It has been a while since the last recap and we wanted to go over changes we have made in Luau since the last update. Because of the amount of time that passed, in this part of the recap, we are going to focus on the runtime changes: new library functions, compiler changes, native code generation changes and Luau C API updates! ## New libraries and functions We have added the [vector library](https://rfcs.luau.org/vector-library.html) to construct and work without native `vector` type. Before this, the type was available, but the embedder had to provide construction and methods to work with it. It also meant that it lacked built-in call optimizations for common methods. With the built-in library, we get fast-call optimization, support for vector constants and constant-folding in the compiler and native code generation comes out of the box! In the `math` library, we have added [`math.map`](https://rfcs.luau.org/function-math-map.html), [`math.lerp`](https://rfcs.luau.org/function-math-lerp.html) and [`math.isnan`/`math.isinf`/`math.isfinite`](https://rfcs.luau.org/math-isnan-isfinite-isinf.html) functions. Finally, for the `buffer` library, [`buffer.readbits`/`buffer.writebits`](https://rfcs.luau.org/function-buffer-bits.html) API was added. ## Require by string After the earlier approval of the require-by-string RFC, we have built a separate Luau.Require library that any project can include. It will bring the common semantics of the string require while supporting the full set of features such as alias and configuration resolution while remaining customizable in different environments with both real and virtual file systems representing the Luau file hierarchy. ## Runtime changes and improvements A new `lua_newuserdatataggedwithmetatable` API lets you create tagged userdata objects with an associated shared metatable (using `lua_setuserdatametatable`) in a single call. In our applications, we have measured a 3x speedup of creating new userdata objects, which is especially important when they represent small and frequently allocated structures like colors or matrices. And speaking of userdata, Luau now guarantees that it will be suitable for objects that require 16 byte alignment. As long as you provide Luau with a global allocator which also respects that. For lightuserdata, new `lua_rawgetp`/`lua_rawsetp`/`lua_rawgetptagged`/`lua_rawsetptagged` have been added to match Lua 5.2+ and allow you to index tables with lightuserdata keys directly and more performantly. Yieldable C functions can now call other yieldable functions using the `luaL_callyieldable` method. One limitation we still have is making nested yieldable protected calls. We will be looking into supporting that in the future. Protected calls using `pcall` or `xpcall` are now stackless when performed in a yieldable context. This means that calling those functions will not apply the C call depth limit to your Luau code. We will be looking into making those stackless even in non-yieldable contexts as well as improving overall performance of `pcall`/`xpcall` next year. Our runtime is now more robust against out-of-memory errors and is easier to work with in low memory conditions: - `luaL_where` and `luaL_error` can be called without `lua_checkstack` - `luau_load` will no longer throw an error on out-of-memory - `lua_checkstack` will report a failure on out-of-memory instead of throwing an error - `lua_cpcall` function has returned and allows you to enter a protected environment to execute your target C function There were also some small bug fixes: - Using ‘%c’ with a 0 value in `string.format` appends a ‘0’ instead of doing nothing - `xpcall` is consistent before and after target function yields Finally, a few new C API functions that weren’t mentioned: - `lua_clonetable` lets you clone a table - `lua_tolstringatom` is an alternative to `lua_tostringatom` but also provides you with the length of the string - `lua_unref` no longer accepts references that are not in the table ## Changes in the compiler On the compiler side, we have made improvements to constant propagation, inlining and a few other things. With the introduction of the `vector` library mentioned earlier, we have provided constant propagation and type inference for vector library globals. Vector arithmetic and library functions are also constant-folded when possible and vector constants are embedded into the bytecode. Constant-folding has also been added to `string.char` and `string.sub` methods. String concatenation and string interpolation will also be constant-folded for constant strings or even when only some of the strings in the expression are constant. Inlining has received multiple improvements. The inlining cost model is now aware of the work constant-folding has done and will not consider constant expressions to have a cost of evaluation. This means that functions computing a constant based on other global constants is a very likely inlining candidate: Further improvements made it so that code which can be considered dead based on the state of global constant locals does not increase the cost: Inlining can now propagate constant variables that are not representable as literal values. For example, passing a function into a function as an argument can cause the argument function to be inlined! And the biggest change is that the inlining cost model is now updated per call to take constant arguments into account. This means that a large function can sometimes collapse into a small one, which is much more suitable for inlining: Some smaller features are rewriting `const * var` and `const + var` operations into `var * const` and `var + const` when `var` is known to be a number from type annotations. This allows the expression to use one bytecode instruction instead of two for a small performance improvement. Finally, with all these optimizations, we have added a way for the embedder to disable them for a specific built-in function call in case it has a different overwritten meaning. ## Changes in Native Code Generation A lot of work is still going into our native code generation module, which has gained support for working on Android and has been tested in production. Once again, `vector` library introduction required us to provide native lowering of all those functions for best performance. It is now possible to remove a lot of code in case you had those native IR hook functions for vectors. In particular, for `vector.dot` we are lowering it to a CPU dot product instruction when possible. `vector.lerp` and `math.lerp` enjoy a new `MULADD_NUM` instruction that lowers to CPU fused-multiply-add when that is available. Load-store propagation pass has been added to detect duplicate loads of vector components as well as allowing loads from previous stores to re-use the existing register value or extract a single component from it using a new `EXTRACT_VEC` instruction. Unused stores of vectors into VM registers can also now be removed. Multiple optimizations have been done to ensure our basic blocks are as long as possible without being broken up by control flow. The longer the basic block, the easier it is to optimize and reuse values. We have updated the lowering of `bit32.btest` to use a new `CMP_INT` instruction which no longer causes that call to generate a branch. Equality comparisons `==`/`~=` are also performed without branching now. With some extra handling, checks like `type(x) == "number"` of `typeof(x) == "string"` are now transformed into a tag check or a direct string pointer comparison, all without introducing branches. Operators `and`/`or` for a simple value will use the new `SELECT_IF_TRUTHY` instruction which will also keep the basic block linear. An additional optimization to keep blocks linear is a specialized instruction `GET_CACHED_IMPORT` for resolving imports. Multiple calls to global functions can be in a block without creating unnecessary diamond shapes in the control-flow graph. Finally, we are now lifting the checks for safe execution environment to the start of the block and also skipping tag checks on type-annotated function arguments that are not being modified inside the function. Load-store propagation was very effective for vectors so we extended it to upvalues, buffers and userdata. Multiple upvalue lookups to the same slot can now be reused without reloading the memory. We keep all the stores for now until we get new dead store optimizations, but we can still skip reloading the values that have just been stored outside. To support this for buffer data, we had to introduce new instructions for properly truncating data. For example, if you write `0xabcd` with `buffer.writei8`, you cannot just re-use the same value for a future read at that location, but need to truncate it to `0xcd`. And of course that might not be a constant value you can constant-fold. Userdata is actually very similar to buffers, using the same IR instructions for access. But with load-store propagation, we are able to remove temporary userdata allocation. Custom userdata types with proper IR hooks can now generate code that is very efficient without having to be built-in. In the following example, we are reading a userdata field ‘uv’ from another userdata twice to access its components: After new optimizations, we propagate the fields, remove unused temporary allocations and perform the target multiplication: In the future, we are looking to apply load-store propagation to table accesses as well. Another area of optimization that we are looking into are optimizations around implicit integer values. Operations like adding or subtracting integer numbers coming from buffers or `bit32` library results can now use integer CPU instructions automatically. Additional optimizations around int/uint/double conversions lets us stay longer with those integer values as long as results perfectly match the ones that double numbers would give. Other work we have done this year includes: - Arithmetic optimization for basic identities like `1 * a => a`, `a * 2 => a + a` and others - Optimization data now flows between separate basic blocks as long as they end up glued together in 1:1 relationship - Unused GC object stores to VM registers can now be removed as long as no one will observe their death by garbage collection - Float load/store has been separated from float/double conversion for better value reuse - Constant information can be attached to IR registers instead of VM registers for values without a VM storage location - Loop step value extraction optimization has been fixed to work in additional cases - Optimization for register spills and handling of code with more live registers than can fit into CPU registers We have a lot of work planned for improving native code generation next year! ## Community A big thank you goes to our [open source community](https://github.com/luau-lang/luau) for their contributions over the last year. Some of the improvements that we have mentioned come directly from your PRs or your feedback!
2,307
971b899a90ab1bfe03227ebf9dbed3a36612d1dd0a97f0b1c98cb1e44a09dab9
https://luau.org/news/2023-03-31-luau-recap-march-2023
https://luau.org/
2026-03-29T11:32:15.996439+00:00
# Recap: March 2023 March 31, 2023 How the time flies! The team has been busy since the last November Recap:working on some large updates that are coming in the future, but before those arrive, we have some improvements that you can already use! ## Improved type refinements Type refinements handle constraints placed on variables inside conditional blocks. In the following example, while variable `a` is declared to have type `number?`, inside the `if` block we know that it cannot be `nil`: One limitation we had previously is that after a conditional block, refinements were discarded. But there are cases where `if` is used to exit the function early, making the following code essentially act as a hidden `else` block. We now correctly preserve such refinements and you should be able to remove `assert` function calls that were only used to get rid of false positive errors about types being `nil`. Throwing calls like `error()` or `assert(false)` instead of a `return` statement are also recognized. Existing complex refinements like `type`/`typeof`, tagged union checks and other are expected to work as expected. ## Marking table.getn/foreach/foreachi as deprecated `table.getn`, `table.foreach` and `table.foreachi` were deprecated in Lua 5.1 that Luau is based on, and removed in Lua 5.2. `table.getn(x)` is equivalent to `rawlen(x)` when ‘x’ is a table; when ‘x’ is not a table, `table.getn` produces an error. It’s difficult to imagine code where `table.getn(x)` is better than either `#x` (idiomatic) or `rawlen(x)` (fully compatible replacement). `table.getn` is also slower than both alternatives and was marked as deprecated. `table.foreach` is equivalent to a `for .. pairs` loop; `table.foreachi` is equivalent to a `for .. ipairs` loop; both may also be replaced by generalized iteration. Both functions are significantly slower than equivalent for loop replacements, are more restrictive because the function can’t yield. Because both functions bring no value over other library or language alternatives, they were marked deprecated as well. You may have noticed linter warnings about places where these functions are used. For compatibility, these functions are not going to be removed. ## Autocomplete improvements When table key type is defined to be a union of string singletons, those keys can now autocomplete in locations marked as ’^’: We also fixed incorrect and incomplete suggestions inside the header of `if`, `for` and `while` statements. ## Runtime improvements On the runtime side, we added multiple optimizations. `table.sort` is now ~4.1x faster (when not using a predicate) and ~2.1x faster when using a simple predicate. We also have ideas on how improve the sorting performance in the future. `math.floor`, `math.ceil` and `math.round` now use specialized processor instructions. We have measured ~7-9% speedup in math benchmarks that heavily used those functions. A small improvement was made to builtin library function calls, getting a 1-2% improvement in code that contains a lot of fastcalls. Finally, a fix was made to table array part resizing that brings large improvement to performance of large tables filled as an array, but at an offset (for example, starting at 10000 instead of 1). Aside from performance, a correctness issue was fixed in multi-assignment expressions. In this example, `n - 1` was assigned to `n` before `n` was assigned to `arr[1]`. This issue has now been fixed. ## Analysis improvements Multiple changes were made to improve error messages and type presentation. - Table type strings are now shown with newlines, to make them easier to read - Fixed unions of `nil` types displaying as a single `?` character - “Type pack A cannot be converted to B” error is not reported instead of a cryptic “Failed to unify type packs” - Improved error message for value count mismatch in assignments like `local a, b = 2` You may have seen error messages like `Type 'string' cannot be converted to 'string?'` even though usually it is valid to assign `local s: string? = 'hello'` because `string` is a sub-type of `string?`. This is true in what is called Covariant use contexts, but doesn’t hold in Invariant use contexts, like in the example below: In this example, while `Model` is a sub-type of `Instance` and can be used where `Instance` is required. The same is not true for a table field because when using table `b`, `b.x` can be assigned an `Instance` that is not a `Model`. When `b` is an alias to `a`, this assignment is not compatible with `a`’s type annotation. --- Some other light changes to type inference include: - `string.match` and `string.gmatch` are now defined to return optional values as match is not guaranteed at runtime - Added an error when unrelated types are compared with `==`/`~=` - Fixed issues where variable after `typeof(x) == 'table'` could not have been used as a table ## Thanks A very special thanks to all of our open source contributors: - [niansa/tuxifan](https://github.com/niansa) - [B. Gibbons](https://github.com/bmg817) - [Epix](https://github.com/EpixScripts) - [Harold Cindy](https://github.com/HaroldCindy) - [Qualadore](https://github.com/Qualadore)
1,207
f9a521de5b65d5207789bbe459740bb830a9141edaec675d95c8d6c668ee2b39
https://luau.org/news/2023-02-02-luau-string-interpolation
https://luau.org/
2026-03-29T11:32:16.026787+00:00
# String Interpolation February 2, 2023 String interpolation is the new syntax introduced to Luau that allows you to create a string literal with expressions inside of that string literal. In short, it’s a safer and more ergonomic alternative over `string.format`. Here’s a quick example of a string interpolation: String interpolation also composes well with the `__tostring` metamethod. To find out more details about this feature, check out [Luau Syntax page](/syntax#string-interpolation). This is also the first major language feature implemented in a [contribution](https://github.com/Roblox/luau/pull/614) from the open-source community. Thanks [Kampfkarren](https://github.com/Kampfkarren)!
159
00c166e196fbcbb4a6112567b4ef28a0d727aecc1aedc06ae1cfbc970db37143
End of preview. Expand in Data Studio
README.md exists but content is empty.
Downloads last month
48