@Mells
When you call the function setmetatable, it erases the other metatable and replaces it with the most recent one. It’s usually used for assigning one ‘class’. In order to do proper multiple inheritances, you would need to do a more programming and it gets a bit complicated. Instead I use a simpler method for inheritance that is almost identical to what someone linked to on your forum post:
main.lua
[lua]–NEVER USE GLOBAL OBJECTS. ALWAYS STORE THINGS LOCALLY
local Balls_Class = require (“balls”)
require (“libraries”)
local Game = {}
function Game:startSetup()
local listBalls = Balls_Class.newBalls()
print (listBalls[1].x) – Displays “400”, great until there
listBalls[1]:move(50) – Doesn’t work.How can I access function move() in ball.lua
end
Game:startSetup()[/lua]
balls.lua
[lua]module(…,package.seeall)
–CREATE A CLASS THAT REFERENCES THE BALL CLASS. ITS ONLY USED IN THE BALLS CLASS SO NO NEED FOR IT IN THE MAIN FILE
–ALWAYS RETURN A LOCAL OBJECT OR YOU WILL POLLUTE YOUR GLOBAL SPACE!!!
local Balls_Class = {}
local Ball_Class = require(‘ball’)
function Balls_Class:newBalls()
– GO STRAIGHT INTO MAKING THE LIST TABLE. NO NEED FOR A SETUP
local listBalls = {}
– Set Balls Defaults
local params = {
{ radius=20, xdir=1, ydir=1, xspeed=2.8, yspeed=6.1, r=255, g=0, b=0, posx=400, posy=150 },
{ radius=50, xdir=-1, ydir=-1, xspeed=1.8, yspeed=1.5, r=115, g=23, b=33, posx=200, posy=200},
{ radius=20, xdir=1, ydir=1, xspeed=2.8, yspeed=6.1, r=255, g=0, b=0, posx=400, posy=350 }
}
for i, j in pairs(params) do
print(j.radius)
local param = j
local ball = Ball_Class:newBall(j)
table.insert(listBalls, ball)
–ball = nil
end
return listBalls
end
–RETURNING THE BALL CLASS SO THE VARIABLE INHERITS THE OBJECTS FUNCTIONS
return Balls_Class[/lua]
ball.lua
[lua]module(…,package.seeall)
—THIS CLASS HOLDS ALL FUNCTIONS FOR CREATING THE BALL
local Ball_Class = {}
function Ball_Class:newBall(params)
local default_xpos = display.contentWidth*0.5
local default_ypos = display.contentHeight*0.5
– Create Display Object for Ball
local Ball = display.newCircle(default_xpos, default_ypos, params.radius )
function Ball:move(dist)
print (“Move Ball”)
self.x = self.x + dist – example of accessing a property
self:setFillColor(128,0,0)
end
return Ball
end
return Ball_Class[/lua]
This method is much simpler for making classes and you can perform multiple levels of inheritance without calling every class in the main file.
Side Note: Try not to pollute your global namespace. Use more local variables because it maintains your programs speed and helps in memory management.
Let me know if this helps.
-JT [import]uid: 49520 topic_id: 20965 reply_id: 82867[/import]