Dylariant
Dylariant

Reputation: 105

LUA Metatable and Classes

local Class = {}
Class.__index = Class

--default implementation
function Class:new() print("Bye!!") end

--create a new Class type from our base class
function Class:derive(type)
  local cls = {}
  cls.type = type
  cls.__index = cls
  cls.super = self
  setmetatable(cls, self)
  return cls
end

function Class:__call(...)
  local inst = setmetatable({},self)
  inst:new(...)
  return inst
end

function Class:get_type()
  return self.type
end


--Create 'Player' class
local Player = Class:derive("Player")

function Player:new(name)
  print("hello " .. name)
end

--Create player instance
plyr1 = Player('Dylan')


This is a Class module in lua

I have a few questions.

  1. What is the point of Class:new() if it does not do anything?

  2. At Line 19 inst:new(...) in the Class:__call(...) function,why does the program search for the :new function in the Player table and not the original Class table?

Meaning, When Player("Dylan") is called, "Hello Dylan" is printed instead of "Bye!!"

Isn't the meta table of inst table set to self, which references Class?

Code is taken from youtube video https://www.youtube.com/watch?v=O15GoH7SDn0 about Lua Classes

Upvotes: 1

Views: 220

Answers (1)

Nifim
Nifim

Reputation: 5031

When doing Player("Bob") we will enter the __call metamethod defined in the metatable of Player which is Class:__call

function Class:__call(...)
  local inst = setmetatable({},self)
  inst:new(...)
  return inst
end

In this call self refers to the Player table not the Class table, so when we create inst we are setting it's metatable to Player which has an __index value that points to itself, so inst:new will be equal to Player.new(inst, name)

Upvotes: 2

Related Questions