[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: PiL2, ch 28.3: Adding Lua methods to an array?
- From: Javier Guerra <javier@...>
- Date: Fri, 9 Jun 2006 08:00:12 -0500
On Friday 09 June 2006 3:35 am, Carsten Fuchs wrote:
> Hello all,
>
> when we have userdata with a metatable as described in the "array"
> example in the PiL1 or PiL2, chapter 28.3 "Object-Oriented Access"
> (http://www.lua.org/pil/28.3.html), I would like to be able to add more
> functions in Lua.
>
> For example, chapter 28.3 in PiL2 starts with the example
>
> a = array.new(1000)
> print(a:size())
> a:set(10, true)
> print(a:get(10))
>
> And now I'd like to be able to add a statement like
>
> function a:OnMouseClick()
> -- do something...
> print("Hello!\n")
> end
your object 'a' is a userdata; but it has a metatable already set, and i guess
its __index field points to the methods table. so, you can write:
local m = getmetatable (a).__index
function m:OnMouseClick()
.........
end
maybe even:
function getmetatable (a).__index:OnMouseClick()
.......
end
another thing you could try is to use __newindex:
local mt = getmetatable (a)
function mt.__newindex (t,k,v)
t.__index[k] = v
end
after that, any value you set like "a[xx] = yy" will be set on the methods
table, therefore this could work:
function a:OnMouseClick ()
......
end
--
Javier
Attachment:
pgpyMzO5Rr_OY.pgp
Description: PGP signature