I have never done any OOP and I am having trouble with instance v refference and the scope of 'self'
I have been reading here -
http://www.lua.org/pil/16.html
But I still can't get it right.
The erroe I am getting is "44: attempt to index local 'self' (a nil value)"
Here is my code - line 44 is marked
Can someone please explain what I am doing wrong. Is there a good link to something about what I call 'scope'. What do you call it in LÖVE / Lua ??
Code: Select all
function love.load()
objects = {}
local button1 = newTextButtonToggle()
local button2 = newTextButtonToggle()
button1.xpos = 50
button2.xpos = 150
objects = {button1, button2}
end
function love.draw()
for index = 1, 2 do
local button = objects[index]
love.graphics.print(button.currentvalue, button.xpos, button.ypos, 0, 1, 1, 0, 0, 0, 0)
end
end
function love.update()
end
function love.mousereleased()
local index
local object
for index = 1, #objects do
object = objects[index]
if object['click'] then
object.click()
end
end
end
function newTextButtonToggle()
return
{
xpos = 0,
ypos = 0,
width = 50,
height = 20,
initvalue = 'text',
altvalue = 'alt text',
currentvalue = 'text',
click = function (self)
self.currentvalue = 'clicked'
end
}
end
function love.load()
objects = {}
local button1 = newTextButtonToggle()
local button2 = newTextButtonToggle()
button1.xpos = 50
button2.xpos = 150
objects = {button1, button2}
end
function love.draw()
for index = 1, 2 do
local button = objects[index]
love.graphics.print(button.currentvalue, button.xpos, button.ypos, 0, 1, 1, 0, 0, 0, 0)
end
end
function love.update()
end
function love.mousereleased()
local index
local object
for index = 1, #objects do
object = objects[index]
if object['click'] then
object.click()
end
end
end
function newTextButtonToggle()
return
{
xpos = 0,
ypos = 0,
width = 50,
height = 20,
initvalue = 'text',
altvalue = 'alt text',
currentvalue = 'text',
click = function (self)
self.currentvalue = 'clicked' -- *** This is line 44 ***
end
}
end