[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Emulate setters and getters on table
- From: Alfredo Palhares <masterkorp@...>
- Date: Mon, 25 Feb 2013 14:28:37 +0100
Excerpts from Rena's message of Sun Feb 24 00:15:07 +0100 2013:
> <masterkorp@masterkorp.net> wrote:
> There is: the __index and __newindex metamethods. See
> http://www.lua.org/manual/5.2/manual.html#2.4
>
> myTable = {}
> setmetatable(myTable, {
> __index = function(self, key)
> print(key, "was looked up")
> return rawget(self, key)
> end,
>
> __newindex = function(self, key, value)
> print(key, "was set to", value)
> rawset(self, key, value)
> end,
> })
>
> That will create a table that will report when a value is read or
> written. HOWEVER, these metamethods are only called if the key is not
> already present in the table. So:
> myTable[1] = 'a' --will print a message
> myTable[1] = 'b' --will NOT print a message
Thanks, that was what i was looking for. Now i have one small question.
I plan to call the respective get and set methods based on the key, instead of using rawset,
just becayse each key will have its own logic.
Its there a way to call a method based on a string ?
like method = "set" .. key and the use it?
Thank you so much.
--
Regards,
Alfredo Palhares