Emulation of some PHP functions

Posted by Faux on Mon 17 Jan 2005 02:54 AM — 1 posts, 11,930 views.

United Kingdom #0
There's some functions that I can't cope without having, and.. as lua doens't provide them, I'm going to write them.

Hope someone else finds at least some of them useful :)

Starting with: print_r (based on Nick's code):
ie. print_r({5,3,{5,3}})

function print_r (t, indent, done)
	done = done or {}
	indent = indent or 0
	for key, value in pairs (t) do
		Tell (string.rep (" ", indent)) -- indent it
		if type (value) == "table" and not done [value] then
			done [value] = true
			Note ("[" .. tostring (key) .. "]:");
			print_r (value, indent + 4, done)
		else
			Note ("[" .. tostring (key) .. "] = " .. tostring (value))
		end
	end
end

and explode:
ie. explode(" ","this is a test string")

function explode(d,p)
	t={}
	ll=0
	while true do
		l=string.find(p,d,ll+1,true) -- find the next d in the string
		if l~=nil then -- if "not not" found then..
			table.insert(t, string.sub(p,ll,l-1)) -- Save it in our array.
			ll=l+1 -- save just after where we found it for searching next time.
		else
			table.insert(t, string.sub(p,ll)) -- Save what's left in our array.
			break -- Break at end, as it should be, according to the lua manual.
		end
	end
	return t
end


and implode:
ie. implode(" ",{"this","is","a","test","array"})

function implode(d,t)
	ss=""
	for a, v in pairs(t) do ss = ss .. v .. d end  -- foreach value, add it to ss and add the delimiter
	ss=string.sub(ss,0,string.len(ss)-string.len(d)) -- Remove the bogus ending delimiter.s
	return ss
end


..and preg_replace:
ie. preg_replace("\((.*?)\)","", " Obvious exits: n(closed) w(open) rift")
NOTE: Normal preg_replace supports using the wildcards in the replace, this doesn't.. yet

function preg_replace(pat,with,p)
	while true do
		a=rex.new(pat) -- compile regexp
		x,y,t=a:match(p) -- match regexp
		if (x~=nil and y~=nil) then -- if we matched then
			p=string.sub(p,0,x-1).. with .. string.sub(p,y+1) -- rebuild the string
		else
			break
		end
	end
	return p
end