Hi everyone,
I get the following error when attempt to create a simple class for storing data. Any ideas?
main.lua:17: attempt to call method 'createPC' (a nil value) stack traceback:
Characters = Core.class()
function Characters:init()
self.player = {}
end
function Characters:CreatePC()
self.player.hp = 10 --fixed hp
self.player.weapon = math.random(0, 2) * 2 + 4 --weapon does either 1d4, 1d6 or 1d8 damage
self.player.ac = math.random(0, 2) * 3 --armor is either +0, +3 or +6
end
local c = {}
c=Characters.new()
c:createPC(x)
Comments
Fragmenter - animated loop machine and IKONOMIKON - the memory game
'.' instead of ':' too.
And () instead of {}!
Use {} to define tables; and you can use : or . to call functions from classes.
. references the class, : references the object.
You can always use . but then you have to pass the object as first parameter.
Example:
player1.doSomething(player1) is the same as
Player.doSomething(player1) is the same as
player1:doSomething()
player1.doSomething() would give an error, because with the single dot you call the class method which expects an object (which will then referred to by 'self').
With the colon (:), player1 passes itself to the function.
This mechanic is not exclusive to Lua, take for example PHP:
Player::doSomething(player1); or
player1->doSomething();
Please someone correct me if I got something wrong, I'm only 85% sure of what I'm talking about