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

[solved] Reading word by word in read()

Started by Moti, 13 May 2014 - 12:23 PM
Moti #1
Posted 13 May 2014 - 02:23 PM
I need to read word by word in read() function(if it is possible) or I need something else.

Example:
I wrote: "My name is SomeName"
Program after reading "My name is" and "SomeName" start a function name()
that print: "Welcome to the server SomeName"

I hope someone can help.
Edited on 14 May 2014 - 02:52 PM
CometWolf #2
Posted 13 May 2014 - 03:45 PM
This is farily straight forward, using string.gmatch.

local words ={}
for word in string.gmatch(read(),"%S+") do -- the %S pattern means any non space character
  --the variable word will represent each word in this loop
  words[#words+1] = word
end
http://lua-users.org...LibraryTutorial
Skillz #3
Posted 13 May 2014 - 05:43 PM

local function split(s)
  local words = {}
  for word in string.gmatch(tostring(s), "%S")
	table.insert(words, word)
  end
  return words
end

input = read() --> Input("My name is {@Moti}")
print("Welcome to the server " .. split(input)[4]) --> Output("Welcome to the server {@Moti}")

Pardon me, CometWolf was correct, i've appended the function, it will now work :)/>
Edited on 13 May 2014 - 07:13 PM
CometWolf #4
Posted 13 May 2014 - 06:12 PM

function split(s)
  return string.gmatch(tostring(s), "[^%s]+") -- seperates a string into a table of words, the "[^%s]+" pattern matches to every non-empty string in between space characters.
end
input = read() --> Input("My name is {@Moti}")
print("Welcome to the server " .. split(input)[4]) --> Output("Welcome to the server {@Moti}")
gmatch is an iterator function, and does not return a table, so this won't actually work. Also note my usage of the capital "s" instead of [^%s]. Though the result is the same, "%S" is obviously a lot easier. This applies to all single letter pattern classes, uppercase letters means opposite.
Moti #5
Posted 14 May 2014 - 08:50 AM
Thank you very much, this is really helpful. :)/>
Admin can lock this post.