Jump to content




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


3 replies to this topic

#1 ThinkInvisible

  • Members
  • 24 posts

Posted 28 August 2012 - 02: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.

#2 Kolpa

  • New Members
  • 260 posts
  • LocationGermany

Posted 28 August 2012 - 02: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/>

#3 Grim Reaper

  • Members
  • 503 posts
  • LocationSeattle, WA

Posted 28 August 2012 - 03: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/>

#4 ThinkInvisible

  • Members
  • 24 posts

Posted 28 August 2012 - 03: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!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users