lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On Tue, Feb 07, 2006 at 08:39:48AM +1100, Matthew Percival wrote:
> G'Day,
> 
> 	I have been searching around on this topic, and have not come up with
> anything substantial, so I suspect there is currently no option for
> this, but I thought it best to ask, in case a skilled Lua programmer
> knows a way.  Quite simply, I want to check stdin to see if there is
> anything currently buffered, and only perform stdin:read() if there is.
> As a simple example:
> 
> i = 1
> while (i != 0) do
> 	if (stdin:read("*ready")) then -- somehow test if it's ready
> 		i = stdin:read("*all")
> 	else
> 		print "Looping again...\n"
> end
> 
> 	So, if the user ever types a 0, the loop will exit; if the user types
> nothing, it will continually print on the screen.  Perhaps a bad
> example, but a nice, simple one.  Can this be done, or would something
> like this have to be written in first?
> 
> Thanks,
> 
> Matthew
> 
if you really want to do idle waiting then setting
the file descriptor nonblocking should do;
most implementations of stdio should then return
nothing read or an error (instead of looping internally).

On *nix, using a wrapper like nb.c:
#include <fcntl.h>
#include <unistd.h>
int main (int argc, char **argv)
{
	fcntl(0, F_SETFL, O_NONBLOCK);
	return execvp(argv[1], argv+1);
}

you can have
nb lua -e 'while (not io.stdin:read(1)) do print "." end'
print dots until there is some input.

Another problem may be to have your terminal deliver
a single character without waiting for a newline.
Add some ioctls to the wrapper, or use
stty raw; nb lua -e '...'; stty sane


cheers