Jump to content


MKlegoman357's Content

There have been 76 items by MKlegoman357 (Search limited from 10-February 22)


By content type

See this member's


Sort by                Order  

#246198 Can't wrap head around prototyping and metatables, how to implement this...

Posted by MKlegoman357 on 20 February 2016 - 09:45 PM in Ask a Pro

Lua is more like JavaScript: even though it doesn't have a class system it gives you tools to create your own. In Lua, you can implement OOP in any way you want. Your class system can support operator overloading, function overloading, multiple inheritance and any other features you might think about. Since most of your OOP system will need tables and probably metatables you'll want to learn those. Tables are the best feature of Lua. Metatables allow you to extend them even more.

Both, tables and metatables, should actually be easy to understand, since they are quite basic (but powerful) things. A table is simply a container, where you can store any value under any key. Because of the lack of OOP, tables and functions can actually work together using the "colon" syntax:

local object = { --# define a simple object
  bar = "Hello World!";
}

function object:foo () --# create a function inside that object
  print(self.bar)
end

object:foo() --# prints 'Hello World!'

You can extend tables using metatables. Metatables define what a table should do in certain situations. For example if, when assigning a new value to a table:

local object = {}

object.foo = 1

..you'd want to modify that value before actually assigning it, you could use the '__newindex' metamethod:

local object = setmetatable({}, { --# create a table and change it's metatable
  __newindex = function (t, k, v) --# define the metamethod'
    rawset(t, k, v + 1) --# modify the value
  end;
})

object.foo = 1

print(object.foo) --# prints '2'