File: coroutine.lua

package info (click to toggle)
widelands 2%3A1.3-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 684,084 kB
  • sloc: cpp: 196,737; ansic: 19,395; python: 8,515; sh: 1,734; xml: 700; makefile: 46; lisp: 25
file content (77 lines) | stat: -rw-r--r-- 2,359 bytes parent folder | download | duplicates (3)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
-- RST
-- coroutine.lua
-- -------------
--
-- This script contains convenience wrapper around creation and resuming
-- of coroutines and yielding proper sleeping times to widelands. These
-- functions are more specially tailored to widelands and take a lot of
-- the awkwardness out of using coroutines directly.
--
-- .. Note::
--    Do not use these functions for multiplayer scripting (scenarios and
--    winconditions) in combination with any functions in :ref:`ui.lua`
--
-- To make these functions available include this file at the beginning
-- of a script via:
--
-- .. code-block:: lua
--
--    include "scripting/coroutine.lua"
--

-- =======================================================================
--                             PUBLIC FUNCTIONS
-- =======================================================================

-- RST
-- .. function:: run(func[, ...])
--
--    Start to run a function as a coroutine and hand it over to widelands
--    for periodical resuming. All arguments passed to this function are
--    given to the coroutine when it is first run.
--
--    :arg func: Lua function to launch as a coroutine
--
--    :returns: :const:`nil`
function run(func, ...)
   local c = coroutine.create(func)
   local success, sleeptime = coroutine.resume(c, ...)
   if success then
      if coroutine.status(c) ~= "dead" then
         wl.Game():launch_coroutine(c, sleeptime)
      end
   else
      error(sleeptime)
   end
end

-- RST
-- .. function:: sleep(time)
--
--    This must be called inside a coroutine. This will put the coroutine to
--    sleep. Widelands will wake it after the given amount of time.
--
--    :arg time: time to sleep in ms
--    :type time: :class:`integer`
--
--    :returns: :const:`nil`
function sleep(time)
   coroutine.yield(wl.Game().time + time)
end

-- RST
-- .. function:: wake_me(at)
--
--    This must be called inside a coroutine. This will put the coroutine to
--    sleep. Widelands will wake it at the absolute time given. If this time is
--    already in the past (that is at < :func:`wl.Game.time`), the
--    coroutine will be woken at :func:`wl.Game.time` instead.
--
--    :arg at: when to wake this coroutine
--    :type at: :class:`integer`
--
--    :returns: :const:`nil`
function wake_me(at)
   if (at < wl.Game().time) then at = wl.Game().time  end
   coroutine.yield(at)
end