
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Split a String in Lua Programming
Splitting a string is the process in which we pass a regular expression or pattern with which one can split a given string into different parts.
In Lua, there is no split function that is present inside the standard library but we can make use of other functions to do the work that normally a split function would do.
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.
Example
Consider the example shown below −
local example = "lua is great" for i in string.gmatch(example, "%S+") do print(i) end
Output
lua is great
The above example works fine for simple patterns but when we want to make use of a regular expression and the case that we can have a default pattern with which to split, we can consider a more elegant example.
Example
Consider the example shown below −
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 ans = mysplit("hey bro whats up?") for _, v in ipairs(ans) do print(v) end ans = mysplit("x,y,z,m,n",",") for _, v in ipairs(ans) do print(v) end
Output
hey bro whats up? x y z m n