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

Seperate String

Started by Left, 21 March 2013 - 07:10 PM
Left #1
Posted 21 March 2013 - 08:10 PM
Hello,

I have a string that will look something like: Linearus:true:50:y0owsb8 but I don't quite know how I can seperate this up into the 4 parts seperated by the colon.

Just a bit of probably unneeded information, the first section is username, seccond auth status, third credits and fourth is a ckey.

Thanks, Linearus
theoriginalbit #2
Posted 21 March 2013 - 08:19 PM
The string split function I use when needing to do tasks like this

local function split_string(str, pat)
  local t = {}
  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

Usage example

local details = split_string( 'Linearus:true:50:y0owsb8', ':' )

print('username: '..details[1])
print('authStat: '..details[2])
print('credits: '..details[3])
print('ckey: '..details[4])
Kingdaro #3
Posted 21 March 2013 - 08:37 PM
I would prefer to use gmatch.


local data = {}

for part in string.gmatch('Linearus:true:50:y0owsb8','[^:]+') do
  table.insert(data, part)
end

-- etc
theoriginalbit #4
Posted 21 March 2013 - 08:42 PM
I would prefer to use gmatch.


local data = {}

for part in string.gmatch('Linearus:true:50:y0owsb8','[^:]') do
  table.insert(data, part)
end
That will just split each character into the table without the ':' characters.

{ 'L', 'i', 'n', 'e', 'a', 'r', 'u', 's', 't', 'r', 'u', 'e', --[[ etc ]] }
Kingdaro #5
Posted 21 March 2013 - 09:45 PM
Whoops. The match string should have a "+" at the end of it.
theoriginalbit #6
Posted 21 March 2013 - 09:51 PM
Whoops. The match string should have a "+" at the end of it.
much better :P/>
Kingdaro #7
Posted 21 March 2013 - 09:53 PM
Yep. That's programming. One missing/extra character will indeed screw everything over. :lol:/>