Jump to content




Splitting a string?


  • You cannot reply to this topic
3 replies to this topic

#1 Zudo

  • Members
  • 800 posts
  • LocationUK

Posted 11 July 2013 - 01:14 AM

I need to split a string, as I have a table which contains something like this:
{["item1"]="something,something else,even more!"}

How can I change this:

"something,something else,even more!


Into these seperate strings:

"something"
"something else"
"even more!"


#2 darkrising

  • Members
  • 234 posts
  • LocationScotland

Posted 11 July 2013 - 03:11 AM

Try this
function split(str, pattern) -- Splits string by pattern, returns table
  local t = { }
  local fpat = "(.-)" .. pattern
  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

so you would pass it your string:
aTable = split(theString, ",")

It would return each value in the table,
aTable[1] would be "something" etc etc

#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 11 July 2013 - 03:15 AM

What darkrising posted would work, here is a more efficient function, with a smaller footprint. It uses patterns.

local function split( str, patt )
  local t = {}
  for s in str:gmatch("[^"..patt.."]+") do
    t[#t+1] = s
  end
  return t
end


#4 Zudo

  • Members
  • 800 posts
  • LocationUK

Posted 11 July 2013 - 10:26 AM

OK, thanks





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users