OOP question

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()

Hey Abdou23,

  1. Of course you can do that, here’s the class stucture I use.

    local ClassConstructor = {} local Class = {} --the class local ClassMetaTable = {__index = Class} --the class metatable Class.x = 100 Class.y = 100 function ClassConstructor.new(arg) local arg = arg or {} local self = setmetatable({}, ClassMetaTable) --apply arguments self.x = arg.x --x value you want to set self.y = arg.y --y value you want to set return self end

  2. There are only two ways to do this. Use the colon operator or use the object as the first argument.

    local instance = Class.new() --method one instance:show(parameter1, parameter2) --method two instance.show(instance, parameter1, parameter2)

Hope that helps :slight_smile:

Yes, that absolutely helps, thank you. 

Hey Abdou23,

  1. Of course you can do that, here’s the class stucture I use.

    local ClassConstructor = {} local Class = {} --the class local ClassMetaTable = {__index = Class} --the class metatable Class.x = 100 Class.y = 100 function ClassConstructor.new(arg) local arg = arg or {} local self = setmetatable({}, ClassMetaTable) --apply arguments self.x = arg.x --x value you want to set self.y = arg.y --y value you want to set return self end

  2. There are only two ways to do this. Use the colon operator or use the object as the first argument.

    local instance = Class.new() --method one instance:show(parameter1, parameter2) --method two instance.show(instance, parameter1, parameter2)

Hope that helps :slight_smile:

Yes, that absolutely helps, thank you.