[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: best way to add field to userdata?
- From: Mark Hamburg <mark@...>
- Date: Thu, 22 Apr 2010 07:17:04 -0700
In the particular case of width and height, I've found a "dimensions" method that returns both to be useful. Multiple value return is something that gets forgotten about far too often by people coming from other languages. But that's just a special case and would not, for example, handle a property like the alignment on a sprite.
There are various interesting proposals for how to modify Lua to better support this, but we won't go there at this point (though they might be a reasonable discussion for 5.2).
Essentially, you need your __index function to implement the following logic:
__index = function( t, k )
local v = methods[ k ]
if v ~= nil then return v end
local get = getters[ k ]
if get ~= nil then
return get( t, k )
end
error( "Bad key: " .. k ) -- Insert better error message here
end
methods and getters are upvalues for the function.
You could implement this function either in C or in Lua. I'm not sure which would work more efficiently and it may depend on how you implement your getter functions. Using upvalues should make this fairly easy, however, to write in C since you can just access the method and getter tables using pseudo-indices.
Mark