Basic concepts of OOP
Posted: Thu Feb 16, 2012 12:04 pm
Hello, after learned how to manipulate well enough tables with inserts/remove/ipairs I decided upgrade functions with some minimal OO and understand the basic principles. So I used this and all worked well.
-- main.lua
-- enemy.lua
Then I tried to simplify and understand if was possible merge table "enemies" and class "enemy:" in the same table and so I failled when using enemy:update. Do I must always reserve "enemy" as function variable or I'm not doing the right thing to achieve a function/table mix (if possible)?
Also I'd like to know if it's possible use something like enemy:add({ race = "half-human", weapon = "Hammer" }) and then skip in-between function args like define HP? Thank you in advance!
-- main.lua
Code: Select all
function love.load()
require ("enemy")
enemy:init()
enemy:add("elf",20)
enemy:add("human")
enemy:add("dwarf",30)
enemy:add()
end
function love.update(dt)
enemy:update(dt)
end
function love.draw()
enemy:draw()
end
function love.quit()
end
Code: Select all
enemy, enemies = {},{}
function enemy:init()
local instance = {}
setmetatable(instance, {__index = enemy})
end
function enemy:add(race,hp)
local enemy = {}
enemy.race = race or "human"
enemy.hp = hp or 15
table.insert (enemies,enemy)
end
function enemy:update(dt)
for i,v in pairs (enemies) do
if v.race == "elf" and v.hp < 100 then v.hp = v.hp + 2 end
end
end
function enemy:draw()
for i,v in pairs (enemies) do
love.graphics.print (i.." "..v.race.." "..v.hp,0,15*i)
end
end
Code: Select all
enemy = {}
function enemy:init()
local instance = {}
setmetatable(instance, {__index = v})
end
function enemy:add(race,hp)
local v = {}
v.race = race or "human"
v.hp = hp or 15
table.insert (enemy,v)
end
function enemy:update(dt)
for i,v in pairs (enemy) do
if v.race == "elf" and v.hp < 100 then v.hp = v.hp + 2 end
end
end
function enemy:draw()
for i,v in pairs (enemy) do
love.graphics.print (i.." "..v.race.." "..v.hp,0,15*i)
end
end