Lua timing thread - multithreading

How do I write a thread, or a co-routine (correct my nomenclature) to execute one function in Lua while the mainline code looks at its results and makes decisions ?
What I want is a function, something like
-----------------------------------------------------------
-- Countdown_Nine_Seconds() --
-- --
-- On Entry: Nothing --
-- --
-- Returns: Nothing --
-- --
-- Action: Decrements these two counters... --
-- --
-- Full_Wait --
-- Tenth_Wait --
-----------------------------------------------------------
function Countdown_Ten_Seconds()
Full_Wait = 9 -- This will be a global
local i
local j
for i = 9, 0, -1
do -- This is the I loop start
Tenth_Wait = 10 -- ten tenths in a second
for j = 10, 0, -1
do -- This is the J loop start
box.wait(100) -- our implementation has this; wait 0.1 seconds
Tenth_Wait = Tenth_Wait - 1 -- Tell the rest of the world
end -- end of inner J-Loop
Full_Wait = Full_Wait - 1 -- One less second
end -- end of ouer I-Loop
end -- end of this complete function
I would then like to have a main line code do something like
While(Full_Wait > 0)
do
:
:
:
(my stuff here)
:
:
:
:
end
What's the syntax ? Where do I read about this ?
What else am I missing ?

lua co-routines are collaboratively threaded. They need to explicitly yield control to one another. They don't run at the same time.
If you need preemptive threading you need one of the various lua threading libraries.

Related

Haskell recursion loop counter

Is there anyway I could check the number of recursion the program is at. For example, I want to stop the recursion after 2 times. Is there anyway to do that in haskell.
Yes, there is but...
Stopping recursion is normally done when some final state is achieved, something like "I've run out of data to process" or "I have reached the base case." When I see something as arbitrary as "after 2 times" I want to ask where you came up with 2.
However in the interest of answering the question asked:
You need to pass in a counter to the recursive function and bail out when you have done the required number of cycles. For cases like this where the number of cycles is not a matter external to the function, it is typically the case that one creates an auxilary function to introduce it.
myFunction :: Value -> Value
myFunction init = recurse 2 init
where
recurse :: Int -> Value -> Value
recurse 0 result = result
recurse n intermediate = recurse (n-1) (someFun intermediate)

Named documentation chunk with Haddock

I'm trying to document my sources and I have a problem with named chunk.
I would like to document a large amount of patterns (more than 50), I would like to keep each explanation near the code and gather all the explanations in the header
I tried the following :
module Haddock
(
-- A test for Haddock named chunk
--
-- $doc1
--
-- $doc2
--
-- $doc3
)
where
-- $doc1
-- First serie of explanations
myFunction 0 = 1
myFunction 1 = 1
-- $doc2
-- Second serie of explanations
myFunction 2 = 3
-- $doc3
-- Some examples
--
-- > myFunction a
--
myFunction a = a * a
but only the first chunk is shown :
Is there something wrong with my Haddock markup or is it a bug ?

Lua, Advancing to the next letter of the alphabet

