错误的参数#2到'setmetatable'(nil或表预期)?

时间:2015-01-12 17:29:45

标签: oop lua corona

我目前使用我正在制作的电晕应用程序坚持这一点。

我有一个如下文件结构: 应用 - >课程 - >对象 - >一般

在App文件夹中是main.lua,menu.lua,level.lua和Class.lua。在Classes文件夹中有Object.lua。在物体中,ship.lua和最后在船上是我不同的船只,即玩家和敌人。

我跟着this tutorial,我的代码与他的(bar player和enemys类)几乎完全相同,但仍然在Class.lua中收到此错误

“错误的论点#2到'setetatable'(预期为零或表)”

我收到错误的代码是

function Class(Super)
  Super = Super or Base
  local prototype = setmetatable({}, Super) -- receive error here
  prototype.class = prototype
  prototype.super = Super
  prototype.__index = prototype
  return prototype
end

Base = Class()

function Base:new(...)
  local instance = setmetatable({}, self)
  instance:initialize(...)
  return instance
end

function Base:initialize() end

function Base:get()
  local Instances = self.Instances
  if (not Instances[1]) then local obj = self:new() end
  return table.remove(Instances, 1)
end

function Base:dispose()
  table.insert(self.Instances, self)
end

我已经尝试更改类并将“setmetatable({},Super)”更改为“setmetatable(Super,self)”,将所有类放在一个文件中,我已阅读lua文档,需要类.maa,菜单和level.lua等中的.lua,没有任何效果。

非常感谢任何帮助。

由于

1 个答案:

答案 0 :(得分:2)

function Class(Super)
  Super = Super or Base
  local prototype = setmetatable({}, Super) -- receive error here
  prototype.class = prototype
  prototype.super = Super
  prototype.__index = prototype
  return prototype
end

Base = Class()

执行上面的代码。

您声明一个函数Class,然后调用它(并将其返回值分配给Base)。

Class行开始执行Base = Class()

function Class(Super)

该函数接受一个名为Super

的参数
Super = Super or Base

通过使用默认值Super,您允许Base参数为nil / notassed。 此调用Base = Class()未传递值,因此此行Super = Super or Base的{​​{1}}为Super,因此评估为nil,但全局Super = nil or Base nil尚未分配,因此您获得Base

Super = nil

然后,此行尝试使用local prototype = setmetatable({}, Super) (从之前的行分配),正如我们刚刚看到的那样Super因此您的错误。

您错过的教程(或至少在您发布的代码段中遗漏的)中的至关重要的 nil {{1功能定义。