cross version compatible module definition
Posted: Sat Apr 18, 2015 5:43 pm
The search form didn't answer my question so I'll start a thread about it, and I'm guessing Kikito is the one I'd like to answer it, but everyone else is welcome to share opinions of course. Also, as far as LoVE is concerned, we're locked into the 5.1 world via luajit, so this isn't a thing to worry about for most people. I'm writing a module of all of the things I consider to be useful to me from my time in the javascript world. The inspiration is from moses.lua, luafun, underscore.lua, etc. Please go review and trust them before using anything you get out of me, they actually unit test.
For me, I'd like to know what's a good pattern to use for modules that would not only work in luajit, but 5.2/5.3 (in case I bring this code over to lua.io, or any other node clone). The feature in particular I'm after is simulating _ENV's safety. I think this it the way to go:
The question is: is this a terrible idea? What am I forgetting? Is checking for setfenv enough to discover 5.1? What should I change?
For me, I'd like to know what's a good pattern to use for modules that would not only work in luajit, but 5.2/5.3 (in case I bring this code over to lua.io, or any other node clone). The feature in particular I'm after is simulating _ENV's safety. I think this it the way to go:
Code: Select all
local module = function(_ENV)
__ = {}
__.reduce = function(fn, array, initial)
local result = initial or 0
for i = 1, #array do
result = fn(result, array[i], i)
end
return result
end
return __
end
local environment = setmetatable({}, {__index = _G})
if setfenv then setfenv(module, environment) end
return module(environment)