lua-users home
lua-l archive

RE: manipulating data

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


Darius Blaszijk wrote:
> I understand what you mean. The problem however is that I 
> don't want to store the same data as table in the lua state 
> and in my application as object (for memory and debugging 
> reasons). Therefore I was thinking of using a getter and 
> setter function that encapsulates the data. So in effect:
> 
> data[1,2] = 1.234 is comparable in calling the function 
> setdata(1,2,1.234) and print(data[1,2] is comparable to 
> calling the function getdata(1,2)
> 
> the first does not return any value, the second returns the 
> value of the data object in my app at position 1,2
You can use the slightly more complex syntax data[{1, 2}]. To do that
youmust use index and newindex metamethods. Here is an example with
tables:
function matrix()
 local self = setmetatable({}, {
 matrix = {},
 __newindex = function(self, key, value)
 local t = getmetatable(self).matrix
 for i=1,#key-1 do
 if not t[key[i]] then t[key[i]] = {} end
 t = t[key[i]]
 end
 t[key[#key]] = value
 end;
 __index = function(self, key)
 local t = getmetatable(self).matrix
 for i=1,#key-1 do
 if not t[key[i]] then t[key[i]] = {} end
 t = t[key[i]]
 end
 return t[key[#key]]
 end;
 })
 return self
end
local m = matrix(2)
m[{1,2}] = 1.234
print(m[{1,2}])
print(m[{3,2}])
print(m[{1,4}])
You may have to complete this example to deal with the cases where given
indices don't match your matrix dimension.

AltStyle によって変換されたページ (->オリジナル) /