This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
CLNinja's profile picture

Snippets | Bits and Bobs of random useful code

Started by CLNinja, 26 July 2017 - 10:31 PM
CLNinja #1
Posted 27 July 2017 - 12:31 AM
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

Wojbie #2
Posted 27 July 2017 - 04:16 AM
Isn't unexplodejust a table.concat?
CLNinja #3
Posted 27 July 2017 - 04:31 AM
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'
Wojbie #4
Posted 27 July 2017 - 05:12 AM
Also table.concat({"hello","there"}," ") would also return "hello there"
Edited on 27 July 2017 - 03:12 AM
CLNinja #5
Posted 27 July 2017 - 05:29 AM
Also table.concat({"hello","there"}," ") would also return "hello there"

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

Thanks!
Lupus590 #6
Posted 27 July 2017 - 11:40 AM
I've been collecting random snippits for a while, here's the git repo I've been keeping them.