Scripts

loadstring

Compiles a Luau source string and returns the loaded function.

Syntax

loadstring(source: string, chunkName?: string): function | nil | string | nil

Arguments

NameTypeDescription
sourcestringLuau source string to compile. Embedded null bytes after the first null are not preserved.
chunkName?stringOptional chunk name used for error reporting. Defaults to "@" when omitted or nil.

Returns

NameTypeDescription
chunkfunction | nilLoaded function when compilation and loading succeed, otherwise nil.
errorMessagestring | nilLoad error message when loading fails. Not returned on success.

Description

Compiles a Luau source string and returns the loaded function. If loading fails, it returns nil and an error message. The returned function is not executed automatically.

Call it with 2 parameter(s): source, chunkName. The argument table explains which values are required and which ones only refine the behavior.

It returns chunk (function | nil), errorMessage (string | nil). Use the returns table to separate successful values from nil results and recoverable errors.

Example

Compile source text and handle a possible compiler error.

local chunk, message = loadstring("return 6 * 7", "ExampleChunk")

if chunk then
    print(chunk())
else
    warn(message)
end