Skip to content

loadstring

Unsafe by design

Compiles the given string, and returns it runnable in a function. The environment must become unsafe after this function is called due to it allowing the modification of globals uncontrollably (see setfenv/getfenv documentation).

Should error when compilation fails

This function should return nil and an error message if the provided code fails to compile.

loadstring compiles a string of Luau code and returns it as a runnable function. If the code has errors, nil is returned and an error message is output.

function loadstring<A...>(source: string, chunkname: string?): (((A...) -> any) | nil, string?)

Parameters

Parameter Description
source The source code string to compile.
chunkname? Custom chunk name.

Examples

Example 1

Compiling and running source code successfully
1
2
3
4
5
loadstring([[
    placeholder = {"Example"}
]])()

print(placeholder[1]) -- Output: Example

Example 2

Using a custom chunk name while also getting an error
1
2
3
4
local func, err = loadstring("Example = ", "CustomChunk")

print(func) -- Output: nil
print(err)  -- Output: [string "CustomChunk"]:1: Expected identifier when parsing expression, got <eof>