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

reading pieces of/splitting a string

Started by uh20, 30 January 2013 - 02:02 AM
uh20 #1
Posted 30 January 2013 - 03:02 AM
hey, ive been having troubles splitting a line from file:read() into pieces (basically i want to know how to edit a string)

for example, how would you split this
line = "12345678"
value[1] = "12"
value[2] = "34"
value[3] = "56"
and so on…

this seems like an easy thing to do, but the search engines have dubiously failed to return any answers.
thanks in advance.
Lyqyd #2
Posted 30 January 2013 - 03:42 AM
Split into new topic.
theoriginalbit #3
Posted 30 January 2013 - 03:43 AM
To extract characters when when know where they will be

local s = "This is a string"
print( string.sub( s, 2 ) )	 -- Output: his is a string
print( string.sub( s, 2, 6 ) )  -- Output: his i
print( s:sub( 2, 6 ) )		  -- Output: his i
NOTE: The 3rd code example does the same as the second, its just written differently

To get the parts of a string when the only thing we know is a common character

function split( str, regex )
  local t = { }
  local fpat = "(.-)"..regex
  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

local s = "This is a string"
local tableOfParts = split( s, " " )
This will give us a table containing the following data
"This"
"is"
"a"
"string"

the basics of this one is it goes through the string looking for the pattern suppled, when found it will add the string between those patterns and add them to a table. certain characters like "." require a % in front making the search pattern "%."
Edited on 30 January 2013 - 02:46 AM
uh20 #4
Posted 01 February 2013 - 03:00 AM
OK
i thought string.sub only did substitutions, guess it can also read specific parts of a line as well
theoriginalbit #5
Posted 01 February 2013 - 03:03 AM
no string.sub doesn't do substitutions. thats string.gsub. string.sub stands for string.substring

string.sub("hello",3) is from the 3rd character to the end ("llo")
string.sub("hello",3,4) is from the 3rd to the 4th character ("ll")
string.sub("hello",3,3) is the 3rd character in the string ("l")

More info can be found here: http://lua-users.org/wiki/StringLibraryTutorial
uh20 #6
Posted 01 February 2013 - 03:10 AM
ok, thats what i got mixed up them ;)/>
was needing this for reading a reboot-file, so the computer can tell what storage carts where after turning off.