love.filesystem.load

Available since LÖVE 0.5.0
This function is not supported in earlier versions.

Loads a Lua file (but does not run it).

This is equivalent to loadfile except it operates on LÖVE filesystem paths.

Function

Synopsis

chunk, errormsg = love.filesystem.load( name, mode )

Arguments

string name
The name (and path) of the file.
Available since LÖVE 12.0
LoadMode mode ("bt")
Controls to only allow precompiled chunk, plain text, or both.

Returns

function chunk
The loaded chunk.
string errormsg (nil)
The error message if file could not be opened.

Examples

It is important to note that love.filesystem.load does not invoke the code, it just creates a function (a 'chunk') that will contain the contents of the file inside it. In order to execute the chunk, you have to put () behind it.

Also, it is worth noting that loaded files can return values. For example, the following file:

return 1+1, "foo"

Will return 2 and "foo", when called like this:

local chunk = love.filesystem.load("someFolder/myFile.lua") -- load the chunk
local result1, result2 = chunk() -- execute the chunk
print("Results: "..tostring(result1)..", "..tostring(result2)) -- prints 'Results: 2, foo'

This raises an error if there's a syntax error in the loaded file. If you want your game to continue if the file isn't valid (for example if you expect it to be written by users), you can protect the loading and calling of the file with pcall:

-- success, valueOrErrormsg = runFile( name )
local function runFile(name)
	local ok, chunk, err = pcall(love.filesystem.load, name) -- load the chunk safely
	if not ok    then  return false, "Failed loading code: "..chunk  end
	if not chunk then  return false, "Failed reading file: "..err    end

	local ok, value = pcall(chunk) -- execute the chunk safely
	if not ok then  return false, "Failed calling chunk: "..tostring(value)  end

	return true, value -- success!
end

print(runFile("goodFile.lua"))
print(runFile("fileWithRuntimeError.lua"))
print(runFile("fileWithSyntaxError.lua"))
print(runFile("nonexistentFile.lua"))

See Also


Other Languages