عملگرهای تنبل
سمت راست `and`، `or` و `??` و بازوهای `if ... then ... else` فقط وقتی لازم باشند اجرا میشوند. اینجا چه چیزی را میشود با خیال راحت نوشت.
Edition 1 سمت راست and، or و ?? و بازوهای یک if ... then ... else یکخطی را فقط وقتی لازم باشد اجرا میکند. به همین دلیل فراخوانیای که حالت نگه میدارد نمیتواند مستقیماً در آنها بنشیند (E3302).
عملگرهای تنبل#
and، or و ?? سمت راستشان را فقط وقتی لازم باشد اجرا میکنند؛ عملوندهای خالص اشکالی ندارند.
Cuprel
// `and`, `or`, `??` and the two arms of `if ... then ... else` run their right side only when it is needed.
// Pure operands (plain arithmetic, comparisons, values already bound to a name) are always fine there.
indicator "Lazy operators"
edition = 1
display = price
let average = tech.sma(close, 20)
let above = close > average
let near = math.abs(close - average) < tech.atr(14)
let signal = above and near
let fallback = average ?? close
plot(if signal then fallback else na, name = "Near and above", style = circles)خواندن محافظتشده#
آزمون اندازه در سمت چپ and جلوی شکست خواندنِ سمت راست را میگیرد؛ بازویی از if-then-else که انتخاب نشده خوانده نمیشود.
Cuprel
// The right side of "and" runs only when the left side is true, and so does an arm of "if ... then ... else" that is not chosen: neither is read at all.
// That lets a guard protect a read that would fail. The array holds the rises of the close; its tenth item does not exist until ten rises have been seen,
// and the size test on the left keeps the read on the right from ever failing.
indicator "Guarded read"
edition = 1
display = pane
state gains: array<float> = array<float>()
if close > close[1]
gains.push(close - close[1])
let tenth_is_big = gains.size() > 9 and gains.at(9) > 2
let newest = if gains.size() > 0 then gains.last() else 0.0
let flag = if tenth_is_big then 1 else 0
plot(flag, name = "Tenth rise is big", style = histogram, color = color.green)
plot(newest, name = "Newest rise", color = color.blue)
plot(gains.size(), name = "Rises seen", display = none)خواندن بعد از انتهای آرایه#
بدون آزمون اندازه، عضو دهم پیش از آنکه وجود داشته باشد خوانده میشود.
Cuprel · خطا E5602
// A mistake on purpose: without the size test on the left, the tenth item is read before it exists.
indicator "Guarded read"
edition = 1
display = pane
state gains: array<float> = array<float>()
if close > close[1]
gains.push(close - close[1])
let tenth_is_big = gains.at(9) > 2
let newest = if gains.size() > 0 then gains.last() else 0.0
let flag = if tenth_is_big then 1 else 0
plot(flag, name = "Tenth rise is big", style = histogram, color = color.green)
plot(newest, name = "Newest rise", color = color.blue)
plot(gains.size(), name = "Rises seen", display = none)