如何在 Pine 脚本中创建自定义类?

Mar*_*ola 3 pine-script

是否可以在 Pine 中创建自定义类以及如何创建一个?我在网上搜索了如何在 Pine Script 中创建类,但没有找到任何页面。

下面是一个用 Python 编写的类示例:

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)
Run Code Online (Sandbox Code Playgroud)

ozm*_*ozm 5

从 v5 开始,Pine Script 不支持类。类型是 Pine 脚本中最接近类的东西。

例如:

// @version=5
library('mylib')

// Custom types can only have attributes. No methods are allowed.
export type person        // lower first case is just a convention as seen in builtin objects
    string  name
    int     age
    over18  boolean
    bool    isVip = false // Only constant literals, no expressions historical access allowed in default value.

export new(string name, int age) =>
    isOver18 = age >= 18
    person   = person.new(name, age, isOver18)
    person
Run Code Online (Sandbox Code Playgroud)

发布库后,您可以按如下方式使用它。(您不必将其设为库,只需将其添加到代码中即可,但是当用作库时,它更接近于类。)

import your_username/mylib/1

// Create with our factory/constructor
john         = mylib.new("John", 25)
isJohnOver18 = john.over18                  // true

// Unfortunately there is nothing to prevent direct object creation
mike         = mylib.person.new("Mike", 25) // Create object with type's builtin constructor.
isMikeOver18 = mike.over18                  // na

Run Code Online (Sandbox Code Playgroud)

编辑:我目前看到奇怪的行为,我无法理解使用类型参数并访问其历史价值时的原因。请参阅下面的示例:


weirdFunction(person user) =>
    // This is somehow not working as expected in the function.
    // However it works flawlessly in a global context.
    previousAge = user.age[1] // Gets wrong value

// Workaround

correctFunction(person user) =>
    previousUser = user[1]
    previousAge = previousUser.age
Run Code Online (Sandbox Code Playgroud)