Simplifying tpl programs by putting functions in a seperate file.

44 views
Skip to first unread message

Carl Giles

unread,
Apr 10, 2021, 8:07:59 PM4/10/21
to CAMotics Users

I would like to put many subroutines (functions) in a 'routines.tpl' file and load that file in at the beginning of my main .tpl source file so that I can do a lot with a file of 30 or so lines of code (because the thousands of lines of functions are hidden while I write.)

Could someone split up the example cds.tpl into cds.funcs.tpl carrying the functions, and load it into Cds.tpl which would just use the functions? I have tried the require keyword, and either I try it in a way where the file for the functions can't be found, or I get it to load in, but for some reason it doesn't find executable code there.

On this PC I have Linux Mint and Camotics 1.2.0.

Thanks,
Carl

Joseph Coffland

unread,
Apr 14, 2021, 2:22:53 AM4/14/21
to CAMotics Users
You can use the require() function to load in other programs.  E.g. var routines = require('routines.tpl');.  You have to make your functions accessible by exporting them.  I recommend doing it like this:

var routines = {
  a: function () {
    routines.b();
  },

  b: function () {
    console.log('Hello World!');
  }
}

module.exports = routines;

Then you can do this:

var routines = require('routines.tpl');
routines.a();

Carl Giles

unread,
Apr 19, 2021, 9:57:23 PM4/19/21
to CAMotics Users
I tried that.  The last two lines went into 'main.tpl'
The first 11 or so lines went into 'routines.tpl'
both files were in the ~/CNC/camotics directory.

I loaded 'main.tpl' into camotics, and it couldn't find 'routines.tpl'
I tried renaming 'routines.tpl' to routines.json'
and changed the line to:
var routines = require('routines.json');
but that didn't work.

I get the impression that javascript is very very sensitive to syntax.

Joseph Coffland

unread,
Apr 22, 2021, 6:45:50 PM4/22/21
to CAMotics Users
Try require('./routines.json');

Carl Giles

unread,
Jul 3, 2021, 10:34:02 PM7/3/21
to CAMotics Users
  I have found that if all the files are in the same directory, then the .tpl file can import the routines.tpl file if the ./ is prepended to the name:
require ('./routines.tpl');

as in your example, the subroutines must be separated by a comma, and not a semicolon.

Thanks.

Erica C

unread,
Feb 3, 2022, 9:19:14 AM2/3/22
to CAMotics Users
Hi there,

I'm trying to do the exact same thing as recommended here. But when I compile it in CAMotics, I get the following error:

ERROR:Exception: ReferenceError: module is not defined

ERROR: at C:/code/CNC/Geom.tpl:57:1


Any ideas as to why it's not working on mine?


Thanks in advance,


Erica.


Erica C

unread,
Feb 3, 2022, 9:39:05 AM2/3/22
to CAMotics Users
Oops, please ignore, I had added the library module to the camotiocs project, which generated that error. Once removed it worked as advertised.

Thanks,

Erica.

Reply all
Reply to author
Forward
0 new messages