Jump to content




Seperate String


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

#1 Left

  • Members
  • 88 posts

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

#2 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

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])


#3 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

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


#4 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 21 March 2013 - 08:42 PM

View PostKingdaro, on 21 March 2013 - 08:37 PM, said:

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 ]] }


#5 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

Posted 21 March 2013 - 09:45 PM

Whoops. The match string should have a "+" at the end of it.

#6 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 21 March 2013 - 09:51 PM

View PostKingdaro, on 21 March 2013 - 09:45 PM, said:

Whoops. The match string should have a "+" at the end of it.
much better :P

#7 Kingdaro

    The Doctor

  • Members
  • 1,636 posts
  • Location'MURICA

Posted 21 March 2013 - 09:53 PM

Yep. That's programming. One missing/extra character will indeed screw everything over. :lol:





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users