Home Accessibility Courses Twitter The Mouth Facebook Resources Site Map About Us Contact
 
20.9.2014 - We have just updated our course layouts and descriptions and added our 2015 schedule.

__index and __newindex in Lua - metatable methods

When you call up an element in a table in Lua, it's like accessing an array element - and it works well. But you can go further by associating a metatable with a table - that's another table with a whole lot of extras - and that allows you to alter the behaviour of the original table. Since Lua works "by reference", you can apply the same metatable characteristics to a whole lot of different tables, resulting in what are different types of tables - very close to object orientation if you think of it like that.

To start you off, you can define a piece of code called __index in your Lua metatable, and that piece of code will be run whenever you read the value of variable that doesn't exist as a table member in its own right. You can also define a piece of code called __newindex, and that piece of code will be run whenever you write the value of a variable.

I've written a demonstration of this from first principles [here - full source]. Let's look at that part by part:

Here is my __newindex method - I have simply added any input onto the end of a long single member called "sponge"

metapicture.__newindex = function(which,what,becomes)
  which["sponge"] = which["sponge"] ..
    what .. ": " .. becomes .. "\n"
  end


Here is my __index method, in which I get ALL lines of the string that I've been building up that match the requested parameter, and return them as a single string

metapicture.__index = function(which,what)
  rv = ""
  for k,v in string.gmatch(which["sponge"],
        "(%a+):.(.-)\n") do
    if k == what then
        rv = rv .. v .. "\n"
        end
    end
  return rv
  end


Basically, I'm implementing an "append anything" table.

I've tested that by storing several famous pictures in the single picture table, then extracting ALL the painters and ALL the picture names:

picture.name = "The Haywain"
picture.painter = "Constable"
 
picture.name = "Whistler's Mother"
picture.painter = "Whistler"
 
print ("\nNamed of pictures:")
io.write(picture.name)
 
print ("\nPainters of pictures:")
io.write(picture.painter)


And running that, I see a list of picture names, then a list of painters, and not just the most recent picture of the most recent painter:

[trainee@holt lm10]$ lua index_123
 
Named of pictures:
The Haywain
Whistler's Mother
 
Painters of pictures:
Constable
Whistler
[trainee@holt lm10]$








(written 2010-04-05)

 
Associated topics are indexed as below, or enter http://melksh.am/nnnn for individual articles
U107 - Object Orientation - the Lua way
  [4273] Dot or Colon separator between table name and member in Lua - what is the difference? - (2014-05-06)
  [4248] Metatables, Metamethods, classes and objects in Lua - (2014-03-18)
  [4117] Is Lua an Object Oriented language? - (2013-06-15)
  [3730] What is a metatable? How do I set one up? How do I use them? Lua - (2012-05-12)
  [3727] Using Lua tables as objects - (2012-05-11)
  [3694] Special __ methods you can use in Lua metatables - (2012-04-12)
  [3683] Weak references in Lua - what are they, and why use them? - (2012-04-04)
  [3524] Metaclasses (Python) and Metatables (Lua) - (2011-11-17)
  [3396] Tables as Objects in Lua - a gentle introduction to data driven programming - (2011-08-17)
  [3142] Private and Public - and things between - (2011-01-22)
  [2703] Lua Metatables - (2010-04-02)
  [2701] Is Lua an Object Oriented language? - (2010-04-01)
  [2455] Lua examples - coroutines, error handling, objects, etc - (2009-10-15)
  [2359] A fresh example - objects the Lua way - (2009-08-13)
  [2318] For Lua Programmers AND for Town Planners - (2009-08-02)
  [1819] Calling base class constructors - (2008-10-03)
  [1743] First class functions in Lua lead to powerful OO facilities - (2008-08-07)
  [1699] If you are learning Lua, here are some more examples - (2008-07-06)
  [1692] Towards Object Oriented Programming in Lua - (2008-06-30)


Back to
Old trackways and routes near Melksham
Previous and next
or
Horse's mouth home
Forward to
For loop - checked once, or evety time? Ruby v Perl comparison and contrast
Some other Articles
A simple example - XML from a Ruby program
History is all around us
A more informed decision than ever before
For loop - checked once, or evety time? Ruby v Perl comparison and contrast
__index and __newindex in Lua - metatable methods
Old trackways and routes near Melksham
The bull on the footpath
A walk on the Kennet and Avon
Error trapping in Lua - no exceptions.
Hotel booking in Melksham made easy!
4291 posts, page by page
Link to page ... 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86 at 50 posts per page


This is a page archived from The Horse's Mouth at http://www.wellho.net/horse/ - the diary and writings of Graham Ellis. Every attempt was made to provide current information at the time the page was written, but things do move forward in our business - new software releases, price changes, new techniques. Please check back via our main site for current courses, prices, versions, etc - any mention of a price in "The Horse's Mouth" cannot be taken as an offer to supply at that price.

Link to Ezine home page (for reading).
Link to Blogging home page (to add comments).

You can Add a comment or ranking to this page

© WELL HOUSE CONSULTANTS LTD., 2014: Well House Manor • 48 Spa Road • Melksham, Wiltshire • United Kingdom • SN12 7NY
PH: 01144 1225 708225 • FAX: 01144 1225 899360 • EMAIL: info@wellho.net • WEB: http://www.wellho.net • SKYPE: wellho

PAGE: http://www.wellho.net/mouth/2710_-in ... thods.html • PAGE BUILT: Thu Sep 18 15:30:25 2014 • BUILD SYSTEM: WomanWithCat