How to define global functions?

Im running simmilar code in each script of my game objects in order to collect data on the size and scale.

	local _, window_height , _= window.get_size()
	local sprite_height = go.get("shep#shep_sprite", "size.y") 
	local sprite_yscale = go.get("shep#shep_sprite", "scale.y") 
	local go_yscale = go.get_scale().y 
        ....
        do_sth()

I want to define a global funcion collect_data(game_object), which will return window_height, sprite_height_sprite_yscale, go_yscale. I guess the code would look like

function collect_data(go)
	local _, window_height , _= window.get_size()
	local sprite_height = go.get("shep#shep_sprite", "size.y") 
	local sprite_yscale = go.get("shep#shep_sprite", "scale.y") 
	local go_yscale = go.get_scale().y 
end

Where can I oput this definition, so I can use the function in each of my scripts, instead of writting the same code over and over again?

Sharing code among scripts can be done with Lua modules, which are just Lua files used for sharing code with other Lua files. The difference between modules are scripts are:

  • Module file extension is .lua, instead of .script.
  • Script files are attached to game objects, whereas modules are standalone files.
  • If a script file contains an engine lifecycle function (e.g. init(), update(), etc.), then it will be called automatically by the engine. Functions inside modules are called by the developer, not the engine.

See the following documentation to learn about modules:

2 Likes