Filesystem

loadfile

Reads a workspace file, compiles its contents with the Luau compiler, and returns the loaded Luau function without executing it.

Syntax

loadfile(path: string, chunkName?: string): function | nil | string | nil
Aliases loadfileasyncdofiledofileasync

Arguments

NameTypeDescription
pathstringFile path resolved inside the workspace after separator normalization, workspace-boundary checks, and extension checks. Path, open, and read-size errors are thrown.
chunkName?stringOptional chunk name passed to luau_load. Defaults to = when omitted or nil.

Returns

NameTypeDescription
chunkfunction | nilLoaded Luau function when luau_load succeeds. The function is not executed by loadfile.
errorMessagestring | nilError string returned as the second value only when luau_load fails. Filesystem and path errors are thrown instead.

Description

Reads a workspace file, compiles its contents with the Luau compiler, and returns the loaded Luau function without executing it.

Call it with 2 parameter(s): path, 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

Load a workspace Luau file as a function, then call it yourself.

writefile("examples/module.luau", "return 2 + 3")

local chunk, message = loadfile("examples/module.luau", "ExampleModule")

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