Classic style OO code - in Lua
Archive - Originally posted on "The Horse's Mouth" - 2015-11-05 18:49:58 - Graham EllisLua tables can hold not only data values, but also functions - those functions defining behaviours. See [here].
However, if you have a lot of tables (data items) all of which require the same code attached, that's not efficient and so you can set up a metatable - a subsidiary table of extra information - which can be shared between lots of tables. I've just introduced this concept on this week's course - my example is [here].
Taking a further step, a table named after a data type can be used to hold common code for that type in addition to the metatable, and that provides an ability to write something close to "classic" OO code in Lua:
south = train.new(3,78,"06:42","Southampton")
north = train.new(1,79,"07:48","Swindon")
services = {north,south}
for k,service in ipairs(services) do
print(k,service)
print(service:getCapacity())
end
Full code, including implementation, [here]
We run Lua Courses for both newcomers to programming, and for those with prior programming experience. Public course run every few month in Melksham, Wiltshire, England (about 100 miles west of London), and if you have a group of delegates we can train you on site in many different countries.