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)
Code: Select all
x = player.x
player.y = 100
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
--Plus, if you ever need direct access to a member variable,
--there's always the directGet and directSet functions.
player:directSet('x', 99999)
print('direct access: ', player:directGet('x'))
Code: Select all
set y to 0
accessed x: 0
set y to 100
direct access: 99999
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