why are there 2 cast operations (in 5.1src)?

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

why are there 2 cast operations (in 5.1src)?

fatfatson
hi,all:
   last night i read the 5.1src and found a strange code in ltable.c, please note the lines i marked RED: there are 2 cast for "k" and "n", first cast "n" from lua_Number to int and result is saved in "k", but soon it then cast "k" back to lua_Number to adopt to the function luai_numeq as its first argument. i don't known why it's neccesary:(
 
const TValue *luaH_get (Table *t, const TValue *key) {
  switch (ttype(key)) {
    case LUA_TNIL: return luaO_nilobject;
    case LUA_TSTRING: return luaH_getstr(t, rawtsvalue(key));
    case LUA_TNUMBER: {
      int k;
      lua_Number n = nvalue(key);
      lua_number2int(k, n);
      if (luai_numeq(cast_num(k), nvalue(key))) /* index is int? */

        return luaH_getnum(t, k);  /* use specialized version */
      /* else go through */
    }
    default: {
      Node *n = mainposition(t, key);
      do {  /* check whether `key' is somewhere in the chain */
        if (luaO_rawequalObj(key2tval(n), key))
          return gval(n);  /* that's it */
        else n = gnext(n);
      } while (n);
      return luaO_nilobject;
    }
  }
}
Reply | Threaded
Open this post in threaded view
|

Re: why are there 2 cast operations (in 5.1src)?

Roberto Ierusalimschy
>   last night i read the 5.1src and found a strange code in ltable.c, please
> note the lines i marked RED: there are 2 cast for "k" and "n", first cast
> "n" from lua_Number to int and result is saved in "k", but soon it then cast
> "k" back to lua_Number to adopt to the function luai_numeq as its first
> argument. i don't known why it's neccesary:(

To check whether that lua_Number fits in an integer. luai_numeq is
a macro that expands likes this:  

     if (cast_num(k) == nvalue(key)) /* index is int? */

-- Roberto

Reply | Threaded
Open this post in threaded view
|

Re: why are there 2 cast operations (in 5.1src)?

fatfatson
thanks a lot!  i'v got it.:)