Module:Split

From Dota 2 Wiki
Jump to: navigation, search

Documentation for Module:Split Jump to code ↴ [ edit | purge ]

This module provides a more efficient way than mw.text.split() to split strings in Lua.

Usage[edit]

split( string, pattern, plain )

Example[edit]

local p = {}
local split = require( 'Module:Split' )

function p.main()
  split( '1/2/3/4', '/' ) --> { '1', '2', '3', '4' }
end

return p

Tests[edit]

YesY All tests passed.

Name Expected Actual
YesY test_pattern_split
YesY test_split
YesY test_split_plain


local checkType = require( 'libraryUtil' ).checkType


return function ( str, pattern, plain )
  checkType( 'split', 1, str, 'string' )
  checkType( 'split', 2, pattern, 'string' )
  checkType( 'split', 3, plain, 'boolean', true )
  
  local i, out = 1, {}
  local split_start, split_end = string.find( str, pattern, i, ( plain or false ) )
  while split_start do
    out[#out + 1] = string.sub( str, i, split_start - 1 )
    i = split_end + 1
    split_start, split_end = string.find( str, pattern, i, ( plain or false ) )
  end
  out[#out + 1] = string.sub( str, i )

  return out
end