You can create a custom setter and getter by overriding the __newindex and __index methods in your class.
Note that you will need to modify LuaSandbox.lua, which is part of Codea, to enable the rawset and rawget methods (comment out the lines that set them to zero). EDIT: This no longer applies to the latest version of Codea, rawsetand is rawgetavailable by default.
The __newindex method is called whenever you try to set a property in a table that has not previously been set.
The __index method is called whenever you try to get a property that does not exist in the table.
, , -. , __newindex __index.
MyClass = Class()
function MyClass:init()
-- We'll store members in an internal table
self.members = {}
end
function MyClass:__newindex( index, value )
if index == "testMember" then
self.members[index] = value
print( "Set member " .. index .. " to " .. value )
else
rawset( self, index, value )
end
end
function MyClass:__index( index )
if index == "testMember" then
print( "Getting " .. index )
return self.members[index]
else
return rawget( self, index )
end
end
function setup()
foo = MyClass()
foo.testMember = 5
foo.testMember = 2
print( foo.testMember )
end
: http://lua-users.org/wiki/MetamethodsTutorial