Created
June 12, 2013 18:17
-
-
Save EndangeredMassa/5767753 to your computer and use it in GitHub Desktop.
Lua packages
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_G.createContext() | |
local a = require('complex') | |
print( a.add(5, 6) ) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- GLOBAL CHANGES -- | |
-- make requires return the object -- | |
_require = _G.require | |
_G.require = function (name) | |
local original = _G[name] | |
_require(name) | |
local package = _G[name] | |
_G[name] = original | |
return package | |
end | |
-- creating contexts for files -- | |
_G.createContext = function () | |
_G.createPackageContext(nil) | |
end | |
_G.createPackageContext = function (packageName) | |
local exports = {}; | |
setmetatable(exports, {__index = _G}) | |
if (packageName) then | |
_G[packageName] = exports; | |
end | |
setfenv(2, exports) | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
_G.createPackageContext(...) | |
function add(a, b) | |
print('calculating') | |
return a + b | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$ lua -l global index.lua | |
calculating | |
11 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This allows you to require modules and store the result in a variable. It also provides helper methods that set the file context properly so that you don't create globals all over the place.