Separate a string with a character in Lua

I have type strings "ABC-DEF", and I need to break them into a character "-"and assign each of the two parts to a variable. In Ruby, I would do it like this:

a, b = "ABC-DEF".split('-')

Lua doesn't seem to have such an easy way. After some digging, I could not find a short and concise way to achieve what I needed. I mention that I am a complete newbie to Lua, and I need to use it in a script for Redis (so it really should be small, if possible with one liner).

+1
source share
2 answers

Use pattern matching:

a, b = string.match("ABC-DEF", "(.*)%-(.*)")

, - , %.

+7

, , , , , Python, . gsplit().

local unpack = table.unpack or unpack

--------------------------------------------------------------------------------
-- Escape special pattern characters in string to be treated as simple characters
--------------------------------------------------------------------------------

local
function escape_magic(s)
  local MAGIC_CHARS_SET = '[()%%.[^$%]*+%-?]'
  if s == nil then return end
  return (s:gsub(MAGIC_CHARS_SET,'%%%1'))
end

--------------------------------------------------------------------------------
-- Returns an iterator to split a string on the given delimiter (comma by default)
--------------------------------------------------------------------------------

function string:gsplit(delimiter)
  delimiter = delimiter or ','          --default delimiter is comma
  if self:sub(-#delimiter) ~= delimiter then self = self .. delimiter end
  return self:gmatch('(.-)'..escape_magic(delimiter))
end

--------------------------------------------------------------------------------
-- Split a string on the given delimiter (comma by default)
--------------------------------------------------------------------------------

function string:split(delimiter,tabled)
  tabled = tabled or false              --default is unpacked
  local ans = {}
  for item in self:gsplit(delimiter) do
    ans[ #ans+1 ] = item
  end
  if tabled then return ans end
  return unpack(ans)
end
+1

Source: https://habr.com/ru/post/1658303/


All Articles