开发者

Real-world usage of Lua co-routines/continuation serialization to simplify async logic?

The Pluto library for Lua claims to be able to serialize Lua co-routines. I interpret this as meaning 'serializeable continuations', which is an important feature for making asyncronous programming writeable in a syncronous style.

For example, a workflow can be expressed linearly instead of requiring named entry points

if (ask user is hungry) then
     if (not ask user is vegetarian) then
       if (ask user if likes_burgers) then
          feed_user(burger)
       else
          tell_user("Picky!")
     else
       feed_user(salad)

instead of

function main()
   ask(user is hungry, "hungry_response")

function hungry_response(answer)
  if (answer is yes)
     ask(user is vegetarian, "vegetarian_response")

function vegetarian_response(answer)
  if (answer is yes)
     feed_user(salad)
  else
     ask(user likes burgers, "burgers_response")

functi开发者_运维百科on burgers_response(answer)
  if (answer is yes) then
    feed_user(burger)
  else
    tell_user("Picky!")

While if statements translated into the previous style aren't bad, things get very complicated once you involve local variables, loops, nested function calls, etc.

This is where serializeable continuations become critically important.

Serialized continuations are used in JavaFlow, Cocoon (Rhink), Seaside, PLT Scheme, SICS, and are great for dealing with business workflows, medical diagnostics, and (in my case), textual adventure games.

Are there any examples (hopefully open source!) of Lua and Pluto leveraging their features in this way, using continuations to simplify logic in an async environment?


http://sheddingbikes.com/posts/1289384533.html

http://dpaste.de/Huj4/

For examples, check out Tir from a WKP ("a well-known programmer"). It simplifies, if not serializes, async operations. It is a BSD licensed micro web framework that uses Lua coroutines.

From the blog...

The magic that makes this work is Lua's coroutines. At each of the points where we call web:prompt and web:click the Tir engine yields our handler, saves it for later, and then a new request brings it back. Code that does this is basically:

function Web:recv()
    return coroutine.yield()
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