Search code examples
classmodulelualove2d

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


I've tried defining my class on a file called "basic.lua" called "Point" and tried to implement it on the file "main.lua" but I keep getting this error:

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'

Here is my code for "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;

};

and here is my code for "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;

I'm struggling with Lua's classes a lot so any help would be appreciated.


Solution

  • Your module returns a table but inside that table constructor you try to define a global function Point. You cannot create a table field like that. This is invalid syntax.

    return { function a() end }
    

    Use

    return { a = function() end }
    

    instead.

    PlayerAcceleration.AsString()
    

    Will not work. Either use PlayerAcceleration.AsString(PlayerAcceleration) or PlayerAcceleration:AsString()

    Otherwise AsString's parameter self will be nil leading to an error when you attempt to index it in the function's body.

    "{x: " + self.x + ", y: " + self.y + "}" is not how you concatenate strings in Lua. Use Lua's concatenation operator .. instead of +.

    Further you're calling Basic.Point:new which does not exist. Please do a Lua beginners tutorial, read the Programming in Lua and the Lua Reference Manual befor you continue trying to implement classes.