lua-users home
lua-l archive

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


If i understand correctly, the problem is really how to maintain distinct state across multiple instances (one per card). In Lua there are several possibilities, some of which you have clearly tried out:

1. Use a table to maintain the state, and pass to functions as necessary.
2. As above, but make the functions methods and use the ":" syntactic sugar.
3. In Lua 5.2, you can manipulate _ENV so that each function thinks it is the only device (this is just a variation on #1 with tricky playing with globals).
4. Use upvalues and closures with a factory.

Of these choices, #4 is the most efficient, since it places the state in upvalues, which are much more efficient to access than globals or tables (which are really the same thing). In fact, an upvalue is nearly as efficient as a local. It is also more readable in that you can access the state as if only one card exists in the methods, but maintain as many state instances as you make calls to the factory.

Make sense?

--Tim


On Apr 6, 2013, at 8:12 AM, Luke Gorrie <lukego@gmail.com> wrote:

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.


What do you think?

(Please excuse the use of module() which I understand I should consider changing.)