Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Split string in Lua?

Tags:

string

lua

People also ask

What is Lua table?

Tables are the only data structure available in Lua that helps us create different types like arrays and dictionaries. Lua uses associative arrays and which can be indexed with not only numbers but also with strings except nil. Tables have no fixed size and can grow based on our need.

How do I concatenate strings in Lua?

The most straightforward way to concatenate (or combine) strings in Lua is to use the dedicated string concatenation operator, which is two periods ( .. ). message = "Hello, " .. "world!" -- message equals "Hello, World!"

How do you split a string on Roblox?

Splits a string into parts based on the defined separator character(s), returning a table of ordered results. If an empty “slice” is located, that part will be returned as an empty string. For instance string. split("abc||def", "|") will return a table with three strings: "abc" , "" , and "def" .

How do you slice a string in Lua?

A very simple example of a split function in Lua is to make use of the gmatch() function and then pass a pattern which we want to separate the string upon.


Here is my really simple solution. Use the gmatch function to capture strings which contain at least one character of anything other than the desired separator. The separator is **any* whitespace (%s in Lua) by default:

function mysplit (inputstr, sep)
        if sep == nil then
                sep = "%s"
        end
        local t={}
        for str in string.gmatch(inputstr, "([^"..sep.."]+)") do
                table.insert(t, str)
        end
        return t
end

.


If you are splitting a string in Lua, you should try the string.gmatch() or string.sub() methods. Use the string.sub() method if you know the index you wish to split the string at, or use the string.gmatch() if you will parse the string to find the location to split the string at.

Example using string.gmatch() from Lua 5.1 Reference Manual:

 t = {}
 s = "from=world, to=Lua"
 for k, v in string.gmatch(s, "(%w+)=(%w+)") do
   t[k] = v
 end

If you just want to iterate over the tokens, this is pretty neat:

line = "one, two and 3!"

for token in string.gmatch(line, "[^%s]+") do
   print(token)
end

Output:

one,

two

and

3!

Short explanation: the "[^%s]+" pattern matches to every non-empty string in between space characters.


Just as string.gmatch will find patterns in a string, this function will find the things between patterns:

function string:split(pat)
  pat = pat or '%s+'
  local st, g = 1, self:gmatch("()("..pat..")")
  local function getter(segs, seps, sep, cap1, ...)
    st = sep and seps + #sep
    return self:sub(segs, (seps or 0) - 1), cap1 or sep, ...
  end
  return function() if st then return getter(st, g()) end end
end

By default it returns whatever is separated by whitespace.


Here is the function:

function split(pString, pPattern)
   local Table = {}  -- NOTE: use {n = 0} in Lua-5.0
   local fpat = "(.-)" .. pPattern
   local last_end = 1
   local s, e, cap = pString:find(fpat, 1)
   while s do
      if s ~= 1 or cap ~= "" then
     table.insert(Table,cap)
      end
      last_end = e+1
      s, e, cap = pString:find(fpat, last_end)
   end
   if last_end <= #pString then
      cap = pString:sub(last_end)
      table.insert(Table, cap)
   end
   return Table
end

Call it like:

list=split(string_to_split,pattern_to_match)

e.g.:

list=split("1:2:3:4","\:")


For more go here:
http://lua-users.org/wiki/SplitJoin


If you program in Lua, you are out of luck here. Lua is THE one programming language that just happens to be notoriously infamous because its authors never implemented "the" split function in the standard library, and instead wrote 16 screenfulls of explanations and lame excuses as to why they didn't and wouldn't, interspersed with numerous half-working examples that are virtually guaranteed to work for almost everyone but break in your corner case. This is just Lua state of the art, and everyone who programs in Lua simply ends up clenching their teeth and iterating over characters. There are lots of solutions in existence that are sometimes better, but exactly zero solutions that are reliably better.