Split a string and store in an array in lua - string

I need to split a string and store it in an array. here i used string.gmatch method, and its splitting the characters exactly, but my problem is how to store in an array ? here is my script.
my sample string format : touchedSpriteName = Sprite,10,rose
objProp = {}
for key, value in string.gmatch(touchedSpriteName,"%w+") do
objProp[key] = value
print ( objProp[2] )
end
if i print(objProp) its giving exact values.

Your expression returns only one value. Your words will end up in keys, and values will remain empty. You should rewrite the loop to iterate over one item, like this:
objProp = { }
touchedSpriteName = "touchedSpriteName = Sprite,10,rose"
index = 1
for value in string.gmatch(touchedSpriteName, "%w+") do
objProp[index] = value
index = index + 1
end
print(objProp[2])
This prints Sprite (link to demo on ideone).

Here's a nice function that explodes a string into an array. (Arguments are divider and string)
-- Source: http://lua-users.org/wiki/MakingLuaLikePhp
-- Credit: http://richard.warburton.it/
function explode(div,str)
if (div=='') then return false end
local pos,arr = 0,{}
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1))
pos = sp + 1
end
table.insert(arr,string.sub(str,pos))
return arr
end

Here is a function that i made:
function split(str, character)
result = {}
index = 1
for s in string.gmatch(str, "[^"..character.."]+") do
result[index] = s
index = index + 1
end
return result
end
And you can call it :
split("dog,cat,rat", ",")

Reworked code of Ricardo:
local function split (string, separator)
local tabl = {}
for str in string.gmatch(string, "[^"..separator.."]+") do
table.insert (tabl, str)
end
return tabl
end
print (unpack(split ("1234#5678#9012", "#")))
-- returns 1234 5678 9012

Related

Lua string manipulation

This is my code
local function char(...) return string.char(...) end
local function addtok(text,token,C)
text = text or ""
local string = ""
local count = 0
for word in text:gmatch(("[^%s]+"):format(char(C))) do
string = string..char(C)..word
end
string = string..char(C)..token
print(string)
end
The function
addtok("Devotion Aura;Charger;Righteous Fury","Seal of Wisdom",59)
returns
";Devotion Aura;Charger;Righteous Fury;Seal of Wisdom"
but what I want is
"Devotion Aura;Charger;Righteous Fury;Seal of Wisdom"
possible fix: print(string.sub(string, 2))
any better solution?
local function addtok(text,token,C)
local string = (text or "").. string.char(C) .. token
print(string)
end
addtok("Devotion Aura;Charger;Righteous Fury","Seal of Wisdom",59)
The line string = string..char(C)..word will prepend the first semicolon. That's the issue with appending within a loop - you have to make an exception for either the last or the first element if you don't want a trailing or leading delimiter. In this case however, you should be using table.concat, both for performance (avoiding unnecessary string copies) and convenience of joining by delimiter:
local function char(...) return string.char(...) end
local function addtok(text,token,C)
text = text or ""
local words = {}
local count = 0
for word in text:gmatch(("[^%s]+"):format(char(C))) do
table.insert(words, word)
end
local string = table.concat(words, char(C))..char(C)..token
print(string)
end

How to separate a string by more than one character in lua?

string is "abc||d|ef||ghi||jkl",
How to divide this string into an array, if the separator is "||" .
eg. "abc","d|ef","ght","jkl".
I found a code to split a string, but only one character can be used as a separator.
the code is :
text={}
string="abc||d|ef||ghi||jkl"
for w in string:gmatch("([^|]*)|")
do
table.insert(text,w)
end
for i=1,4
do
print(text[i])
end
Therefore, how to seperate the string with multiple characters?
Well, either grab letters '[a-zA-Z]+' -or- '[%a]+' your choice.
#! /usr/bin/env lua
text = {}
string = 'abc||def||ghi||jkl'
for w in string :gmatch( '[a-zA-Z]+' ) do
table .insert( text, w )
end
for i = 1, #text do
print( text[i] )
end
or anything that isn't pipes '[^|]+'
text = {}
string = 'abc||def||ghi||jkl'
for w in string :gmatch( '[^|]+' ) do
table .insert( text, w )
end
for i = 1, #text do
print( text[i] )
end
https://riptutorial.com/lua/example/20315/lua-pattern-matching
abc
def
ghi
jkl
You could try this:
text={}
string="abc||def||ghi||jkl"
for w in string:gmatch("([^|]*)||")
do
table.insert(text,w)
end
for i=1,4
do
print(text[i])
end
It's the same code, just with another "|".
EDIT:
This should work better now:
str = "abc||d|ef||ghi||jkl"
function getMatches(inputString)
hits = {}
beginSection = 1
consecutive = 0
for index=0,#inputString do
chr = string.sub(inputString,index,index)
if chr=="|" then
consecutive = consecutive+1
if consecutive >= 2 then
consecutive = 0
table.insert(hits,string.sub(inputString,beginSection,index-2))
beginSection = index + 1
end
else
consecutive = 0
end
end
if beginSection ~= #inputString then
table.insert(hits,string.sub(inputString,beginSection,#inputString))
end
return hits
end
for _,v in pairs(getMatches(str)) do print(v) end
io.read()
Patterns aren't always the way to go in Lua, they are rather limited (no grouping).

How to concatenate strings into one using loop?

can someone help me with string concatenate problem. I read data from register. It's function utf(regAddr, length). I get table with decimal numbers, then I transform it into hex and to string in loop. I need concatenate these strings into one.
there is not in Lua something like .= operator
function utf(regAddr, length)
stringTable = {}
table.insert(stringTable, {mb:readregisters(regAddr-1,length)})
for key, value in pairs(stringTable) do
for i=1, length do
v = value[i]
v = lmcore.inttohex(v, 4)
v = cnv.hextostr(v)
log(v)
end
end
end
-- function(regAddr, length)
utf(30,20)
There is no append operator for strings. Strings are immutable values.
The .. operator concatenates two string, producing a third string as a result:
local b = "con"
local c = "catenate"
local a = b .. c -- "concatenate"
The table.concat function concatenates strings in a table, producing a string result:
local t = { "con", "catenate" }
local a = table.concat(t) -- "concatenate"
local t = { "two", "words" }
local a = table.concat(t, " ") -- "two words"
The string.format function takes a format pattern with a list of compatible values, producing a string result:
local b = 2
local c = "words"
local a = string.format("%i %s", b, c) -- "2 words"
local t = { 2, "words" }
local a = string.format("%i %s", unpack(t)) -- "2 words"
If you are accumulating a lot of strings that you eventually want to concatenate, you can use a table as a temporary data structure and concatenate when you are done accumulating:
local t = {}
for i = 1, 1000 do
table.insert(t, tostring(i))
end
local a = table.concat(t) -- "1234...9991000"
For a very large number of strings, you can concatenate incrementally. See LTN 9: Creating Strings Piece by Piece and related discussions.
You should try the table.concat method.
Maybe this other question can help you:
Lua table.concat
Checkout this tutorial http://lua-users.org/wiki/TableLibraryTutorial
this code works:
function utf(regAddr, length)
stringTable = {}
table.insert(stringTable, {mb:readregisters(regAddr-1,length)})
for key, value in pairs(stringTable) do
t = {}
for i=1, length do
v = value[i]
v = lmcore.inttohex(v, 4)
v = cnv.hextostr(v)
table.insert(t, v)
end
a = table.concat(t)
end
end
-- function(regAddr, length)
utf(30,20)

Is it possible to concatenate a string with series of number?

I have a string (eg. 'STA') and I want to make a cell array that will be a concatenation of my sting with a numbers from 1 to X.
I want the code to do something like the fore loop here below:
for i = 1:Num
a = [{a} {strcat('STA',num2str(i))}]
end
I want the end results to be in the form of {<1xNum cell>}
a = 'STA1' 'STA2' 'STA3' ...
(I want to set this to a uitable in the ColumnFormat array)
ColumnFormat = {{a},... % 1
'numeric',... % 2
'numeric'}; % 3
I'm not sure about starting with STA1, but this should get you a list that starts with STA (from which I guess you could remove the first entry).
N = 5;
[X{1:N+1}] = deal('STA');
a = genvarname(X);
a = a(2:end);
You can do it with combination of NUM2STR (converts numbers to strings), CELLSTR (converts strings to cell array), STRTRIM (removes extra spaces)and STRCAT (combines with another string) functions.
You need (:) to make sure the numeric vector is column.
x = 1:Num;
a = strcat( 'STA', strtrim( cellstr( num2str(x(:)) ) ) );
As an alternative for matrix with more dimensions I have this helper function:
function c = num2cellstr(xx, varargin)
%Converts matrix of numeric data to cell array of strings
c = cellfun(#(x) num2str(x,varargin{:}), num2cell(xx), 'UniformOutput', false);
Try this:
N = 10;
a = cell(1,N);
for i = 1:N
a(i) = {['STA',num2str(i)]};
end

Split string and replace dot char in Lua

I have a string stored in sqlite database and I've assigned it to a var, e.g. string
string = "First line and string. This should be another string in a new line"
I want to split this string into two separated strings, the dot (.) must be replace with (\n) new line char
At the moment I'm stuck and any help would be great!!
for row in db:nrows("SELECT * FROM contents WHERE section='accounts'") do
tabledata[int] = string.gsub(row.contentName, "%.", "\n")
int = int+1
end
I tried the other questions posted here in stachoverflow but with zero luck
What about this solution:`
s = "First line and string. This should be another string in a new line"
a,b=s:match"([^.]*).(.*)"
print(a)
print(b)
Are you looking to actually split the string into two different string objects? If so maybe this can help. It's a function I wrote to add some additional functionality to the standard string library. You can use it as-is or rename it to what ever you like.
--[[
string.split (s, p)
====================================================================
Splits the string [s] into substrings wherever pattern [p] occurs.
Returns: a table of substrings or, if no match is made [nil].
--]]
string.split = function(s, p)
local temp = {}
local index = 0
local last_index = string.len(s)
while true do
local i, e = string.find(s, p, index)
if i and e then
local next_index = e + 1
local word_bound = i - 1
table.insert(temp, string.sub(s, index, word_bound))
index = next_index
else
if index > 0 and index <= last_index then
table.insert(temp, string.sub(s, index, last_index))
elseif index == 0 then
temp = nil
end
break
end
end
return temp
end
Using it is very simple, it returns a tables of strings.
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> s = "First line and string. This should be another string in a new line"
> t = string.split(s, "%.")
> print(table.concat(t, "\n"))
First line and string
This should be another string in a new line
> print(table.maxn(t))
2

Resources