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

标签 oop lua coronasdk

我目前正在使用我正在创建的 Corona 应用程序来解决这个问题。

我的文件结构如下: 应用程序 -> 类 -> 对象 -> 船舶

App文件夹中有main.lua、menu.lua、level.lua和Class.lua。在Classes文件夹中有Object.lua。在“对象”中,ship.lua 以及最后在“船舶”中是我的不同船舶,即玩家和敌人。

我关注了this tutorial我的代码几乎与他的(玩家和敌人类)完全相同,但仍然在 Class.lua 中收到此错误

“‘setetatable’的错误参数 #2(nil 或预期的表)”

我收到错误的代码是

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文档,需要类.lua 在 mai、菜单和 level.lua 等中,但没有任何效果。

任何帮助将不胜感激。

谢谢

最佳答案

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)。

Base = Class() 行逐步执行 Class

function Class(Super)

该函数采用一个名为 Super 的参数

Super = Super or Base

您通过使用默认值Base 允许Super 参数为零/不传递。 此调用 Base = Class() 未传递值,因此该行 Super = Super 或 BaseSuper 设为 nil ,因此计算结果为 Super = nil 或 Base 但是全局 Base 也是 nil,因为它尚未被分配,所以你得到 super =零

local prototype = setmetatable({}, Super)

此行然后尝试使用 Super (从之前的行分配),但正如我们刚刚看到的,它是 nil 因此您的错误。

教程中您错过的部分(或至少在您发布的代码片段中错过的部分)是极其重要 local Base上面 Class 函数定义。

关于oop - 错误的参数 #2 到 'setmetatable'(nil 或预期的表)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27907581/

相关文章:

lua - 为什么我的球不旋转? - lua - 电晕

coronasdk - 避免在 Corona SDK 中发生碰撞

c# - 遍历控件并使用函数

string - Lua 字符串模式 - 更短的代码

matrix - 将 Corona SDK 中的图 block 合并为一个词来表示 Breakout 游戏网格?

c - C进程中的Lua内存泄漏

ubuntu - 更改redis-server使用的lua版本

c++ - 在 Visual Studio 2017 中使用函数从 main 创建和初始化数组

java - android中用户定义的对象数组

C# 无法访问类的基本属性(只能继承)