loadfile
Loads a Lua 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 loaded function, or nil on error |
string? | Error message if loading failed |
Description
loadfile reads a Lua file, compiles it, and returns it as a callable function. This is similar to loadstring but reads from a file.
Example
-- Create a Lua file
writefile("mymodule.lua", [[
local message = "Hello from file!"
return message
]])
-- Load and execute it
local func, err = loadfile("mymodule.lua")
if func then
local result = func()
print(result) -- "Hello from file!"
else
warn("Error:", 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 Lua from a string