- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How to 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
- Related Articles
- How to convert a string to int in Lua programming?
- How to Use lua-mongo library in Lua Programming?
- How to Implement a Queue in Lua Programming?
- How to make a namespace in Lua programming?
- How to work with MySQL in Lua Programming?
- How to define and call a function in Lua Programming?
- Comments in Lua Programming
- How to use the Insert function in Lua Programming?
- How to Use the Remove function in Lua programming?
- How to use the require function in Lua programming?
- How to use the Time package in Lua programming?
- How to use Lua Programming to check if a file exists?
- table.pack() function in Lua programming
- table.unpack() function in Lua programming
- Lexical Conventions in Lua Programming
