Here is a working example:
enemy.lua:
local Enemy = {x = 0, y = 0} Enemy.metatable = {} Enemy.metatable.\_\_index = Enemy function Enemy.new(t) return setmetatable(t, Enemy.metatable) end function Enemy:showX() -- for some reason naming it "getX" doesn't work! print(self.x) end return Enemy
main.lua:
local enemy = require( "enemy") local e1 = enemy.new({x=10, y=20}) print("e1.y: "..e1.y) local e2 = enemy.new({x=300, y=5}) print("e2.y: "..e2.y) e2:showX()
I got the code from corona’s guide here but kind of turned it into a class/module hybrid because the original non-module way did not allow me to create instances in another file and I don’t know why.
What I noticed is that with this example above I will always have to setup my functions with a colon operator instead of a dot if I want to access any of the passed arguments in the “new” function.
My questions are:
1- Can I specify x,y as args that the function “new” takes instead of an empty table? and how would that work ?
2- Can I reference “self.x, self.y” in another function using the dot operator instead of the colon? without adding “self” as an argument, like this:
function Enemy.showX() instead of: function Enemy:showX()