Lua getters and setters

I work with the Codea iPad app and learn Lua. Codea uses Class.lua for classes. What I'm trying to achieve is a way of defining functions for the get and set methods of variables. Currently, the variable "x" can be accessed by: print (obj.x) and set with this code: obj.x = 1. I would like the variable to call the get and set function instead, which I can specify I am porting something written in ActionScript 3 and I need to imitate the A3 get and set function declarations. Let me know if this is possible, or if this is another way. I can override Codea Class.lua if adding or changing its code is a solution. Thank.

+5
source share
1 answer

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

+5

All Articles