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

Splitting a string?

Started by Zudo, 11 July 2013 - 12:14 AM
Zudo #1
Posted 11 July 2013 - 02: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!"
darkrising #2
Posted 11 July 2013 - 04: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
theoriginalbit #3
Posted 11 July 2013 - 04: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
Zudo #4
Posted 11 July 2013 - 11:26 AM
OK, thanks