[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Overriding assignment to do userdata copy instead of reference
- From: Geoff Richards <Ni1phahs@...>
- Date: Wed, 24 Sep 2008 21:56:42 +0100
On Wed, Sep 24, 2008 at 11:28:11AM -0700, Matthew Armstrong wrote:
> ...
>
> There are methods to get/set _function_ environments, but no
> corresponding function for userdata. The lua reference manual says
> there's a C API function for userdata environments, but I don't see
> it. Can you point me in the right direction?
You just use the same functions: lua_getfenv, lua_setfenv. These work
with either a function or userdata in the stack position you point to.
In either case the environment has to be a table, or it can be nil for a
userdata (the default).
I've used this with a DateTime module I've written (not released yet,
I'm fine tuning the API). There are C structs called DateTime and
TimeZone, both of which are stored in userdatas. A DateTime points to a
TimeZone object. I have a C pointer in the DateTime structure, because
that's convenient and efficient for accessing the C time zone data, but
DateTime userdatas also have an environment that points to the time zone
so that I can retrieve the userdata object if someone calls the
'get_time_zone' method or whatever, and that also ensures that Lua won't
collect the time zone while it's being used.
You have to wrap a userdata in a table to keep it in an environment
(e.g., just have an array with one element). And of course you'll need
'__gc' metamethods for the userdatas to free up the structures (or C++
objects, makes no difference).
--
--- Geoff Richards -------------><-------------- http://ungwe.org/ ---
"I tried to fling my shadow at the moon,
The while my blood leapt with a wordless song." -- Theodore Roethke
- References:
- Re: Overriding assignment to do userdata copy instead of reference, Lucas Hermann Negri
- Re: Overriding assignment to do userdata copy instead of reference, Matthew Armstrong
- Re: Overriding assignment to do userdata copy instead of reference, Geoff Richards
- Re: Overriding assignment to do userdata copy instead of reference, Matthew Armstrong
- Re: Overriding assignment to do userdata copy instead of reference, Javier Guerra
- Re: Overriding assignment to do userdata copy instead of reference, Matthew Armstrong
- Re: Overriding assignment to do userdata copy instead of reference, Jerome Vuarand
- Re: Overriding assignment to do userdata copy instead of reference, Matthew Armstrong
- Re: Overriding assignment to do userdata copy instead of reference, Mauro Iazzi
- Re: Overriding assignment to do userdata copy instead of reference, Matthew Armstrong