【问题标题】:Problems working with the 'classic' library written by rxi使用 rxi 编写的“经典”库时出现问题
【发布时间】:2020-10-04 10:17:31
【问题描述】:

目前,我正在尝试学习如何使用 Love2D 框架制作视频游戏。一个教程建议使用 rxi 的“经典”库来使用 OOP。

目前,我正在尝试创建一个shape.lua 文件来描述一般形状(无论是圆形、矩形还是三角形)。这是我的基类,我将使用它派生一个描述矩形的子类,称为rectangle.luashape.lua 文件只会在这些矩形在屏幕上移动时处理其子类的移动。

但是,每当我尝试运行 main.lua 文件时,此错误仍然存​​在:

Error

rectangle.lua:16: attempt to index global 'Shape' (a nil value)


Traceback

rectangle.lua:16: in main chunk
[C]: in function 'require'
main.lua:3: in function 'load'
[C]: in function 'xpcall'
[C]: in function 'xpcall'

以下是我的main.lua 文件:

function love.load()
  Object = require "classic"
  require "rectangle"
  require "shape"
  require "circle"

  r1 = Rectangle(50, 50, 90, 60, 100)
  r2 = Circle(350, 80, 40)
end

function love.update(dt)
  r1:update(dt)
  r2:update(dt)
end

function love.draw()
  r1:draw()
  r2:draw()
end

这是我的 shape.lua 文件:

Shape = Object:extend()

function Shape:new(x, y)
  self.x = x
  self.y = y
  self.speed = 100
end

function Shape:update(dt)
  self.x = self.x + self.speed * dt
end

rectangle.lua文件如下

Rectangle = Shape:extend()

function Rectangle:new(x, y, width, height)
    Rectangle.super.new(self, x, y)
    self.width = width
    self.height = height
end

function Rectangle:draw()
    love.graphics.rectangle("line", self.x, self.y, self.width, self.height)
end

我现在想要的最终结果是一个圆形和一个矩形在屏幕上以相同的速度向右移动。

如果有帮助,我也在使用 Atom 文本编辑器。

我希望答案坚持使用“经典”库,所以如果有人使用它,非常感谢帮助!

【问题讨论】:

    标签: lua love2d


    【解决方案1】:

    Shape 是您的rectangle.lua 范围内的nil

    require "rectangle" 执行该文件中的代码,其中Rectangle = Shape:extend() 立即导致索引Shape 出错。

    require "shape" 添加到rectangle.lua 应该可以解决此问题。

    另一种选择是在您的main.lua 中切换require "shape"require "rectangle",但在您真正需要的地方需要它会更好。

    【讨论】:

    • 谢谢!它似乎已经解决了这个问题。不过,这是一个奇怪的库。
    猜你喜欢
    • 2023-04-11
    • 1970-01-01
    • 2018-10-14
    • 1970-01-01
    • 1970-01-01
    • 2011-05-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多