Indie game storeFree gamesFun gamesHorror games
Game developmentAssetsComics
SalesBundles
Jobs

ct.js

Create cool 2D games with a free game editor! · By Cosmo Myzrail Gorynych

How to access a function from another Copy

A topic by JB007 created 42 days ago Views: 48 Replies: 1
Viewing posts 1 to 2
(1 edit)

Hi fellow devs,

I have gone around in circles trying to figure out how to access a function from another copy, and I either always get 'cannot access x from undefined' or 'x is not a function'

For example (Pseudo code) - Here I would like to call GetPiece function  that is another copy.

copy > Piece code =======================================================

var board=ct.types.list["Board"];

var p=board.GetPiece(3,4); // get the peice stored at position 3,4

copy> Board code =======================================================

function GetPiece(x,y){

    return x*y;             // pseudo example

}


I have tried putting the function in Create and OnStep but not joy.

Developer(+1)

There are several issues here.

ct.types.list["Board"] returns an array of all the boards. Even if there is just one board, it will still be an array. To access the first element, you can write var board = ct.types.list["Board"][0];. (Note the [0] index.)

function GetPiece(x,y){...} creates a global function that is visible from anywhere without any prefixes. In this format, it is better to put it once in Settings > Scripts so it does not get overwritten every once in a while when a new copy is created.

Functions created in format function getPiece() {...} can be called at any time by their name: p = getPiece();. Now, global functions don’t have access to copies’ properties, but you can pass a needed copy as an argument, e.g. var p = getPiece(board);, and inside this function you use board.x and board.y.

You can also attach functions to copies in this format:

// In OnCreate tab of a Board
this.getPiece = function (someCondition) {
  if (someCondition) {
    return this.x * this.y;
  } else {
    return 0;
  }
}

These functions do have access to its parent’s parameters and can be called with board.getPiece(lalala);. You probably want to use this approach.