You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何定义PineScript方法的返回类型形式以适配const上下文?

解决Pine Script中const上下文调用方法返回类型不匹配问题

问题核心是你用method定义的make_title默认返回series string,但input.bool的title参数要求的是const string(编译期就能确定的固定值,不能随K线变化)。method是为series类型设计的,即便传入常量参数,调用后仍会返回series类型,导致类型不匹配。

解决方案:将method改为纯常量计算的函数

把make_title从method改为普通函数,并用const修饰内部固定字符,同时确保所有参数为simple类型,这样当传入常量参数时,函数会返回const string,符合input参数的要求:

// @function make_title - 生成带缩进、填充和唯一标识的标题字符串
// @param this - 待修改的原始字符串
// @param ident - 前置的特殊空格数量
// @param fill - 后置的特殊空格数量
// @param id - 后置的零宽空格数量
// @returns 处理后的常量字符串
export const function make_title(simple string this, simple int ident = 0, simple int fill = 0, simple int id = 0) =>
    const string specialSpaceCharacter = ' '
    string identStr = ''
    for i = 0 to ident > 0 ? ident - 1 : na
        identStr := identStr + specialSpaceCharacter
    string fillStr = ''
    for i = 0 to fill > 0 ? fill - 1 : na
        fillStr := fillStr + specialSpaceCharacter
    const string zeroWidthSpaceCharacter = '​'
    string idStr = ''
    for i = 0 to id > 0 ? id - 1 : na
        idStr := idStr + zeroWidthSpaceCharacter
    identStr + this + fillStr + idStr

调用方式

直接将函数结果传给input.bool的title参数即可,或者提前用const变量存储结果再传入:

// 方式1:直接调用
show = input.bool(defval = true, title = make_title('​​My Title​', ident = 2, fill = 1, id = 1))

// 方式2:提前存储为const变量(更直观)
const string formattedTitle = make_title('​​My Title​', ident = 2, fill = 1, id = 1)
show = input.bool(defval = true, title = formattedTitle)

原理说明

  • const function确保函数在编译期执行计算,返回固定的const string而非随K线变化的series类型。
  • 所有参数使用simple类型,限定只能传入常量值,保证计算过程完全基于编译期可确定的内容。

内容的提问来源于stack exchange,提问作者Jason

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 18:45:25