flatten


The flatten function "flattens" the numeric values of a general lua table to an indexed 1-dimensional array. This procedure discards all non-numeric values and table keys, and reduces all higher dimension tables to the base 1-dimensional array. Flattening is useful, for example, when a function that supports only 1-dimensional arrays, such as meansdev, need to run on values from a complex table. Use the flattenn when a multi-dimensional table must retain all keys and values when flattened to 1-dimensional form.

Syntax

new_array = flatten( tbl )

bullet.gif    tbl is a general lua table.

bullet.gif    new_array is the flattened 1-dimensional array.

Examples

The following script creates a 3-D array with 5 planes, 4 rows, and 3 columns and flattens it to a 1-dimensional array.

plane = {}

-- create the master table

for k = 1,5 do

-- 5 planes

  row = {}

 

  for j = 1,4 do

-- 4 rows

    col = {}

 

    for i = 1,3 do

-- 3 columns

      col[i] = i+j+k

 

    end

 

    row[j] = col

-- row[j] is the column aray

  end

 

  plane[k] = row

-- plane[k] is the row array

end

 

list(plane)

-- list the 3-dimensional array

t = flatten(plane)

-- flatten 3-D to 1-D

list(t)

-- list the 1-dimensional array

  

The next script flattens a complex, ugly table. The original and flattened tables are listed below the script.

t = { 6, -2, 15, "a", {5,"b"}, c="5.4" }

 

list(t)

-- list the original table

tnew = flatten(t)

-- flatten the table

list(tnew)

-- list the result

Notice that all non-numeric values, keys, and sub-tables have been removed.

Original Table

Flattened Table

{

  [1]=6

  [2]=-2

  [3]=15

  [4]="a"

  [5]=

  {

    [1]=5

    [2]="b"

  }

  [c]="5.4"

}

{

  [1]=6

  [2]=-2

  [3]=15

  [4]=5

}

Related Topics

Table and Array Functions

flattenn


Mira Pro x64 Script User's Guide, Copyright Ⓒ 2023 Mirametrics, Inc. All Rights Reserved.