I am trying to understand how classes work in order to use them in a sample game I am building. First, I am trying to create an extremely basic class to better understand. My goal is for the instances of this class to have one value and two methods:
instance.color = "red"
instance.alpha() --> prints "orange"
instance.beta() --> prints "blue"
Based on this example from SquidGodDev, I wrote the following:
import 'CoreLibs/sprites.lua'
import 'CoreLibs/graphics.lua'
import 'CoreLibs/object.lua'
class("TestClass").extends(playdate.graphics.sprite)
function TestClass:init()
self.color = "red"
function self.alpha()
print("orange")
end
end
function TestClass.beta()
print("blue")
end
test = TestClass:new()
print(test.color)
test.alpha()
test.beta()
function playdate.update()
end
My expected output is:
blue
orange
red
Instead, I receive the error:
main.lua:21: field 'alpha' is not callable (a nil value)
I'm guessing I'm doing something very obviously wrong or using classes wrong. Can someone help me understand, or point me in the right direction? I am programming on OSX in Nova.
Making TestClass into a table instead of a class makes everything work, but that's not the goal of this exercise.
import 'CoreLibs/sprites.lua'
import 'CoreLibs/graphics.lua'
import 'CoreLibs/object.lua'
--class('TestClass').extends(playdate.graphics.sprite)
--above line causes sim to crash with no error
TestClass = {}
--above line produces expected output
function TestClass:new()
self.color = "red"
function self.alpha()
print("orange")
end
return self
end
function TestClass.beta()
print("blue")
end
test = TestClass:new()
print(test.color)
test.alpha()
test.beta()
function playdate.update()
end
I doubt my other attempted solutions are relevant, but they are:
I tried changing "init()" to "new()", and after some fiddling I was able to print blue, but the methods produced the same error above.
I tried including TestClass.super.new(self) and similar in various places, without any luck.
I tried redefining "update()" instead of the methods described above; this appears to have resulted in the test variable inheriting the sprite update function, as it would not produce the error above, but would also not do anything.
I tried reading the CoreLibs directly, but the "object" and "sprite" libraries use programming that is beyond my knowledge regarding metatables (i.e. __index and __call).