loadstring
Compiles and loads a string of Luau source code at executor-level identity.
function loadstring(source: string, chunkname: string?): (function?, string?)Synopsis
How it works
Compiles the Luau source string using the executor's built-in Luau compiler (same pipeline as Roblox Studio). The compiler produces bytecodeBytecodeThe compiled binary representation of Luau source code. A sequence of 32-bit instructions (opcodes + operands) stored in a Proto's code[] array. Executed by the Luau VM interpreter. which is then loaded into a new
LClosure with the executor's environment. The returned function runs at full executor thread identityThread identityA numeric privilege level (0–8) assigned to each Luau thread. Determines which Roblox APIs are accessible. Identity 2 = LocalScript, 3 = server Script, 6+ = CoreScript/Plugin level. Executors typically use identity 8..Compilation pipeline
- Lexer — tokenizes the source string
- Parser — builds an ASTASTAbstract Syntax Tree — a tree representation of source code structure. The Luau compiler parses source into an AST (nodes for statements, expressions, identifiers), then compiles it down to bytecode instructions. from tokens
- Compiler — emits Luau bytecodeBytecodeThe compiled binary representation of Luau source code. A sequence of 32-bit instructions (opcodes + operands) stored in a Proto's code[] array. Executed by the Luau VM interpreter. (instruction stream + constant tableConstant tableThe Proto.k[] array containing all literal values (strings, numbers, booleans, nil) referenced by a function's bytecode. Instructions like LOADK and GETGLOBAL index into this table. + proto hierarchy)
- Loader — deserializes bytecode into a
Proto, wraps in anLClosure
nil plus the errorerror()Throws a Lua error, halting execution and unwinding the call stack to the nearest pcall/xpcall. Can throw any value (not just strings). Level parameter controls which function appears in the error message. message string.Security
loadstring is the most dangerous function in the API — it effectively grants code execution. Standard Roblox disables loadstring for game scripts. The executor re-enables it at elevated identity, meaning loaded code has full access to all executor APIs.Usage
Dynamic execution
local fn, err = loadstring("return 1 + 1")
if fn then
print(fn()) "cc">--> 2
else
warn("Compile error:", err)
endParameters
source string The Luau source code to compile.
chunkname string optionalName used in error stack traces.
Returns
function? The compiled function, or nil on error.
string? The compilation error message if compilation failed.
Security
Never loadstring untrusted user input — it runs at full executor identity.