Search code examples
lualove2d

Love2D Lua no idea why this doesn't work


Apologies for the unhelpful title but I really don't know what to call this. Anyway, I can't tell why this works:

local entity = require "entity"
entity:new(5,10,15,6)
local test = entity
print(test.x,test.y)

...but this doesn't...

local entity = require "entity"
local test = entity:new(5,10,15,6)
print(test.x,test.y)

Entity.lua simple contains:

local Entity = {}

function Entity:new(x,y,w,h)
  self.x = x
  self.y = y
  self.width = w
  self.height = h
end

return Entity

Solution

  • Case 1:

    variable entity gets table which is returned from Entity.lua.

    When you call Entity:new() in Entity.lua all the variable initialization is performed on table(object) entity. So, entity has variables x, y, width and height. You assigned table to test and printed it.

    It works.

    Case 2:

    local test = Entity:new().

    Here variable test takes return value of method new(), which is nil in this case, because function doesn't return any value.

    It prints an error because table test doesn't have any keys called x and y.