There are several ways to load and execute code in Lua and LÖVE. As you discovered there is
loadfile, but this function doesn't know about the LÖVE paths and will try to load files from the working directory if you give it a relative path. It also can't decode files from the zip archive.
The LÖVE equivalent of loadfile is
love.filesystem.load. This function will properly search in the game and save directories.
Many lovers prefer the
require function to load additional code. It is part of Lua's module loader and it does more than just load and execute. It takes a module name as a string which will be passed to searchers that look for the module. LÖVE adds such searchers so the game and save directory are covered. Once the module is found, it gets loaded, executed and require saves the first return value (or the boolean value true if nothing was returned) in a table. The next time require is called with the same module name it just returns this saved value. This is useful if you use the module in many files, but only want to load it once. (Or you can just assign your stuff to some global variable and access that everywhere. People don't like the 'abuse' of the global environment much, but I think they'll understand if you're still learning.
)
In case of Lua-file modules, the module name is just the filename without the extension. If you have it in a sub-directory, use the period as a separator instead of slashes. Lua will replace them with the appropriate character.
An example: Let's say you have this Lua file in "source/functions.lua".
Code: Select all
local myFunctions = {}
myFunctions.sayHello = function()
print("Hello")
end
myFunctions.add = function(a, b)
return a + b
end
return myFunctions
You can load and use it like this in the other files.
Code: Select all
funcs = require("source.functions")
funcs.sayHello()
print(funcs.add(5, 7))
Shallow indentations.