lua-users home
lua-l archive

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


> On Mon, Apr 14, 2014 at 12:43 PM, Enrique Garcia Cota <kikito@gmail.com>
> wrote:
>> Monkeypatching is a tool. It's a bit more error-prone than others, but
>> mostly because it has been around (popularly) less time. There are
>> things
>> that can be done only through it. That alone justifies its existence in
>> my
>> opinion. But also requires strong reminders of the  dangers of not using
>> it
>> correctly.
>
>
> just call it "dependency injection" and you'll be cool again  :-)

Dependency injection and monkey patching are not the same thing for me.

Dependency injection done right is something I like. In Lua there are
various ways to do it, for instance with the constructor of a "class"
module ("stateless" in Enrique's posts):

-- mod.lua

    local M = {}

    M.new = function(printer)
        return {print = printer}
    end

    return M

-- main.lua

    local M = require "mod"

    local x = M.new(print)
    x.print(42)

With a "stateful" module, a closure and a setter:

-- mod.lua

    local deps = {printer = printer}

    local set_printer = function(printer)
        deps.printer = printer
    end

    return {
        print = function(...) deps.printer(...) end,
        set_printer = set_printer,
    }

-- main.lua

    local M = require "mod"

    M.set_printer(print)
    M.print(42)

-- 
Pierre Chapuis