On 2 October 2013 14:43, Luiz Henrique de Figueiredo <
lhf@tecgraf.puc-rio.br> wrote:
> > Yes, it is on my TODO list to provide a Lua-style interface to the
> > database. The question remains on how/whether to handle other class methods
> > efficiently in __index, since I want to use it for "t[k]".
>
> That's where *proxy* comes in. You create an empty table that redirects
> to the db handle. Something like this:
>
> function db_proxy(db)
> local m= {
> __index=function (t,k) return db:get(k) end,
> __newindex=function (t,k,v) db:set(k,v) end
> }
> return setmetatable({},m)
> end
Yes this is the way I wanted to implement it. What I was thinking that if I want to provide extra "methods" on the proxy object, I would have to do some magic. In the simple case, it is just this:
function db_proxy(db)
local m = {
__index = db.get,
__newindex = db.set
}
return setmetatable({},m)
end
However, if I want to have a for-iterator in Lua5.1, where there is no __pairs, there would have to be special logic to handle i.e. "proxy:cursor()" or "proxy:pairs()", such as:
function db_proxy(db)
local m = {
__index = function (t,k)
if k == "cursor" then return function() return db:cursor() end
else return db:get(k)
end
end,
__newindex = function (t,k,v)
-- ignore "cursor", since it cannot be read
if k == "cursor" then
else db:set(k,v)
end
end
}
return setmetatable({},m)
end
I guess I will stick to the simple case - if you need to iterate over the values in the DB, just use the traditional interface.