lua-users home
lua-l archive

Re: best way to add field to userdata?

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


<snip>
> Alternatively, I could return a table and hang my userdata off that,
> but it seems prone to accidents.
<snip>
You could use the userdatum environment as proxy:
-- image.lua
local env = debug.getfenv
local u = newproxy(true)
local mt = getmetatable(u)
local class = {
 resize = function (o, x, y)
 local e = env(o)
 e.width, e.height = x, y
 end,
 makepretty = function (o)
 print(string.format("image: %d x %d", o.width, o.height))
 end
}
mt.__index = function (o, k) return env(o)[k] or class[k] end
mt.__newindex = function (o, k, v) env(o)[k] = v end
function GetImage (w, h)
 local o = newproxy(u) -- create or read image
 debug.setfenv(o, {width=w, height=h})
 return o
end
$ lua -i image.lua 
Lua 5.1.4 Copyright (C) 1994-2008 Lua.org, PUC-Rio
> img = GetImage()
> img:resize(100, 200)
> img:makepretty()
image: 100 x 200
> print(img.width, img.height)
100	200
> img.width, img.height = 200, 300
> img:makepretty()
image: 200 x 300
I've implemented in Lua for simplicity, but it's straightforward to adapt it
to C (use lua_getfenv instead of debug.getfenv etc.)
Cheers,
Luis
-- 
Computers are useless. They can only give you answers.
 -- Pablo Picasso
-- 
Luis Carvalho (Kozure)
lua -e 'print((("lexcarvalho@NO.gmail.SPAM.com"):gsub("(%u+%.)","")))'

AltStyle によって変換されたページ (->オリジナル) /