将第二个参数传递给'setmetatable'函数的参数不正确(应为表类型或nil)。

我目前在创建一款 Corona 应用程序时遇到了问题。

我的文件结构如下: App -> Classes -> Objects -> Ships

在 App 文件夹中有 main.lua、menu.lua、level.lua 和 Class.lua。在 Classes 文件夹中有 Object.lua。在 Objects 中有 ship.lua,最后在 Ships 中有我的不同飞船,即玩家和敌人。

我按照 这篇教程 来编写代码,我的代码与他的几乎完全相同(玩家和敌人类除外),但仍然在 Class.lua 中收到以下错误:

"bad argument #2 to 'setetatable'(nil or table expected)"

我收到错误信息的那段代码是:

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 文档,在 mai、menu 和 level.lua 中需求了 Class.lua 等等,但都没有成功。

任何帮助都将不胜感激。

谢谢。

点赞
用户258523
用户258523
function Class(Super)
  Super = Super or Base
  local prototype = setmetatable({}, Super) -- 这里收到错误
  prototype.class = prototype
  prototype.super = Super
  prototype.__index = prototype
  return prototype
end

Base = Class()

执行上述代码。

你声明了一个函数 Class,并且调用它(将返回的值赋值给 Base)。

Base = Class() 这一行开始,逐步执行 Class 函数。

function Class(Super)

这个函数有一个名为 Super 的参数。

Super = Super or Base

你允许 Super 参数是 nil 或者未传递,使用默认值 Base。这里调用 Base = Class() 没有传递任何值,所以这一行 Super = Super or Base 中的 Supernil,因此结果是 Super = nil or Base,但是全局变量 Base 也是 nil,因为它还没有被赋值,所以 Super 值为 nil

local prototype = setmetatable({}, Super)

此行尝试使用上一行中的 Super,但是,就像我们刚刚看到的那样,它是 nil,因此会出现错误。

你错过了教程中至关重要的 local Base 行,它位于 Class 函数定义的上面。

2015-01-12 17:45:57