GMLscripts.com

Discuss and collaborate on GML scripts
Invert

You are not logged in.

#1 2016-11-16 16:27:47

Tsa05
Member
Registered: 2016-11-16
Posts: 13

array_insert_2d

Using the new(ish) array accessors to directly manipulate a 2D array, avoiding large copies.
This script accepts a 2D array and inserts a value into the 2nd dimension position of the first dimension array that you specify.

Expand/// array_insert_2d(array, value, row, column);
//
//  Accepts a 2D array and modifies the array to insert
//  a desired value. If the insertion location is
//  outside of the array, devault values are padded.
//
//      array   : The name of a 2D array
//      value   : The value to insert
//      row     : The first dimension index to insert into
//      column  : The second dimension index to insert into
//
//  To avoid duplicating large 2D arrays, the @ accessor is used.
//  No value is returned from the script, as the array is already modified
//
//  This script performs an Insertion, not an overwrite, so expect the 
//  length of the second dimension to change.
//
/// GMLscripts.com/license

var defaultValue = 0; // Used when inserting past the end of an array

var ar = argument[0];
var val = argument[1];
var row = argument[2];
var col = argument[3];

var L1 = array_height_2d(ar);
while(row>=L1){
    // Pad rows up to the one needed
    ar[@L1,0] = defaultValue;
    L1 = array_height_2d(ar);
}

var L2 = array_length_2d(ar,row);
while(col>=L2){
    // Pad columns up to the one needed
    ar[@row,L2] = defaultValue;
    L2 = array_length_2d(ar,row);
}
/*
*   Note on padding:
*
*   Given:
*   |1|2|
*   |3|4|
*
*   array_insert_2d(array, "A", 2, 1)
*
*   Results in:
*   |1|2|
*   |3|4|
*   |0|A|0|
*
*   An extra row was padded, then data up to index 1 was padded
*   Then, the data is inserted (below)
*/

for(var z=L2; z>col; z-=1){
    // Ripple all data forward by one at the desired row,col
    ar[@row, z] = ar[row, z-1];
}
// Set the value at the intended coordinates.
ar[@row,col] = val;

Offline

Board footer

Powered by FluxBB