global
// This source code is subject to the terms of the Mozilla Public License 2.0 at https://mozilla.org/MPL/2.0/
// © marspumpkin
//@version=5
 
// @description:
// Currently in PineScript you cannot change variables from within functions because of the scope limitations.
// One way to work around that is to use Arrays.
// This Library simplifies the use of arrays as Global Variables to make your code look cleaner.
library("global")

export init(int value) => array.new_int(1, value)
export init(float value) => array.new_float(1, value)
export init(bool value) => array.new_bool(1, value)
export init(color value) => array.new_color(1, value)
export init(string value) => array.new_string(1, value)
export init(label value) => array.new_label(1, value)
export init(line value) => array.new_line(1, value)
export init(linefill value) => array.new_linefill(1, value)
export init(box value) => array.new_box(1, value)
export init(table value) => array.new_table(1, value)
   
// @function set value to first element in array. MUST call init() first.
// @param source array, value of the same type
// @returns array containing single item
export set(int[] source, int value) => array.set(source, 0, value)
export set(float[] source, float value) => array.set(source, 0, value)
export set(bool[] source, bool value) => array.set(source, 0, value)
export set(color[] source, color value) => array.set(source, 0, value)
export set(string[] source, string value) => array.set(source, 0, value)
export set(label[] source, label value) => array.set(source, 0, value)
export set(line[] source, line value) => array.set(source, 0, value)
export set(linefill[] source, linefill value) => array.set(source, 0, value)
export set(box[] source, box value) => array.set(source, 0, value)
export set(table[] source, table value) => array.set(source, 0, value)
 
// @function gets value
// @param source any type of array
// @returns first item from array
export get(int[] source) => array.get(source, 0)
export get(float[] source) => array.get(source, 0)
export get(bool[] source) => array.get(source, 0)
export get(color[] source) => array.get(source, 0)
export get(string[] source) => array.get(source, 0)
export get(label[] source) => array.get(source, 0)
export get(line[] source) => array.get(source, 0)
export get(linefill[] source) => array.get(source, 0)
export get(box[] source) => array.get(source, 0)
export get(table[] source) => array.get(source, 0)

// Sample code below:
var price = init(close)
var test = open
test_function() =>
    // test := close -> does not work
    set(price, open) // works
    
if open < close
    set(price, high) // works
    // test := close -> does not work
    test_function()
 
if barstate.islast
    label.new(x=bar_index, y=high, textcolor=color.yellow, text = str.tostring(get(price)), size=size.normal, style=label.style_none)