This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Jman's profile picture

Pulling two potential variables from a single write ()

Started by Jman, 12 February 2014 - 11:13 AM
Jman #1
Posted 12 February 2014 - 12:13 PM
Okay so im am trying to pull two variables from a single write line but every time I think I have figured out I find a flaw in the idea. I really would like to just make one write line and have the user put in two variables EX:
  function w(x)
  turtle.forward(x)
end

write("which direction and how far? :")
mv = read ("", ..d)
--[[User types in: Forward 10
if mv == "forward" then
  p(d)
  print ("Okay, moving forward "..d.." blocks")
end  

This is my goal to achieve. To leanr how to accomplish this without doing:
 write ("Which direction:")
dir = read ()

if dir == "forward" then
  write ("how far:")
  dis = tostring.number(read ())
  W(dis)
Elsif dir == ...ect
end 
I have ran out of possible solutions and need to achieve this in order to carry out my next couple of program ideas. If someone could help by lending alittle of their knowledge and brain power to help me achieve this I would be forever grateful. Thanks.
Edited on 12 February 2014 - 11:21 AM
CometWolf #2
Posted 12 February 2014 - 12:27 PM
There's 2 ways to do this

The way i'd do it, using string.gmatch, as this is far more adaptable

local tWords = {} -- create a table
for word in string.gmtach(read(),"%S+") do -- iterrate through the string passed by read(), returning every string of characters not containing "%S" (not space) seperately.
  tWords[#tWords] = word -- these words are then stored in the table
end
print(tWords[1],tWords[2]) -- call the words stored in the table.

or using string.match

local input = read()
local command = input:match"^%a+"
local amount = input:match"%d+$"
If you want to learn what im doing here, i'd suggest you check out the string librairy
http://lua-users.org/wiki/StringLibraryTutorial