simple events and triggers in interpreter
This commit is contained in:
parent
950c77b127
commit
8183dfd6b1
35
lib/eventable.rb
Normal file
35
lib/eventable.rb
Normal file
@ -0,0 +1,35 @@
|
||||
# A simple event registering/triggering module to mix into classes.
|
||||
# Events are stored in the `@events` ivar.
|
||||
module Eventable
|
||||
|
||||
# Register a handler for the given event name.
|
||||
#
|
||||
# obj.on(:foo) { puts "foo was called" }
|
||||
#
|
||||
# @param [String, Symbol] name event name
|
||||
# @return handler
|
||||
def on(name, &handler)
|
||||
event_table[name] << handler
|
||||
handler
|
||||
end
|
||||
|
||||
def off(name, handler)
|
||||
event_table[name].delete handler
|
||||
end
|
||||
|
||||
def event_table
|
||||
return @event_table if @event_table
|
||||
@event_table = Hash.new { |hash, key| hash[key] = [] }
|
||||
end
|
||||
|
||||
# Trigger the given event name and passes all args to each handler
|
||||
# for this event.
|
||||
#
|
||||
# obj.trigger(:foo)
|
||||
# obj.trigger(:foo, 1, 2, 3)
|
||||
#
|
||||
# @param [String, Symbol] name event name to trigger
|
||||
def trigger(name, *args)
|
||||
event_table[name].each { |handler| handler.call(*args) }
|
||||
end
|
||||
end
|
@ -1,10 +1,34 @@
|
||||
|
||||
require "eventable"
|
||||
|
||||
class Interpreter
|
||||
include Eventable
|
||||
|
||||
attr_accessor :instruction
|
||||
attr_accessor :block
|
||||
attr_accessor :registers
|
||||
|
||||
def initialize
|
||||
@registers = Hash[(0...12).collect{|i| ["r#{i}" , "undefined"]}]
|
||||
end
|
||||
|
||||
def start block
|
||||
set_block block
|
||||
end
|
||||
def set_block block
|
||||
return if @block == block
|
||||
@block = block
|
||||
trigger(:block, block)
|
||||
set_instruction block.codes.first
|
||||
end
|
||||
def set_instruction i
|
||||
return if @instruction == i
|
||||
@instruction = i
|
||||
trigger(:instruction, i)
|
||||
end
|
||||
def tick
|
||||
name = @instruction.class.name.split("::").last
|
||||
send "execute_#{name}"
|
||||
end
|
||||
|
||||
end
|
||||
|
Loading…
Reference in New Issue
Block a user