## Back with a little something...

genericdave
Citizen
Posts: 53
Joined: Tue Dec 15, 2009 9:08 am

### Back with a little something...

After getting busy and uninterested in game development, I left all my code to sit for a while. Well, now I'm back and I decided I might as well share a little something I've found useful.

Inspired by a post over on BlackBulletIV's blog, I decided that this was a must-have feature for Lua, if only it were a little more fleshed out. And so, I made a little class called PropertyGetterSetter. Now, in order to redirect member access to getter and setter methods, all you need to do is inherit from the PropertyGetterSetter base class and make some getter and setter functions. Everything else works as expected.

In other words, usually gettersetter functions look like this:

Code: Select all

x = player:getX()
player:setY(100)

But just by inheriting and defining a couple special methods, you can do this instead and get the exact same effect:

Code: Select all

x = player.x
player.y = 100

Basically, whenever a child class of PropertyGetterSetter accesses a member, it checks for a special method named either _get_ or _set_ prepended to the variable name. If it exists, it uses the function instead. If it doesn't, it accesses the member normally. For example:

Code: Select all

Player = class('Player', PropertyGetterSetter)
function Player:initialize(  )
--be sure to init the parent class *first*
PropertyGetterSetter.initialize(self)

self.x = 0
self.y = 0
end

function Player:_get_x(  )
print('accessed x: ' .. self.x)
return self.x
end

function Player:_set_y( v )
print('set y to ' .. v)
self.y = v
end

player = Player()

x = player.x
player.y = 100

--there's always the directGet and directSet functions.
player:directSet('x', 99999)
print('direct access: ', player:directGet('x'))

Would output:

Code: Select all

set y to 0
accessed x: 0
set y to 100
direct access: 	99999

I've included a little test script. You'll need MiddleClass in order to run it. Assuming everything goes well, the output should be:

Code: Select all

set foo to 100 and incremented counter to 1
accessed foo via function: 100
set foo to 999 and incremented counter to 2
accessed foo directly	333
accessed foo via function: 333
accessed bar directly
doesn't matter that I didn't init this
3.1459
self-counting variable: 	3	4	5

Test it out and tell me how it goes. I'm not really an expert on lua internals, so I'd love suggestions and fixes if you come up with any. I may or may not be doing blatantly stupid stuff in this code, but that's part of the reason why I'm posting it. Have fun!
Attachments
propertygettersetter.lua
Test script