1 
 2 --
 3 -- Example.lua
 4 --
 5 -- This file is part of the source package that accompanies the article
 6 -- "Writing C modules for Lua" from the book "Lua Programming Gems."
 7 --
 8 -- Copyright (c) 2008
 9 -- Wim Couwenberg, Ralph Steggink
10 --
11 -- Example to echo stdin or timeout after five seconds.  Usage:
12 --
13 --     cat | lua Example.lua
14 --
15 -- (Simply typing "lua Example.lua" does not work in an OSX shell for some
16 -- reason.)
17 --
18 
19 -- Load the event module
20 require "Event"
21 
22 -- Setup an event handler.  This handler simply echos stdin and reschedules the
23 -- event or reports a timeout.
24 local function callback(event, fd, event_type)
25     if event_type == Event.EV_TIMEOUT then
26         print("timeout")
27     elseif event_type == Event.EV_READ then
28         local s = io.read("*l")
29         if s then
30             print("you typed: " .. s)
31             event:add(5)
32         end
33     end
34 end
35 
36 -- Create a read event on stdin.
37 event = Event.create(0, Event.EV_READ, callback)
38 
39 -- Add the event with a timeout of five seconds.
40 event:add(5)
41 
42 -- Start the event dispatch loop of libevent.
43 Event.dispatch()
44 
45 -- We're done.
46 print("Bye!")