Page 1 of 1

[SOLVED]Can't call functions from other class

Posted: Wed Apr 20, 2016 9:21 pm
by Vimm
I'm trying to get used to using classes so I have a spawn class and a game class, the game class is supposed to call the spawn class's draw function, but it gives me the error "attempt to call function "draw" a nil value"

can anyone tell me what I need to change?

Re: Can't call functions from other class

Posted: Wed Apr 20, 2016 9:50 pm
by Ikroth
The problem is you're using global variables inside of your class functions.

In game.lua, you write:

Code: Select all

function Game:new()
	require "platformSpawn"
	platform = Platform()
end
platform is in the global scope by default.

Inside platformSpawn.lua, there is also this function:

Code: Select all

function createPlatform()
	platform = 
		{
			x = love.graphics.getWidth(),
			y = love.math.random(0, love.graphics.getHeight()),
			width = 256,
			height = 16
		}
	return platform
end
The platform inside of there refers to the same platform in the global scope, so it overwrites whatever platform was previously. You can confirm this by printing out platform in createPlatform before and after creating the table.

Since createPlatform is called during update, when it moves on to draw, platform is now a table that doesn't have a draw function. That's why you get that specific error.

So, you could fix it by using local variables instead of global variables wherever possible, something like:

Code: Select all

function createPlatform()
	local platform = { ... }
	return platform
end


Re: Can't call functions from other class

Posted: Wed Apr 20, 2016 9:55 pm
by Vimm
Ikroth wrote:The problem is you're using global variables inside of your class functions.

In game.lua, you write:

Code: Select all

function Game:new()
	require "platformSpawn"
	platform = Platform()
end
platform is in the global scope by default.

Inside platformSpawn.lua, there is also this function:

Code: Select all

function createPlatform()
	platform = 
		{
			x = love.graphics.getWidth(),
			y = love.math.random(0, love.graphics.getHeight()),
			width = 256,
			height = 16
		}
	return platform
end
The platform inside of there refers to the same platform in the global scope, so it overwrites whatever platform was previously. You can confirm this by printing out platform in createPlatform before and after creating the table.

Since createPlatform is called during update, when it moves on to draw, platform is now a table that doesn't have a draw function. That's why you get that specific error.

So, you could fix it by using local variables instead of global variables wherever possible, something like:

Code: Select all

function createPlatform()
	local platform = { ... }
	return platform
end

*facepalm*
you're right, that was the issue, I SHOULD KNOW THIS
im disappointed in me XD
thanks! :D