This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
trajing's profile picture

How to use metatables?

Started by trajing, 25 November 2014 - 03:28 PM
trajing #1
Posted 25 November 2014 - 04:28 PM
I've checked the Lua 5.1 reference manual, but it's way over my head. Could someone give me a basic explanation of how to make and use metatables? I'm working on a game engine and I feel like metatables will be the easiest way to set it up.
KingofGamesYami #2
Posted 25 November 2014 - 04:43 PM
metatables are basically tables that tell a table what to do.

This is a simple piece of code demonstrating OO with metatables:

local base = {say = function( self, text ) print( self.name .. ": " .. text ) end }
local myTable = {name="King"}
local mt = {
  __index = base
}
setmetatable( myTable, mt )
myTable:say( "hello" )

Once you know how to make a metatable, this is a great guide to what you can do.