Scripts

loadstring

Compiles a Luau source string and returns the resulting function or an error message.

Syntax

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

Arguments

NameTypeDescription
sourcestringSource value used by the operation.
chunkName?stringOptional name used in debug output for the loaded chunk.

Returns

NameTypeDescription
chunkfunction | nilLoaded function when compilation succeeds, otherwise nil.
errorMessagestring | nilError message returned when loading or parsing fails, otherwise nil.

Description

Compiles a Luau source string and returns the resulting function or an error message.

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