How to structere/organise code in Defold

First of all, thank you very much for providing defold free of charge. It’s a great engine (i like especially that it works flawlessly under linux :)).

I’am still learing defold and just startet out with tutorials, but I am already trying to give my code a structure to be prepared when the project will grow in the future.

Therefore I have a question. If i want to split up my code in logical pieces…how should i do it?

My current solution looks like that:

spaceship.script (attached to spaceship game object)

local playerinput = require("../input/playerinput")

function init(self)
	playerinput.init(self)
end

function update(self, dt)
	playerinput.update(self, dt)
end

function on_input(self, action_id, action)
	playerinput.on_input(self, action_id, action)
end

playerinput.lua

local playerinput = {}

playerinput.init = function(self)
	self.dir = vmath.vector3()
	msg.post(".", "acquire_input_focus")
	self.id = go.get_id()
end

playerinput.update = function(self, dt)
	if vmath.length_sqr(self.dir) > 1 then
		self.dir = vmath.normalize(self.dir)
	end
	local p = go.get_position(self.id)
	go.set_position(vmath.vector3(p + self.dir * dt * 150))
	self.dir = vmath.vector3()
end

playerinput.on_input = function(self, action_id, action)
	if action_id == hash("up") then
		self.dir.y = 1
	elseif action_id == hash("down") then
		self.dir.y = -1
	elseif action_id == hash("left") then
		self.dir.x = -1
	elseif action_id == hash("right") then
		self.dir.x = 1
	end
end

return playerinput

Or is it better just do add several lua.script files in one object?

Thanks in Advance…chris

I like the way you do it. But it ends up being about taste. Some people like more smaller files, others find that breaking things up into many smaller files makes it harder. The important thing is what works for you with being productive. Black boxing code is good. But switching between files often unnecessarily is time consuming. So it’s situational.

I personally break up things as logically as I can into their own .lua modules where it makes sense. My .script files usually do some setup, and then call updates of required files from the script update.

1 Like

Thank you Pkeod for your Feedback :slight_smile:

I am just wondering if its better to add just one script file on an object and then require some lua-file or not using the lua-file but instead add several script-files (each with its own engine-callback-function for example update) to the object. I hope you understand what i mean…sorry for my bad englisch…

If I understand you right, I would go with a single .script per GO which requires one or more .lua modules.

1 Like

thank you