Lua Class Inheritance

Questions about the LÖVE API, installing LÖVE and other support related questions go here.
Forum rules
Before you make a thread asking for help, read this.
Post Reply
User avatar
Drakkahn
Prole
Posts: 28
Joined: Sat Jan 17, 2015 11:09 pm

Lua Class Inheritance

Post by Drakkahn »

This doesn't deal so much with Love2D as it deals more with lua. When I call a function from an inhereted "class" I get the error:

Code: Select all

class_base_block.lua:25: attempt to index local 'self' (a nil value)

Traceback

class_base_block.lua:25: in function 'activate'
class_conditional_block.lua:24: in function 'update'
main.lua:83: in function 'update'
[C]: in function 'xpcall'

class_base_block.lua

Code: Select all

base_block =
{

	x=0,
	y=0,
	action=nil							--function of what to do
	
}
base_block.__index=base_block



function base_block:new(variables)

	variables=variables or {}
	local self=setmetatable(variables,self)
	print("A")
	return self

end



function base_block:activate(...)
	return tostring(self.x)

end

class_conditional_block.lua

Code: Select all

conditional_block = base_block:new(
{

	connected={}						--all the blocks connected to this one
	
})
conditional_block.__index=conditional_block



function conditional_block:new(variables)

	variables=variables or {}
	local self=setmetatable(variables,self)
	print("Z")
	return self

end



function conditional_block:update()

	print("ZED: " .. self.activate())

end
User avatar
Inny
Party member
Posts: 652
Joined: Fri Jan 30, 2009 3:41 am
Location: New York

Re: Lua Class Inheritance

Post by Inny »

This line:

Code: Select all

print("ZED: " .. self.activate())
You want this:

Code: Select all

print("ZED: " .. self:activate())
The colon operator is syntactic sugar, which implies the self variable as the first parameter to the function, seen in Lua 2.5.8 and 2.5.9.

In short, think along these lines:

Code: Select all

-- equivalent declarations
function object:method(parameter) end
object.method = function(self, parameter) end

-- equivalent invocations
object:method(27)
object.method(object, 27)
User avatar
Drakkahn
Prole
Posts: 28
Joined: Sat Jan 17, 2015 11:09 pm

Re: Lua Class Inheritance

Post by Drakkahn »

How can I fix this?
User avatar
kikito
Inner party member
Posts: 3153
Joined: Sat Oct 03, 2009 5:22 pm
Location: Madrid, Spain
Contact:

Re: Lua Class Inheritance

Post by kikito »

Use : instead of . when you call methods. self:activate() instead of self.activate()
When I write def I mean function.
Post Reply

Who is online

Users browsing this forum: Bing [Bot] and 83 guests