lua-users home
lua-l archive

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


2009/12/30 Paul Beckingham <paul@beckingham.net>:
> Hello Lua community.
>
> I have a stylistic question.  I am embedding Lua in an application, such that Lua becomes the language in which hooks are written, to extend or integrate the product.  While I am having no technical difficulties (a testament to your beautiful implementation), I do have a few design decisions to make, and I don't want to end up with something that is not in the spirit of Lua, or Lua-ish if you will.
>
> In the product, an event occurs, which triggers the execution of a Lua script.  There are actually many events, but let's just focus on one, because they are all to be handled in a similar manner.
>
> Option 1)
>
> The product can construct a context (variables and table(s)?) and pass them to the Lua function, which can modify the context, which will then be re-integrated back on the product side.
> Pro: Simple function which simply does what it wants with the data.
> Con: There is a cost to marshaling the data in two directions, even if it isn't used.
>
> Option 2)
>
> The product passes a handle to the Lua script.  The product then implements a series of functions that the Lua can call, to get more data, modify data.
> Pro: Minimal initial data transfer, marshaling on demand
> Con: ?
>
> The product is written in C++, and in one run I might make 300 Lua calls to the same function.
>
> I'm leaning towards option 2, but maybe there is a third I'm not aware of.  Does anyone have any advice on "the Lua way" to do this?


Rather than passing a handle to the function, you can set a proxy
environment to your handler function. The function will then access
the application by accessing some predefined global variables. The
marshalling objects will be created on demand (by the environment
__index function).

One advantage is that if the handler function is a full script (ie. a
chunk without function() header) with unnamed parameters, you don't
have to access the outer world with the sometimes awkward "..."
notation. But that depends on how you define your handler functions
(ie. several named handlers per file, handlers passed to a register
function in an init script, or one script per handler).