[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: RE: userdata access after __gc?
- From: "Thijs Schreijer" <thijs@...>
- Date: Wed, 17 Oct 2012 09:18:31 +0200
> -----Oorspronkelijk bericht-----
> Van: lua-l-bounces@lists.lua.org [mailto:lua-l-bounces@lists.lua.org]
Namens
> Josh Haberman
> Verzonden: woensdag 17 oktober 2012 2:32
> Aan: Lua mailing list
> Onderwerp: Re: userdata access after __gc?
>
> On Tue, Oct 16, 2012 at 5:00 PM, Luiz Henrique de Figueiredo
> <lhf@tecgraf.puc-rio.br> wrote:
> > The standard io library does not do this. It sets the file handle to
> > NULL so that it can issue a "closed file" error message when the user
> > tries to use an invalid file handle.
>
> Yes, I prefer this solution also, since an error message like "attempt to
index
> field '?' (a user data value)" could be very confusing to a user.
>
> Thanks for the answers everyone.
>
To counter Robert Jakabosky s argument of checks everywhere; I use a flag in
the userdata (sometimes a pointer to external allocated stuff, like IO does
with the handle) and then have a single function that gets a specific index
from the stack, checks whether it's a userdata with the specified metatable
and the flag is still valid and returns that. If not, it uses the error
methods to jump out.
Example from LuaUPnP for an IXML document;
// Get the requested index from the stack and verify it being a proper Node
// throws an error if it fails and will not return then.
static IXML_Node* checknode(lua_State *L, int idx)
{
pLuaNode node;
luaL_checkudata(L, idx, LPNP_NODE_MT);
node = (pLuaNode)lua_touserdata(L, idx);
if (node->node == NULL) luaL_error(L, "Invalid Node (document
closed?)");
return node->node;
}
Other methods expecting that userdata type simply start with;
Nodeptr node = checknode(L, 1);
It either succeeds or it won't return.
Thijs