Self calls don't work in custom functions (SOLVED)


#1

When I call self.x to reference a property in init it works just find, but in get_story it returns an error. When I reference story in get_story it returns and empty string, but returns what I assign to it when I reference it in the init function.

go.property("x", 0)
go.property("y", 0)
local story

function get_story(self)
	print(self.x)
	return story
end

function init(self)
	local f = io.open(sys.get_save_file("laser", "grid_data"), "r")
	local dataS = f:read("*a")
	local data = json.decode(dataS)
	--print(dataS)
	f:close()
	print(self.x, self.y)
	story = data[self.x][self.y]
	print(story)
end

#2
go.property("x", 0)
go.property("y", 0)
local story

function get_story(self)
	print(self.x)
	return story
end

function init(self)
	print(self.x, self.y)
	story = "something"
	print(get_story(self))
end

This works for me just fine.


#3

Try calling it on a cell from the mainscript. The cell is a factory product calling the generated reference from factory.create as self. How do i reference the data of a factory product from a seperate script since the getter method doesnt work.


#4

What factory.create returns is not a reference, it is just the hashed ID of the new object. Basically just its name. You can’t use that as self. Are you used to using another game engine? With Defold you generally don’t call functions on game objects. If you want to communicate between objects you use message passing. Or, if you just need to transfer data you can use go.get and go.set with script properties, though the data types you can use with script properties are limited. Another option is to use a lua module with a lookup table or whatever (you can use a hashed ID as a table key for example).

There was another thread here recently about setting and getting stuff from factory-created objects.

Also, it’s generally a bad idea to define global functions (any custom function you define without the local keyword is global). It’s better to put things like that in a module. It’s way too easy to forget that you defined that name globally and cause yourself all sorts of weird bugs and headaches. A bit more about that in this thread.


#5

You need to pass self to the function. It is not something the engine will do for you.


#6

thanks I got it sorted