function returning 2 values to global variable

故事扮演 提交于 2020-06-17 10:26:24

问题


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)

回答1:


My understanding is that assigning with := is not allowed for tuple-like function resturns. 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.




回答2:


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


来源:https://stackoverflow.com/questions/61302696/function-returning-2-values-to-global-variable

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!