文件系统

loadfile

将工作区 Luau 文件作为函数加载,而不立即执行。

语法

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

参数

名称类型描述
pathstring文件或文件夹的工作空间相对路径。
chunkName?string加载块的调试输出中使用的可选名称。

返回值

名称类型描述
chunkfunction编译成功时加载的函数。
errorMessagestring | nil加载或解析失败时返回错误信息,否则返回nil。

说明

将工作区 Luau 文件作为函数加载,而不立即执行。

使用 2 个参数调用: path, chunkName。参数表会说明哪些值必填,哪些值只用于细化行为。

返回 chunk (function), errorMessage (string | nil)。使用返回表区分成功值、nil 结果和可恢复错误。

示例

编译本地Luau文件并处理编译错误。

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

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