loadstring
Compiles Luau source into a callable function.
Returns a function on success, or nil and a compilation error on failure. Compiling does not execute the chunk.
A leading --!optimize N comment is accepted.
- Level 0 disables closure reuse (will be considerably slower on bigger scripts)
- The default is level 1, keeps some optimzations without changing the source too much.
- Level 2 additionally inlines a small parameterless local function.
loadstring(source: string, chunkName: string?): (function?, string?)Parameters
| Parameter | Type | Description |
|---|---|---|
source | string | Source code to compile. |
chunkName | string? | Optional name shown in tracebacks. |
Example
local callback, reason = loadstring("return 2 + 3", "=example")
if callback then print(callback()) else warn(reason) endExample output
5Errors: Invalid argument types raise; syntax errors return nil and a reason.
