Bjorn Mistiaen
Bjorn Mistiaen

Reputation: 6905

function returning 2 values to global variable

In light of this post I'd like to ask why the script hereunder works for [a,b] but doesn't work for [c,d].
Cannot find any documentation that explains why this doesn't work.

This example is only for 2 return values, but in reality I'm going to create a function with 6 or more variables to be returned in one go.
I'm trying to avoid having to enter 6 different lines, because I'll be entering this data every trading day (the function will be date-depentent and I already have code for that).
So I'd like to only have to enter 1 line per day to keep the source code clear and maintainable.

//@version=4
study("Functions test")

var int c = na
var int d = na

f(x) => [x,x+5]

[a,b] = f(20)
[c,d] := f(30)

plot(a)
plot(b)
plot(c)
plot(d)

Upvotes: 3

Views: 8161

Answers (2)

Glauco Esturilio
Glauco Esturilio

Reputation: 383

My understanding is that assigning with := is not allowed for tuple-like function returns. If you want to avoid entering multiple times the function input, in this case, 20 and 30, while keeping the variable definition as it is, you can still do something like:

//@version=4
study("Functions test")

var int c = na
var int d = na

f(x) => [x,x+5]

[a,b] = f(20)
[c1,d1] = f(30)

c := c1
d := d1

plot(a)
plot(b)
plot(c)
plot(d)

It does require several extra lines, and looks ugly, but at least you limit to one the number of times you have to type the input to the function as desired.

Upvotes: 11

Mayank Jain
Mayank Jain

Reputation: 3205

Your solution helped alot. I was trying to switch calling a function based on a boolean input - which were returning same type of tuples.

I ended up using code like this

//@version=4
study("COT weekly change (makuchaku)")
isCommodity = true
symbol = "xx"

float oi = na
float asset_mgr = na

cot_data_financials(symbol) =>
    oi = 1
    asset_mgr = 2
    [oi, asset_mgr]

cot_data_commodities(symbol) =>
    oi = 3
    asset_mgr = 4
    [oi, asset_mgr]


// [oi, asset_mgr] = (isCommodity ? cot_data_financials(symbol) : cot_data_commodities(symbol))
if isCommodity
    [_oi, _asset_mgr] = cot_data_commodities(symbol)
    oi := _oi
    asset_mgr := _asset_mgr
else
    [_oi, _asset_mgr] = cot_data_financials(symbol)
    oi := _oi
    asset_mgr := _asset_mgr

plot(oi) // plots 3
plot(asset_mgr) // plots 4

Upvotes: 7

Related Questions