LUA 元表和类

Dylariant
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')


这是lua中的一个类模块

我有几个问题。

  1. 如果 Class:new() 什么都不做,它的意义何在?

  2. 在 Class:__call(...) 函数的第 19 行 inst:new(...) 中,为什么程序在 Player 表中搜索 :new 函数而不是原始 Class 表?

意思是,当调用 Player("Dylan") 时,会打印“Hello Dylan”而不是“Bye!!”

inst table的meta table不是设置为self,引用Class吗?

代码取自关于 Lua 类的 youtube 视频https://www.youtube.com/watch?v=O15GoH7SDn0

呼吸

这样做时,Player("Bob")我们将输入__call元表中定义的元方法,Player其中Class:__call

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

在这个调用self中是指Player不是Class表,所以当我们创建时inst我们设置它的元表,Player它有一个__index指向自身的值,所以inst:new将等于Player.new(inst, name)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章