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

[Solved] Is there an easier way to do this? (getwords)

Started by ThinkInvisible, 28 August 2012 - 01:22 PM
ThinkInvisible #1
Posted 28 August 2012 - 03:22 PM
function getwords(str)
	 newstr = {}
	num = 0
	for word in string.gmatch(str, "%a+") do
		table.insert(newstr, word)
	end
	return newstr
end
I'm trying to make a function that separates a string into an array containing every word in the string. I'm pretty new with arrays, but I found this string.gmatch function online that looks promising. Is this function default and/or is there an easier way?


Solved. Apparently that code just isn't going to work and Lua already wrote something to do exactly what I'm trying to do.
Kolpa #2
Posted 28 August 2012 - 03:30 PM
you can do

table.insert(newstr,word)
instead of
newstr[num] = word
num = num + 1

and its actually a table not an array :D/>/>
Grim Reaper #3
Posted 28 August 2012 - 04:14 PM
You could try to use the split join method that was already written by our good friends at LUA :D/>/>

This method splits a string by a certain pattern into a table and then returns said table:

-- Compatibility: Lua-5.1
function split(str, pat)
   local t = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pat
   local last_end = 1
   local s, e, cap = str:find(fpat, 1)
   while s do
	  if s ~= 1 or cap ~= "" then
  table.insert(t,cap)
	  end
	  last_end = e+1
	  s, e, cap = str:find(fpat, last_end)
   end
   if last_end <= #str then
	  cap = str:sub(last_end)
	  table.insert(t, cap)
   end
   return t
end
I DID NOT WRITE THIS!
^^ Code taken directly from http://lua-users.org/wiki/SplitJoin

How you would apply this for splitting a word is calling the split method with a pattern of space:

local sSentence = "This is a cool string!"
local tWords = {}

tWords = split( sSentence, " " ) -- Split the string by spaces.

-- Print out the table.
for index,value in ipairs( tWords ) do
  print( tWords[i] )
end

-- OUTPUT --
This
is
a
cool
string!
----------------

Hope I helped! :P/>/>
ThinkInvisible #4
Posted 28 August 2012 - 04:16 PM
Any numbers included in str are converted to nil for some reason, and just ignored. I'll try the split thing.

Ex:
getwords("string one") returns {"string", "one"}
getwords("string 2") returns {"string"} (i think)

The split thing worked perfectly. Thanks!