[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: require one C module from another
- From: Jay Carlson <nop@...>
- Date: Thu, 19 Jun 2014 23:28:59 -0400
On Jun 19, 2014, at 6:54 PM, Josh Haberman <jhaberman@gmail.com> wrote:
> On Thu, Jun 19, 2014 at 2:26 PM, Aaron Faanes <dafrito@gmail.com> wrote:
>> The safest solution IMO would be to write your luaopen_*
>> to be resilient (or a no-op) in the face of redundant requires.
>> If all they do are assignments to the global environment,
>> this level of safety is easy to attain. I'd be curious to hear
>> if this wasn't the case for you. :)
>
> My C module keeps a weak table mapping (C pointer) -> (Lua wrapper).
> This table is created in my luaopen function. So if my luaopen
> function got called more than once, I would end up with more than one
> table. That would be bad because I generally rely on the guarantee
> that I have at most one Lua wrapper per C object.
>
> I currently store this table in the registry, so I do have the option
> of checking to see whether the table already exists when I create it.
> But I think I should be able to store this as an upvalue of my C
> functions instead if I choose (for example, if it gives better
> performance). If I store the table as an upvalue (the equivalent of
> declaring it as "local" in a pure Lua module), there would be no way
> to do the right thing if my luaopen function gets called multiple
> times.
The easiest thing is to support only one Lua state. You can use static variables like "has_started_initializing" and "has_finished_initializing", or whatever will break the circular dependency.
Section 28.3 of _Programming in Lua, 3ed_ suggests casting the address of a static variable in your C code to a lightuserdata, and using that as an index for the current state's registry.
Jay