Skip to content

Instantly share code, notes, and snippets.

@EndangeredMassa
Created June 12, 2013 18:17
Show Gist options
  • Save EndangeredMassa/5767753 to your computer and use it in GitHub Desktop.
Save EndangeredMassa/5767753 to your computer and use it in GitHub Desktop.
Lua packages
_G.createContext()
local a = require('complex')
print( a.add(5, 6) )
-- 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
_G.createPackageContext(...)
function add(a, b)
print('calculating')
return a + b
end
$ lua -l global index.lua
calculating
11
@EndangeredMassa
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment