Skip to content

Instantly share code, notes, and snippets.

@cristobal
Created September 6, 2012 10:38
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cristobal/3654651 to your computer and use it in GitHub Desktop.
Save cristobal/3654651 to your computer and use it in GitHub Desktop.
Lua php serialize port
--[[
LUA variant of the php serialize function
Port of http://phpjs.org/functions/unserialize
]]--
function serialize (mixed_value)
-- body
local val, key, okey,
ktype, vals, count, _type;
ktype = ''; vals = ''; count = 0;
-- https://gist.github.com/978154
_round = function(num) return math.floor(num + .5) end
_utf8Size = function (str)
local size, i, l, code, val;
size = 0; i = 0;
l = string.len(str); code = '';
for i = 1, l, 1 do
code = str:byte(i)
if code < 0x0080 then
val = 1
elseif code < 0x0800 then
val = 2
else
val = 3
end
size = size + val
end
return size
end
_type = type(mixed_value)
if _type == 'function' then
val = ''
elseif _type == 'boolean' then
val = 'b:' .. (mixed_value and '1' or '0')
elseif _type == 'number' then
val = (_round(mixed_value) == mixed_value and 'i' or 'd') .. ':' .. tostring(mixed_value)
elseif _type == 'string' then
val = 's:' .. _utf8Size(mixed_value) .. ':"' .. mixed_value .. '"'
elseif _type == 'table' then
val = 'a'
for k,v in pairs(mixed_value) do
ktype = type(v)
if ktype ~= 'function' then
vals = vals .. serialize(k) .. serialize(v)
count = count + 1
end
end
val = val .. ':' .. count .. ':{' .. vals .. '}'
else
--- if the object has a property which contains a null value, the string cannot be unserialized by PHP
val = 'N'
end
if _type ~= 'table' then
val = val ..';'
end
return val
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment