Wednesday, May 16, 2012

__index, __newindex Metamethod

 MyArr = {}  
   
 MyArr.Meta = {}   
 MyArr.Meta.__tostring = function(a)  
      result = ""  
      for k, v in pairs(a.arr) do  
           result = result .. "[" .. k .. "]" .. " " .. v .. "\t"  
      end  
      return result  
 end  
 MyArr.Meta.__index = function(a, key)  
      return (a.arr[key])  
 end  
 MyArr.Meta.__newindex = function(a, key, value)  
      a.arr[key] = value  
 end  
 function MyArr.new(a)  
      local instance = {}  
      instance.arr = {}  
      for k, v in pairs(a) do  
           instance.arr[k] = v  
      end  
        
      function instance:printMe()   
           print("----------------------")  
           for k, v in pairs(self.arr) do  
                print(k, v)  
           end  
      end  
        
      setmetatable(instance, MyArr.Meta)  
      return instance  
 end  
   
 do  
      local a = MyArr.new{"Mimi", "Ki", "Jacky"}  
      a[5] = "Tom"  
      print(tostring(a))  
      a:printMe()  
 end  
Programming in Lua / Chapter 13. Metatables and Metamethods / 레퍼런스 : 13.4.1 – The __index Metamethod

No comments:

Post a Comment