lua-users home
lua-l archive

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

Henderson, Michael D wrote:

> Hi. I'm using the 5.1-alpha package. I am changing C++ programs to use
> configuration files written in Lua. It is a joy to see a future where I
> am not maintaining many different custom parsers :)

I like that, too. I now use Lua for almost all of my one-off console

> Do I create a lua_State for each thread?

Threading is the more difficult issue, but many use cases are satisfied
with a single lua state that is protected against multiple entry. Lua
has the hooks already in place. See lua_lock/unlock() in the source code.

> Would I (should I) push the context onto the stack, or would I be
> better off putting it in a table?

Unless you're using tolua++ or another binding tool, you have the choice
of (1) lightuserdata, (2) userdata, or (3) tables. With (1) you cannot
attach metatables. With (2) you can attach a metatable, which allows you
to use the ':' operator with your objects.

I prefer the last option. I create a table and put the pointer to my
C/C++ object in the table with a name like '__self'. It requires an
extra table lookup, but they're fairly cheap and unimportant for my
uses. You may find that not to be the case and may find (2) better
suited for your purposes. The reason I prefer a table over userdata is
that it allows me to put other things in the table if I want to.

I have some sample code that I'll send you directly. But here are the

I provide a 'new()' function that creates an object, sticks it in a
newly created table as a lightuserdata with key "__self", and attaches
the metatable to it. The "__gc" key in the metatable is attached to a
function that calls the destructor. This is SHWEET! The metatable's
"__index" field is set to the main module table so that
obj:getHostName() will work.

Both the main module table and the metatable are created when
luaopen_<module>() is called. The metatable is stored in the registry
with key "<module>_mt". There are LuaL_xxx() routines that will do this
for you and I use those most of the time, though my sample code does not.

I always write a C function that pushes an object on the stack by
creating a table and "__self". I write another function that checks a
particular index on the stack and returns the object or raises an error.

This scheme has worked well for me. As always, your mileage may vary.


Doug Rogers - ICI - V:703.893.2007x220