@goopdev:
Code: Select all
local texture
local playerX, playerY
local blocks
local Block = {}
Block.colors = {
{170, 252, 74},
{232, 148, 12},
{255, 0, 100},
{ 12, 15, 232},
{ 13, 255, 148}
}
function Block.draw(block) -- I defined block explicitly, because i detest using the implicit variable "self".
love.graphics.setColor(Block.colors[block.colorIndex])
love.graphics.draw(texture, block.x, block.y)
end
function Block.new(x,y)
local result = {} -- creates a new table
result.x, result.y = x,y
result.colorIndex = love.math.random(5)
result.draw = Block.draw -- assigns the function to this field; this could also be done with metatables or a number of other ways
return result
end
function love.load()
texture = love.graphics.newImage("assets/Prototype.png")
blocks = {}
for i=1,10 do
blocks[i] = Block.new(love.math.random(300), love.math.random(300))
end
playerX, playerY = 20, 10
end
function love.draw(dt)
love.graphics.draw(texture, playerX, playerY)
for i,k in ipairs(blocks) do
k:draw() -- or k.draw(k)
end
end
Also, assigning nil to any variable is pointless, unless you have the local keyword before them, but then (i think) you don't need to assign anything to them either to make them exist.
raidho36 wrote:Yep, colon notation automatically passes class instance to the function as "self".
Just a minor corrections to this, the only thing colon notation does is that if it is used when
defining a function, it will put a hidden first parameter into the argument list, that can be referred to by "self", and if used when calling a function, the first parameter passed will be wherever you called the function from.
These needn't correlate, so they are a playground for blunders.
Code: Select all
local t = {}
function t.f(a,b) return self,a,b end
function t:g(a,b) return self,a,b end
t.f(1,2) --> nil, 1, 2
t:f(1,2) --> nil, t, 1
t.g(1,2) --> 1, 2, nil
t:g(1,2) --> t, 1, 2
raidho36 wrote:You only need to call the function like this with dot notation, but since colon notation exists it's not very useful.
Hopefully you don't mean that it's not very useful in general, since it does have its uses, that said, i do prefer to write out an extra first param explicitly myself as well, at least in the definition part; calling with : is fine as long as you know what you're doing.
Edit:
airstruck wrote:raidho36 wrote:But more importantly, you never create new table in the "new" function, instead you assign new values to fields of already existing single table. You should instead use something like this:
You are contradicting yourself, you just created a new table in your "new" function.
Well, the op didn't, i think he meant that; also:
Code: Select all
Foo = { }
function Foo.new ( bar )
self = setmetatable ( { }, { __index = Foo } )
self.bar = bar
return self
end
Nothing really wrong with this example code, though i'd not include the new "constructor" in the table of "methods" one gives to an "object", unless it'd be a "copy constructor".