loadfile
Loads a Luau file and returns it as a function.
Syntax
loadfile(path: string) -> function?, string?Parameters
| Parameter | Type | Description |
|---|---|---|
path | string | The file path |
Returns
| Type | Description |
|---|---|
function? | The compiled chunk, or nil when compilation fails |
string? | The compiler error when compilation fails |
Description
loadfile reads a Luau file from Volt's workspace and compiles it in the global environment. Compilation errors return nil and an error string. Invalid paths, missing files, and non-file paths raise errors.
Example
-- Create a Luau file
writefile("mymodule.lua", [[
local message = "Hello from file!"
return message
]])
-- Load and execute it
local chunk, err = loadfile("mymodule.lua")
if chunk then
print(chunk()) -- "Hello from file!"
else
warn(err)
endModule System
-- Create a module file
writefile("utils.lua", [[
local Utils = {}
function Utils.greet(name)
return "Hello, " .. name .. "!"
end
function Utils.add(a, b)
return a + b
end
return Utils
]])
-- Load and use the module
local Utils = loadfile("utils.lua")()
print(Utils.greet("World")) -- "Hello, World!"
print(Utils.add(2, 3)) -- 5Error Handling
local function safeLoadFile(path)
if not isfile(path) then
return nil, "File not found"
end
return loadfile(path)
endRelated Functions
readfile- Read raw file contentsloadstring- Load Luau from a string