Black
Black

Reputation: 20352

How does package and require work?

I have a module named load_modbus.

This is how i require it:

driver_modbus   = require "lua_plugin/load_modbus";

Before I require it, I have these code lines:

-- Include Paths
package.path = package.path .. ";./usr/lua/?.lua;./usr/lua/lua_modules/?.lua";
package.cpath = package.cpath .. ";./lib/?.so;./usr/lib/?.so";

How does the require work now? Does it take the path which I gave to require, (lua_plugin/load_modbus) and place it instead of the ? ?

Am I correct that it will search for these files:

./usr/lua/lua_plugin/load_modbus.lua;
./usr/lua/lua_modules/lua_plugin/load_modbus.lua

./lib/lua_plugin/load_modbus.so;
./usr/lib/lua_plugin/load_modbus.so

It would be nice if someone can tell me if I am correct or not. Still try to understand how it works.

Upvotes: 2

Views: 398

Answers (1)

DarkWiiPlayer
DarkWiiPlayer

Reputation: 7064

Short answer: Yes.

Require does not assume you give it a path, but a template. This is because lua can be used on systems that don't have an actual file system. If you give it a string like "/include/?.lua" and require "test" it will replace the "?" with the string you required and try to load "/include/test.lua".

You are mostly correct with the paths it will search, but keep in mind that if you do package.path = package.path .. <something> will just be appended to the standard search path, so it will not only search that path, but all the others too. If you only want to search one path, you'd have to do package.path = <your search path>

There is some more information on this at http://lua.org/manual/5.3

Consider reading that. It might also be interesting to you that lua caches the result of it's require calls, in case you didn't know that already.

Upvotes: 2

Related Questions