I am very surprised that I did not find this explicitly answered here in StackOverflow, or on the Lua.org Website
If
My Lua variable contains a single letter, and
I want the next letter in the alphabet
Then, how do I manipulate that variable to change from, say, "J" to "K" ?
I looked at The String Library in the Lua.Org website, and didn't see the word "alphabet" on any of the pages there
e.g.
--------------------------------------------------
-- --
-- Func Name: Alphabetic_Advance_By_1 --
-- --
-- On Entry: The_Letter contains one --
-- character. It must be a --
-- letter in the alphabet. --
-- --
-- On Exit: The caller receives the --
-- next letter --
-- --
-- e.g., --
-- --
-- A will return B --
-- B will return C --
-- C will return D --
-- --
-- X will return Y --
-- Y will return Z --
-- Z will return A --
-- --
-- --
-- --
--------------------------------------------------
function Alphabetic_Advance_By_1(The_Letter)
local Temp_Letter
Temp_Letter = string.upper(The_Letter)
-- okay, what goes here ???
return(The_Answer)
end
I am very surprised that I did not find this explicitly answered here in StackOverflow, or on the Lua.org Website
It has to do with the character encodings used in your particular build of Lua, so it's beyond the scope of the Lua language proper.
You can use string.byte to get the byte(s) of a string. You can use string.char to turn bytes into a string.
Lua doesn't guarantee that the character codes for 'A' through 'Z' are contiguous, because C doesn't. You can't even be sure that each is encoded with a single byte. If your implementation is using ASCII then each character is represented by a single byte value and you can add 1 get the next letter, but you shouldn't rely on this. For example, if Temp_Letter < 'Z':
The_Answer = string.char(Temp_Letter:byte() + 1)
Here's a way to do this without relying on character encoding:
local alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
local index = alphabet:find(Temp_Letter)
if index then
index = (index % #alphabet) + 1 -- move to next letter, wrapping at end
TheAnswer = alphabet:sub(index, index)
end

can xmonad's logHook be run at set intervals rather than in (merely) response to layout events?

I'm using dynamicLogWithPP from XMonad.Hooks.DynamicLog together with dzen2 as a status bar under xmonad. One of the things I'd like to have displayed in the bar is the time remaining in the currently playing track in audacious (if any). Getting this information is easy:
audStatus :: Player -> X (Maybe String)
audStatus p = do
info <- liftIO $ tryS $ withPlayer p $ do
ispaused <- paused
md <- getMetadataString
timeleftmillis <- (-) <$> (getCurrentTrack >>= songFrames) <*> time
let artist = md ! "artist"
title = md ! "title"
timeleft = timeleftmillis `quot` 1000
(minutes, seconds) = timeleft `quotRem` 60
disp = artist ++ " - " ++ title ++ " (-"++(show minutes)++":"++(show seconds)++")" -- will be wrong if seconds < 10
audcolor False = dzenColor base0 base03
audcolor True = dzenColor base1 base02
return $ wrap "^ca(1, pms p)" "^ca()" (audcolor ispaused disp)
return $ either (const Nothing) Just info
So I can stick that in ppExtras and it works fine—except it only gets run when the logHook gets run, and that happens only when a suitable event comes down the pike. So the display is potentially static for a long time, until I (e.g.) switch workspaces.
It seems like some people just run two dzen bars, with one getting output piped in from a shell script. Is that the only way to have regular updates? Or can this be done from within xmonad (without getting too crazy/hacky)?
ETA: I tried this, which seems as if it should work better than it does:
create a TChan for updates from XMonad, and another for updates from a function polling Audacious;
set the ppOutput field in the PP structure from DynamicLog to write to the first TChan;
fork the audacious-polling function and have it write to the second TChan;
fork a function to read from both TChans (checking that they aren't empty, first), and combining the output.
Updates from XMonad are read from the channel and processed in a timely fashion, but updates from Audacious are hardly registered at all—every five or so seconds at best. It seems as if some approach along these lines ought to work, though.
I know this is an old question, but I came here looking for an answer to this a few days ago, and I thought I'd share the way I solved it. You actually can do it entirely from xmonad. It's a tiny bit hacky, but I think it's much nicer than any of the alternatives I've come across.
Basically, I used the XMonad.Util.Timer library, which will send an X event after a specified time period (in this case, one second). Then I just wrote an event hook for it, which starts the timer again, and then manually runs the log hook.
I also had to use the XMonad.Util.ExtensibleState library, because Timer uses an id variable to make sure it's responding to the right event, so I have to store that variable between events.
Here's my code:
{-# LANGUAGE DeriveDataTypeable #-}
import qualified XMonad.Util.ExtensibleState as XS
import XMonad.Util.Timer
...
-- wrapper for the Timer id, so it can be stored as custom mutable state
data TidState = TID TimerId deriving Typeable
instance ExtensionClass TidState where
initialValue = TID 0
...
-- put this in your startupHook
-- start the initial timer, store its id
clockStartupHook = startTimer 1 >>= XS.put . TID
-- put this in your handleEventHook
clockEventHook e = do -- e is the event we've hooked
(TID t) <- XS.get -- get the recent Timer id
handleTimer t e $ do -- run the following if e matches the id
startTimer 1 >>= XS.put . TID -- restart the timer, store the new id
ask >>= logHook.config -- get the loghook and run it
return Nothing -- return required type
return $ All True -- return required type
Pretty straightforward. I hope this is helpful to someone.
It cannot be done from within xmonad; xmonad's current threading model is a bit lacking (and so is dzen's). However, you can start a separate process that periodically polls your music player and then use one of the dzen multiplexers (e.g. dmplex) to combine the output from the two processes.
You may also want to look into xmobar and taffybar, which both have better threading stories than dzen does.
With regards to why your proposed TChan solution doesn't work properly, you might want to read the sections "Conventions", "Foreign Imports", and "The Non-Threaded Runtime" at my crash course on the FFI and gtk, keeping in mind that xmonad currently uses GHC's non-threaded runtime. The short answer is that xmonad's main loop makes an FFI call to Xlib that waits for an X event; this call blocks all other Haskell threads from running until it returns.

Mutual recursion -- can someone help explain how this code works?

I'm reading through "A Gentle Introduction to Haskell," and early on it uses this example, which works fine in GHC and horribly in my brain:
initial = 0
next resp = resp
process req = req+1
reqs = client initial resps
resps = server reqs
server (req:reqs) = process req : server reqs
client initial ~(resp:resps) = initial : client (next resp) resps
And the calling code:
take 10 reqs
How I'm seeing it, is reqs is called, yielding a call to client with args 0 and resps. Thus wouldn't resps now need to be called... which in turn calls reqs again? It all seems so infinite... if someone could detail how it's actually working, I'd be most appreciative!
I find that it's usually worthwhile to work out the behavior of small Haskell programs by hand. The evaluation rules are quite simple. The key thing to remember is that Haskell is non-strict (aka lazy): expressions are evaluated only when needed. Laziness is the reason seemingly infinite definitions can yield useful results. In this case, using take means we will only need the first 10 elements of the infinite list reqs: they are all we "need".
In practical terms, "need" is generally driven by pattern matches. E.g., a list expression will generally be evaluated up to the point where we can distinguish between [] and (x:xs) before function application. (Note that a '~' preceding a pattern , as in the definition of client, makes it lazy (or irrefutable): a lazy pattern won't force its argument until the whole expression is forced.)
Remembering that take is:
take 0 _ = []
take n (x:xs) = x : take (n-1) xs
The evaluation of take 10 reqs looks like:
take 10 reqs
-- definition of reqs
= take 10 (client initial resps)
-- definition of client [Note: the pattern match is lazy]
= take 10 (initial : (\ resp:resps' -> client (next resp) resps')
resps)
-- definition of take
= initial : take 9 ((\ resp:resps' -> client (next resp) resps')
resps)
-- definition of initial
= 0 : take 9 ((\ resp:resps' -> client (next resp) resps')
resps)
-- definition of resps
= 0 : take 9 ((\ resp:resps' -> client (next resp) resps')
(server reqs))
-- definition of reqs
= 0 : take 9 ((\ resp:resps' -> client (next resp) resps')
(server (client initial resps)))
-- definition of client
= 0 : take 9 ((\ resp:resps' -> client (next resp) resps')
(server (initial : {- elided... -}))
-- definition of server
= 0 : take 9 ((\ resp:resps' -> client (next resp) resps')
(process initial : server {-...-}))
-- beta reduction
= 0 : take 9 (client (next (process initial)) (server {-...-})
-- definition of client
= 0 : take 9 (next (process initial) : {-...-})
-- definition of take
= 0 : next (process initial) : take 8 {-...-}
-- definition of next
= 0 : process initial : take 8 {-...-}
-- definition of process
= 0 : initial+1 : take 8 {-...-}
-- definition of initial
= 0 : 1 : take 8 {-...-}
-- and so on...
Understanding this code requires two skills:
distinguishing between 'definition', which may be infinite (like the set of natural numbers: naturals = (1 : map '\n->n+1' naturals), or the list of processed requests) and 'reduction', which is the process of mapping actual data to these definitions
seeing the structure of this client-server application: it's just a pair of processes talking to eachother: 'client-server' is a bad name, really: it should have been called 'wallace-gromit' or 'foo-bar', or talking philosophers or whatever, but it's symmetrical: the two parties are peers.
As Jon already stated, reduction works in a lazy way (aka 'call by need'): take 2 naturals would not first evaluate the complete set of naturals, but just take the first one, and prepend that to take 1 (map '\n->n+1' naturals), which would reduce to [1,(1+1) ] = [1,2].
Now the structure of the client server app is this (to my eye):
server is a way to create a list of responses out of a list of requests by using the process function
client is a way to create a request based on a response, and append the response of that request to the list of responses.
If you look closely, you see that both are 'a way to create x:xs out of y:ys'. So we could evenly call them wallace and gromit.
Now it would be easy to understand if client would be called with just a list of responses:
someresponses = wallace 0 [1,8,9] -- would reduce to 0,1,8,9
tworesponses = take 2 someresponses -- [0,1]
If the responses are not literally known, but produced by gromit, we can say
gromitsfirstgrunt = 0
otherresponses = wallace gromitsfirstgrunt (gromit otherresponses)
twootherresponses = take 2 otherresponses -- reduces to [0, take 1 (wallace (gromit ( (next 0):...) )]
-- reduces to [0, take 1 (wallace (gromit ( 0:... ) ) ) ]
-- reduces to [0, take 1 (wallace (1: gromit (...) ) ) ]
-- reduces to [0, take 1 (1 : wallace (gromit (...) ) ) ]
-- reduces to [0, 1 ]
One of both peers needs to 'start' the discussion, hence the initial value provided to wallace.
Also note the ~ before the pattern of gromit: this tells Haskell that the contents of the list argument don't need to be reduced - if it sees it's a list, that's enough. There's a nice topic on that in a wikibook on Haskell (look for "Lazy Pattern Matching).
It's been a while since I've played with Haskell, but I'm pretty sure that it's lazily evaluated, meaning it only calculates what it actually needs. So while reqs is infinitely recursive, since take 10 reqs only needs the first 10 elements of the list returned, that is all that is actually calculated.
It looks like nice obfuscation. If you read precisely you found it simple:
next? it's identity
server? it's simply map process which is map '\n->n+1'
client? It's obscure way how to write 0 : server client e.g. 0 : map '\n->n+1' [0: map '\n->n+1' [0:...]]

Resources