如何在 Lua (Love2D) 中的库中定义 class?

How to define a class within a library in Lua (Love2D)?

我已经尝试在名为“Point”的名为“basic.lua”的文件上定义我的 class,并尝试在文件“main.lua”上实现它,但我不断得到此错误:

Error

Syntax error: basic.lua:3: '(' expected near 'Point'



Traceback

[C]: at 0x7ffc269728f0
[C]: in function 'require'
main.lua:3: in function 'load'
[C]: in function 'xpcall'
[C]: in function 'xpcall'

这是我的代码“basic.lua”

return {

  function Point(self, x, y)
    local Point = {

      x = x;
      y = y;

      AsString = function(self)
          print("{x: " + self.x + ", y: " + self.y + "}");
      end;
      
    }
    return Point;
  end;

};

这是我的代码“main.lua”

function love.load()

    local Basic = require("basic");

    PlayerAcceleration = Basic.Point:new{1, 2};
    PlayerVelocity = Basic.Point:new{0, 0};
    PlayerPosition = Basic.Point:new{0, 0};

    love.graphics.print(PlayerAcceleration.AsString(), 0, 0, 0, 1, 1, 0, 0, 0, 0);

end;

我一直在为 Lua 的 class 苦苦挣扎,所以我们将不胜感激。

你的模块 returns 一个 table 但在那个 table 构造函数中你试图定义一个全局函数 Point。您不能像那样创建 table 字段。这是无效语法。

return { function a() end }

使用

return { a = function() end }

相反。

PlayerAcceleration.AsString()

不会工作。使用 PlayerAcceleration.AsString(PlayerAcceleration)PlayerAcceleration:AsString()

否则 AsString 的参数 self 将为 nil,当您尝试在函数体中对其进行索引时会导致错误。

"{x: " + self.x + ", y: " + self.y + "}" 不是您在 Lua 中连接字符串的方式。使用 Lua 的连接运算符 .. 而不是 +.

此外,您调用的 Basic.Point:new 不存在。请做一个 Lua 初学者教程,阅读 Lua 中的编程和 Lua 参考手册,然后再继续尝试实现 类。