Asset
1. Overview
This is a general abstraction for handling assets in Gestlings.
An asset is a data structure that can be represented as a Lua table, that can be loaded/saved to disk.
The marshaling process is as follows: a lua table is converted to msgpack, then encoded in base64.
2. Tangled File
Called asset.lua
.
<<asset.lua>>=
Asset = {}
<<asset>>
return Asset
3. New: create a new instance of Asset
In order to read/write assets, the asset library must be instantiated. This is done to allow the base64 and msgpack components to be passed in as optional arguments in the configuration.
<<asset>>=
function Asset:new(o)
o = o or {}
o.msgpack = o.msgpack or msgpack
o.base64 = o.base64 or base64
setmetatable(o, self)
self.__index = self
return o
end
4. Instantiate
The instantiate
function
is a helper function that shaves off a few steps and
turns this process into a one-liner.
Asset is instantiated by first loading this module, laoding
the base64/msgpack components, then creating a single
instance with the new
method.
<<asset>>=
function Asset.instantiate()
return Asset:new {
msgpack=dofile("util/MessagePack.lua"),
base64=dofile("util/base64.lua")
}
end
5. Save: Save an asset to a file
<<asset>>=
function Asset:encode(data)
local data_packed = self.msgpack.pack(data)
local data_b64 = self.base64.encode(data_packed)
return data_b64
end
function Asset:save(data, filename)
-- local data_packed = self.msgpack.pack(data)
-- local data_b64 = self.base64.encode(data_packed)
local data_b64 = self.encode(self, data)
local fp = io.open(filename, "wb")
for p=1,#data_b64, 40 do
fp:write(string.sub(data_b64, p, p + 39) .. "\n")
end
fp:close()
end
6. Load: Load an asset from a file
<<asset>>=
function Asset:decode(data_packed_b64)
local data_packed = self.base64.decode(data_packed_b64)
local data = self.msgpack.unpack(data_packed)
return data
end
function Asset:load(filename)
local fp = io.open(filename, "rb")
assert(fp ~= nil, "Could not read file: " .. filename)
local data_packed_b64 = fp:read("*all")
fp:close()
-- local data_packed = self.base64.decode(data_packed_b64)
-- local data = self.msgpack.unpack(data_packed)
data = self.decode(self, data_packed_b64)
return data
end