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.crproc.cr
Class Method Summary
Instance Method Summary
- #==(other : self)
- #===(other : self)
- #===(other)
-
#arity
Returns the number of arguments of this Proc.
-
#call(*args : *T) : R
Invokes this Proc and returns the result.
- #clone
- #closure?
- #closure_data
- #hash
-
#partial(*args : *U)
Returns a new Proc that has its first arguments fixed to the values given by args.
- #pointer
- #to_s(io)
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) : selffrom_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
Instance Method Detail
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
def call(*args : *T) : R
#
Invokes this Proc and returns the result.
add = ->(x : Int32, y : Int32) { x + y }
add.call(1, 2) # => 3
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