Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between loadfile, require, and import

Tags:

lua

It seems like there are multiple ways to access one file from another. Why would I choose one method over another?

local a = loadfile('foo.lua')()
local b = require 'foo.lua'
local c = import 'foo.lua'
like image 733
Ryan Avatar asked Dec 12 '15 02:12

Ryan


1 Answers

There is no import function in the Lua standard library. Not for 5.1, 5.2 or 5.3. Maybe you're thinking of some other code that supplies this functionality; you'll have to ask the provider of that function about it.

require does not load .lua files; it loads modules. Exactly what require does is defined by package.loaders in 5.1 or package.searchers in 5.2/3. A particular module may be implemented as a .lua file, but it may also be a .dll/.so. Or it may be a name that's looked up in a compile-time table if the module is internal to the application. Or it could download something from the internet. Or anything at all, depending on what the loaders/searchers do.

The default loaders/searchers can load .lua files, but they only search through directories based on the Lua search path. This path is initialized by an environment variable, but the user can override it.

Module naming conventions also have some notion of sub-modules. You almost never put ".lua" in a module name. require loads modules, not files; any files loaded are a side-effect of loading a module.

Oh, and require caches loaded modules. Calling it again with the same module name will simply return the module that was previously loaded. If you want to reload a module, you have to effectively unload it first, which requires editing the module cache. package.loaded stores the module cache; setting an entry to nil removes it from the cache, forcing require to reload it.

Note that this will not automatically change any code that already fetched the module. Lots of Lua files will have something like local module_name = require "module_name" at the top of the file. You cannot reach into such scripts and change what they've already fetched. You would have to re-execute such scripts.

As such, attempting to change a module in-situ can be dangerous unless code is specifically written to expect it.

loadfile loads a file from the disk and compiles it as a Lua chunk. It uses the C standard library facilities to do the file loading, so paths work in accord with the C library implementation that Lua was compiled with. It returns the loaded chunk but does not execute it.

like image 165
Nicol Bolas Avatar answered Nov 08 '22 16:11

Nicol Bolas