Jump to content




Empty Pattern in my Split function

lua help

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

#1 Wing

  • Members
  • 58 posts

Posted 01 March 2013 - 10:00 AM

Hey guys, I brought this up inside another one of my threads but here it is again.
When I leave the <pat> empty ("") it returns an empty table, I'm hoping for it to split each letter up and not nothing...
function split(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


#2 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 01 March 2013 - 11:54 AM

Use this instead: "."

The period is a special operator for patterns that matches any single character.

#3 Bubba

    Use Code Tags!

  • Moderators
  • 1,142 posts
  • LocationRHIT

Posted 01 March 2013 - 01:36 PM

I'm confused by what you want. Do you want this function to split the string into separate characters if pat is left empty? If so then there is a handy function called string.gmatch(pat).
local example = "This is a string of characters"
local tExample = {}
for char in example:gmatch(".") do
  table.insert(tExample, char)
end
Now tExample has every character in example seperated.

#4 Wing

  • Members
  • 58 posts

Posted 01 March 2013 - 01:37 PM

Alright, lets try that, will edit the post with the results!

#5 Wing

  • Members
  • 58 posts

Posted 01 March 2013 - 02:10 PM

Ok well, "." didn't work....
command: textutils.serialize(w.split("lol I Win", "."))
returns: {[1]= "", [2]="", [3]="", [4]="", [5]="", [6]="", [7]="",}

#6 Lyqyd

    Lua Liquidator

  • Moderators
  • 8,465 posts

Posted 01 March 2013 - 03:19 PM

Don't use that split function. This should do the trick:

function stringToCharTable(str)
  local tab = {}
  for i = 1, #str do
    tab[i] = string.sub(str, i, i)
  end
  return tab
end


#7 Wing

  • Members
  • 58 posts

Posted 02 March 2013 - 09:06 AM

Thanks I'm sure that works I'll add it, but I still want to know why this isn't working, using 2 different function to split strings is weird, but will have to do!





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users