lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


On 21/04/2011, at 11:36 AM, Valerio Schiavoni wrote:

> On Thu, Apr 21, 2011 at 12:56 AM, Geoff Leyland
> <geoff_leyland@fastmail.fm> wrote:
> 
>> How about having encode do this:
>> function encode(data)
>>  local out = { n=1}
>>  encode_table(data,  out)
>>  return table.concat(out)
>> end
>> and encode_data contains lines like:
>>  encode_table(v, out)
> 
> yes, this helped a bit but still not enough :

You still have a table.concat at every level of the stack.  Try the following.  I've only made it work for the case you test, so you'll need to finish it.

> The benchmark code is as simple as :
> ...
> 	local gen= misc.gen_string(v)

local gen = ("a"):rep(v) ???


function encode_table(data, out)
	local t = type(data)

	if t == 'table' then -- list(array) or hash
		local i = 1
		local list = true
		for k, v in pairs(data) do
			if k ~= i then
				list = false
				break
			end
			i = i + 1
		end
		if list then
			out[out.n] = 'l'
			out.n = out.n + 1
			for k, v in pairs(data) do
				encode_table(v, out)
			end
		else -- hash
			out = 'd'
			for k, v in pairs(data) do
				out = out..encode(k)..encode(v) --!!!!!
			end
		end
		out[out.n] = 'e'
		out.n = out.n + 1
	elseif t == 'string' then
		out[out.n] = tostring(#data); out.n = out.n + 1
		out[out.n] = ":"; out.n = out.n + 1
		out[out.n] = data; out.n = out.n + 1
	elseif t == 'number' then
		-- we need to convert scientific notation to decimal
		return 'i'..to_dec_string(data)..'e'  -- !!!!!
	elseif t == 'nil' then -- extension of benc
		return 'n'  -- !!!!!
	elseif t == 'boolean' then -- extension of benc
		if data then
			return 't' -- !!!!!
		else
			return 'f' -- !!!!!
		end
	end
end


local function encode(data)
	out = { n=1 }
	encode_table(data, out)
	return table.concat(out)
end