lua-users home
lua-l archive

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



> -----Original Message-----
> From: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org] On
> Behalf Of Luke Gorrie
> Sent: zaterdag 6 april 2013 17:13
> To: Lua mailing list
> Subject: Parameterized modules
> 
> Dear list,
> 
> I have been using Lua for some months and really enjoying the experience
> so far.
> 
> I did a small hack for "parameterized modules" this week and I wanted to
> show it to you and ask for some feedback, particularly about whether there
> is a simpler way to achieve the same thing.
> 
> I am writing network card device drivers in Lua. I always start by writing
> the code as if there is only one network card to control, and then I need
> to generalize it to support controlling several network cards in the same
> Lua VM. I have been looking for simple and concise ways to achieve this
> generalization.
> 
> The first thing I tried was to wrap my driver module in a function:
> 
> function new(name_of_device) {
>    local x, y, z -- device-speific state
>    ... module definition ...
> }
> 
> but it seems like a lot of impact on the source code. (Perhaps this is
> mostly because of the way lua-mode is indenting the code in Emacs, i.e.
> forcing the body of the module three spaces to the right.)
> 
> Then I tried using o:m() style object-orientation instead, but I found it
> quite verbose to add so many "self" tokens to the source file.
> 
> Finally I have tried something more radical: to load a new copy of the
> module for every device instance so that I can continue to write each
> driver as if there is only one device to control.
> 
> Here is my
> implementation: https://github.com/SnabbCo/snabbswitch/commit/b44c0fbc32b6
> a82f2771c74521cebcc0306dac0e
> 
> What do you think?
> 

I haven't looked at the actual code, but how about creating a module with 1 function; 'newdriver(param1, param2, etc)`

So instead of (without 'module()')

local upval1, upval2

local M = {}

m.myfunc1 = function(param)
end

m.myfunc1 = function(param)
end

return M

do something like this;


return = {
  newdriver = function(param1, param2, etc)

    local upval1, upval2
    local M = {}

    m.myfunc1 = function(param)
    end

    m.myfunc1 = function(param)
    end  

    return M
  end
}

You can use it as
local driver = require("modulename").newdriver(param1, param2, etc)

or even add a __call metamethod to the module table and do
local newdriver = require("modulename")
local driver = newdriver(param1, param2, etc)


regards
Thijs