Object inheritance
Posted: Fri Jul 05, 2019 10:38 pm
for a while I hopped over to C# (while trying out unity) and after not enjoying the language and engine, I came back to lua. Ever since then I've been learning to do oop in lua, however one issue I've run into is inheritance, I somewhat solved one half of inheritance with functions and variables carrying over to the child objects, however I can't seem to get one feature working, that being inheriting parent functions without overwriting them.
here's the code I have for the base object:
and some example code from the player object
here's the code I have for the base object:
Code: Select all
-- in entity.lua
local Entity = { -- base table with all variables for the entity object
pos = { x=0,y=0 },
dx=0,dy=0,
name="",
stunTimer = 0,
}
-- -- --
Entities = {} -- global table where all entities are stored
-- -- --
function Entity.new( vars )
local entity = setmetatable( table.copy( Entity ), { __index = Entity } ) -- creates entity metatable
for i,v in pairs( vars ) do entity[i] = v end -- takes variables from vars table and moves variables to entity
table.insert( Entities, entity ) -- adds entity to table of all entities ( easier to destroy )
return entity
end
-- -- --
function Entity:update( dt ) -- base update, I want to change so this can be called from any children who inherit entity
print( "entity \""..self.name.."\" does not have an update function!" )
-- ^ will change code once I get this working
end
Code: Select all
-- in player.lua
local Player = { -- base table with all player variables
isPlayer = true,
HP = 0, MAXHP = 3,
canMove = true,
moving = false,
direction = "right",
}
-- -- --
function Player.new()
return ENTITY.new( Player )
end
-- -- --
function Player:update( dt )
-- where I want to call the update function of the 'base' object, entity
end