Ooops
November 24, 2020, 09:39:24 AM

Author Topic: Sharing Functions with Lua and BmaxNG  (Read 1462 times)

Offline GW

  • Full Member
  • ***
  • Posts: 202
Sharing Functions with Lua and BmaxNG
« on: June 15, 2017, 05:10:46 AM »
[There really ought to be a code archives for this kind of post. hint, hint]

This tip is for BMaxNG and the zeke Luajit module, both maintained by Brucey.

Lua doesn't have any builtin Sign() function and handling the function inside lua was killing the performance of my script. 
The solution was to expose a function from Bmax to lua using the FFI.


1) Create a C file and inside put your function
Code:  (Unknown Language)
  1.  
  2. __declspec(dllexport) double c_sign(double x)
  3. {
  4.    return (x>0.0)-(x<0.0);  
  5. }
  6.  
Notice the dllexport part. this tells gcc that the function is exposed at the same level as the C standard library.
2) In your Bmax project you'll want to create a reference to the function like normal:
Code:  (Unknown Language)
  1. import "my_c_functions.c"
  2. extern
  3.    function c_sign:double(x:double)
  4. endextern
  5.  


3) Then in Lua, You need to declare the format of the function like:
Code:  (Unknown Language)
  1. local ffi = require("ffi")
  2.  
  3. ffi.cdef[[
  4. double c_sign(double x);
  5. ]]
  6. function sign(x)
  7.    return ffi.C.c_sign(x)
  8. end
  9.  

Now you can use the sign function in lua that's not slow as hell.
This same method can be used in Vanilla Bmax, but there may be some extra steps because bcc mangles the name. you can look at the top of the generated assembly file to view the new name. It's been many years since I did it, so I don't recall all of the steps for classic BMax.
 

Offline Qube

  • Administrator
  • Hero Member
  • *****
  • Posts: 2565
  • I mostly code at night... Mostly.
    • SyntaxBomb - Indie Coders
Re: Sharing Functions with Lua and BmaxNG
« Reply #1 on: June 15, 2017, 07:20:10 AM »
Quote
[There really ought to be a code archives for this kind of post. hint, hint]
Created, created :)
Mac mini ( 2018 / 2020 ), 3 GHz 6-Core Intel Core i5, 16 GB 2667 MHz DDR4, 1TB NVMe, eGPU Radeon Pro 580 8 GB, LG Ultragear 27GL83A-B 27 Inch
Commodore VIC-20, 1.1Mhz MOS 6502 CPU, 5KB RAM, VIC ( 6560 ) GPU

Until the next time...

 

SimplePortal 2.3.6 © 2008-2014, SimplePortal