Re: Modifying LJ to add a few math functions

  • From: Mike Pall <mike-1307@xxxxxxxxxx>
  • To: luajit@xxxxxxxxxxxxx
  • Date: Fri, 26 Jul 2013 08:51:25 +0200

Emil Dotchevski wrote:
> What should I change in order to add functions to the math lib? I
> added the functions to lib_math.c like so:
> 
> LJLIB_ASM(math_nmod)  LJLIB_REC(math_nmod)
> {
>   int x = lj_lib_checkint(L, 1);
>   if (L->base+1 < L->top) {
>     int y = lj_lib_checkint(L, 2);
>       setintV(L->base-1, x%y);
>       return FFH_RES(1);
>   }
>   return FFH_RETRY;
> }

Change this to:

  LJLIB_CF(math_nmod)
  {
    int x = lj_lib_checkint(L, 1);
    int y = lj_lib_checkint(L, 2);
    setintV(L->top-1, x%y);
    return 1;
  }

> LJLIB_ASM(math_pi)            LJLIB_REC(math_pi)
> {

Umm ... is this really a function? Because math.pi is already
defined. But it's a constant, not a function. Look for:

  LJLIB_PUSH(3.14159265358979323846) LJLIB_SET(pi)

If you really, really want to turn that into a function, then
remove that definition and replace it with:

  LJLIB_CF(math_pi)
  {
    setnumV(L->top++,3.14159265358979323846);
    return 1;
  }

[Note: this will only get you new functions for the interpreter.
Ok, so that's all you need on a (restricted) console. Hooking into
the JIT-compiler would be a bit more involved. This is just in case
someone else reads this posting out of context.]

--Mike

Other related posts: