lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]



On 14 Apr 2014, at 10:03, Enrique Garcia Cota <kikito@gmail.com> wrote:

I've written a series of articles about building Lua modules - it's here:
I would appreciate any feedback or comments on it.

I thought it was very interesting, and made a lot of good points. I have two comments:

o I think the discussion so far in relation to #3 seems to missed what I believe is the main point of monkey patching, that is being able to make big nasty changes quickly with minimum fuss. Chapter 7 of Lua Programming Gems shows an example of this kind of thing. I try my best not to use any code that makes specific efforts for me not to 'decorate' its behaviour. The author of a module is not in the position to decide whether it's a good idea or not for me to patch their code in my circumstances. That being said I am also strongly against any module, that changes the behavioural contract of a function, and I would certainly not permanently change the behaviour of table.concat as another poster suggested that 'Practically everyone' does.

As an example from personal experience, we found a bug in a module used to parse and specifically subtract datetimes. Fixing the bug properly would have required a new software release and an upgrade on 5 servers. However, adding something like (I forget the exact details) the following code to the start of the executing script solved the problem in 10 minutes. We were then free to create the new versions of the server software and redeploy on our own time scale. If the utils module had internally cached the original parseDateTime, we would have been in a different position!

do
local u = require("utils")
local opdt = u.parseDateTime
u.parseDateTime = function(t)
local rv = opdt(t)
rv.isdst = false
return rv
end
end

o A key point that seems to be missing from #5 is that not everybody loads modules from the filesystem. In our environment, we have two searchers, the package.preload searcher, and our own custom searcher that searches an SQLite3 database (our application deployment format). If your multi-file module won't work if I concatenate all the separate files together, then it's of no use to me. I think this can be achieved roughly as follows:

------- part of a module, file1.lua ---
do
local M = {}
M._REQNAME = "mymodule-part-1"

--define your
--module in M

if not package.preload[M._REQNAME] then
package.preload[M._REQNAME] = function() return M end
end
end

------ main part of module, file2.lua ------
do
local part1name = "mymodule-part-1"
local M = {}

if not (pcall(require, part1name)) then
--do your current folder trick and use loadfile/dofile
end
M._part1 = require(part1name)


return M
end

Thanks,
Kevin