Equality...

classic Classic list List threaded Threaded
3 messages Options
Reply | Threaded
Open this post in threaded view
|

Equality...

Fred Bertsch
Is there a way to tell if two lua_Objects are equal from within C?  Some
types are pretty easy, but, for example, tables aren't obvious.  I have to
figure out if they are in the same chunk of memory, but getting a pointer
is obviously not supported by the standard API. 

The only technique I can come up with involves lua_dostring, but that's
not particularly elegant.  

F


Reply | Threaded
Open this post in threaded view
|

Re: Equality...

Roberto Ierusalimschy
> Is there a way to tell if two lua_Objects are equal from within C?  [...]

No :-(  We will consider a function for that for the next version.


> The only technique I can come up with involves lua_dostring, but that's
> not particularly elegant.  

You can do a little better than the obvious solution, using dostring only
once to create the function you need:

  /* untested code */
  int eq;  /* global? static? */
  ...
  /* initialize eq */
  lua_dostring("return function (a,b) return a==b end")
  lua_pushobject(lua_getresult(1));
  eq = lua_ref(1);
  

int is_equal (lua_Object a, lua_Object b) {
  lua_pushobject(a);
  lua_pushobject(b);
  lua_callfunction(lua_getref(eq));
  return !lua_isnil(lua_getresult(1));
}

-- Roberto

Reply | Threaded
Open this post in threaded view
|

Re: Equality...

Luiz Henrique de Figueiredo
In reply to this post by Fred Bertsch
>From [hidden email] Wed Jul 28 20:27:03 1999
>From: Fred Bertsch <[hidden email]>

>Is there a way to tell if two lua_Objects are equal from within C?

Sorry, not with the current API.
Something to consider for the next version.

>I have to
>figure out if they are in the same chunk of memory, but getting a pointer
>is obviously not supported by the standard API. 

Right.
If you must go outside the API, then look at luaA_Address and luaO_equalval.
Something like (unofficial code ahead):

 int ObjectEqual(lua_Object x, lua_Object y)
 {
  return luaO_equalval(luaA_Address(x),luaA_Address(y));
 }

>The only technique I can come up with involves lua_dostring, but that's
>not particularly elegant.  

I don't know whether you mean this (untested code ahead):

 int ObjectEqual(lua_Object x, lua_Object y)
 {
  lua_Object eq;
  int rc;
  lua_beginblock();
  eq=lua_getglobal("EQUAL");
  if (lua_isnil(eq)) {
   lua_dostring("function EQUAL(x,y) return x==y end; return EQUAL");
   eq=lua_getresult(1);
  }
  lua_pushobject(x);
  lua_pushobject(y);
  lua_callfunction(eq);
  rc=!lua_isnil(lua_getresult(1));
  lua_endblock();
  return rc;
 }

For added "efficiency", you can lock the EQUAL function and save a reference
to it in a static var.
--lhf