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).

Does not error

Previous ambiguous wording for this function made it seem like calling loadstring itself with invalid code would actually error, but in fact it does not. Instead, as stated below, it returns nil and a string (which happens to be an error message).

loadstring compiles a string of Luau code and returns it as a runnable function. If the code has errors, two things are returned: nil and a string, which is the error message.

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>