struct Proc(*T, R)

Overview

def self.on_tick(&callback : Int32 ->) # Since Proc is a {Void, Void}, we can't turn that into a Void*, so we # "box" it: we allocate memory and store the Proc there boxed_data = Box.box(callback)

# We must save this in Crystal-land so the GC doesn't collect it (*)
@@box = boxed_data

# We pass a callback that doesn't form a closure, and pass the boxed_data as
# the callback data
LibTicker.on_tick(->(tick, data) {
  # Now we turn data back into the Proc, using Box.unbox
  data_as_callback = Box(typeof(callback)).unbox(data)
  # And finally invoke the user's callback
  data_as_callback.call(tick)
}, boxed_data)

end end

Ticker.on_tick do |tick| puts tick end


Note that we save the box in `@@box`. The reason is that if we don

Defined in:

primitives.cr
proc.cr

Class Method Summary

Instance Method Summary

Instance methods inherited from struct Value

==(other) ==, dup dup

Instance methods inherited from class Object

!=(other) !=, !~(other) !~, ==(other) ==, ===(other)
===(other : YAML::Any)
===(other : JSON::Any)
===
, =~(other) =~, class class, crystal_type_id crystal_type_id, dup dup, hash hash, inspect(io : IO)
inspect
inspect
, itself itself, not_nil! not_nil!, tap(&block) tap, to_json to_json, to_pretty_json(indent : String = " ")
to_pretty_json(io : IO, indent : String = " ")
to_pretty_json
, to_s
to_s(io : IO)
to_s
, to_yaml
to_yaml(io : IO)
to_yaml
, try(&block) try

Class methods inherited from class Object

==(other : Class) ==, ===(other) ===, cast(other) : self cast, clone clone, dup dup, from_json(string_or_io) : self
from_json(string_or_io, root : String) : self
from_json
, from_yaml(string : String) : self from_yaml, hash hash, inspect(io) inspect, name : String name, nilable? nilable?, to_s(io) to_s, |(other : U.class) |

Class Method Detail

def self.new(pointer : Pointer(Void), closure_data : Pointer(Void)) #

[View source]

Instance Method Detail

def ==(other : self) #

[View source]
def ===(other : self) #

[View source]
def ===(other) #

[View source]
def arity #

Returns the number of arguments of this Proc.

add = ->(x : Int32, y : Int32) { x + y }
add.arity # => 2

neg = ->(x : Int32) { -x }
neg.arity # => 1

[View source]
def call(*args : *T) : R #

Invokes this Proc and returns the result.

add = ->(x : Int32, y : Int32) { x + y }
add.call(1, 2) # => 3

[View source]
def clone #

[View source]
def closure? #

[View source]
def closure_data #

[View source]
def hash #

[View source]
def partial(*args : *U) #

Returns a new Proc that has its first arguments fixed to the values given by args.

See Wikipedia, Partial application

add = ->(x : Int32, y : Int32) { x + y }
add.call(1, 2) # => 3

add_one = add.partial(1)
add_one.call(2)  # => 3
add_one.call(10) # => 11

add_one_and_two = add_one.partial(2)
add_one_and_two.call # => 3

[View source]
def pointer #

[View source]
def to_s(io) #

[View source]