Re: Using Gets()

new topic     » goto parent     » topic index » view thread      » older message » newer message

gets() gets characters until an end-of-line character <enter> or ctl-z is received.

So I'm guessing that isn't what you want, since there's no way to count the characters until the line is terminated and returned, and gets() won't recognize arrow key codes, just printable characters. It basically means "get_string"

There are actually two questions here:

First, how to get up to 12 characters, but no more, and second, how to catch the arrow keys.

You could get a character at a time, keeping track of how many you have, until you encounter an <enter> or reach the maximum of 12.

This can be done with get_key() in a loop. get_key() continually returns -1 until a key is pressed, so you ignore those. When a key is pressed, get_key() returns a key code > 0. Valid character codes begin at 48. Below that, the code indicates a control key. The <enter> key code, for example, is 10.

You'll also want to trap the arrow keys. On Linux terminals, those keys actually return 3 integers, beginning with <esc> which is code 27. If get_key() returns a 27, then you want to do 2 more get_key()s, to retrieve the 2nd and 3rd codes, which will let you determine which arrow key was pressed. For example, {27,91,68} would be a left arrow, and {27,91,67} would be right arrow.

Sounds complicated? Yep. That's why people prefer to program with a GUI, where such things are simple.

Someone will probably have a neater way of doing this, but here's a quick and dirty implementation:

(Edited to add variable length parameter per Pete's post.)

function get_input_at(integer x, integer y, integer len) 
object key 
sequence key_sequence = {}  
 
position(x,y)  
 
while 1 do 
key = get_key()  
if key = 27 then -- an arrow or other control key 
   key &= get_key() 
   key &= get_key()  
-- ? key  -- uncomment this to see the other control key values 
   if equal({27,91,68}, key) then 
      return "LEFT ARROW" -- or do whatever  
   end if 
   if equal({27,91,67}, key) then  
      return "RIGHT ARROW"  
   end if 
elsif key = 10 then return key_sequence -- enter key found 
elsif key > 47 then 
   puts(1,key) -- display it, starting at the x,y point 
   key_sequence &= key -- add it to return value 
   if length(key_sequence) >= len then exit end if -- enough already! 
end if 
end while 
 
return key_sequence 
end function 
 
object x = get_input_at(24,50,12) 
new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu