Jump to content




Snippets | Bits and Bobs of random useful code


5 replies to this topic

#1 CLNinja

  • Members
  • 191 posts

Posted 26 July 2017 - 11:31 PM

I don't know if this is the best place to put it, but I feel that a place to put random snippets of useful code is something nice.

I'll start off by putting my 2 functions:

--[[
Explode takes a string and a character to split on and
returns a table with every bit of text that was separated by
the given character
Ex: explode("hi there"," ")
   Return: {"hi","there"}
uexplode takes a table and a character and returns a
string with each index of the table concatenated with the
given character
Ex: uexplode({"hi","there"}," ")
   Return: "hi there"
--]]

function explode(str,char)
    local tbl = {}
    if char == "" then
	    for i=1, str:len() do
		    table.insert(tbl,str:sub(i,i))
	    end
	    return tbl
    elseif not str:find(char) then
	    return {str}
    else
	    local _,amt = str:gsub(char," ")
	    for i=1, amt+1 do
		    if str:find(char) then
			    local x,y = str:find(char)
			    local rep = str:sub(1,x-1)
			    table.insert(tbl,rep)
			    str = str:sub(y+1, str:len())
		    else
			    table.insert(tbl,str)
		    end
	    end
    end
    return tbl
end

function uexplode(tbl,char)
    local ret = ""
    for k,v in pairs(tbl) do
	    if k == #tbl then
		    ret = ret..v
	    else
		    ret = ret..v..char
	    end
    end
    return ret
end



#2 Wojbie

  • Members
  • 631 posts
  • LocationKinda lost

Posted 27 July 2017 - 03:16 AM

Isn't unexplodejust a table.concat?

#3 CLNinja

  • Members
  • 191 posts

Posted 27 July 2017 - 03:31 AM

View PostWojbie, on 27 July 2017 - 03:16 AM, said:

Isn't unexplodejust a table.concat?
Not completely

table.concat on a table such as {"hello","there"} would return hellothere as a string

uexplode({"hello","there"}," ") would return 'hello there'

#4 Wojbie

  • Members
  • 631 posts
  • LocationKinda lost

Posted 27 July 2017 - 04:12 AM


Also table.concat({"hello","there"}," ") would also return "hello there"

Edited by Wojbie, 27 July 2017 - 04:12 AM.


#5 CLNinja

  • Members
  • 191 posts

Posted 27 July 2017 - 04:29 AM

View PostWojbie, on 27 July 2017 - 04:12 AM, said:

Also table.concat({"hello","there"}," ") would also return "hello there"

Oh, I didn't know that table.concat could actually do that.

Thanks!

#6 Lupus590

  • Members
  • 2,029 posts
  • LocationUK

Posted 27 July 2017 - 10:40 AM

I've been collecting random snippits for a while, here's the git repo I've been keeping them.





1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users