Since I don't know how familiar you are with Lua in general, my explanation may be hard to understand.
First of all the specific problem you are having is because of this line:
In Lua terms, this line first runs the player:new() function, takes whatever value that function returns, and makes testplayer equal to it. Since player:new() doesn't return any value, testplayer is made equal to nil, which is equivalent to never initializing testplayer at all.
The other problem you are having is that you are not creating new objects from your class. In your current code you are attempting to essentially make testplayer equal the "player" class. Instead, you need to create a new object from the blueprint that is the "player" class. I apologize if that was hard to understand.
The quick fix for your problem is as follows:
Code: Select all
player = {name, level, class}
function player:new()
local obj = {} --First line to add, this creates a new table called obj. Check the Lua documentation if you don't know what "local" means here.
setmetatable(obj, self) --Line change here, this sets the metatable of your new object to the classes metatable, this is essentially what makes "obj" an object created from the class "player"
self.__index = self
return obj --Second line to add, this returns the new object you just created from your class.
end
Here's the new code in total without my comments:
Code: Select all
--OOP Sandbox
player = {name, level, class}
function player:new()
local obj = {}
setmetatable(obj, self)
self.__index = self
return obj
end
testplayer = player:new()
testplayer.name = "testplayer" --errors are coming from these lines
testplayer.level = 80 -- here
testplayer.class = "Warrior" --and here
If you'd like, you can add this to the end so you can see what testplayer is initialized to when you run that code in LOVE:
Code: Select all
function love.draw()
love.graphics.print("testplayer.name = " .. testplayer.name, 50, 50)
love.graphics.print("testplayer.level = " .. testplayer.level, 50, 75)
love.graphics.print("testplayer.class = " .. testplayer.class, 50, 100)
end