Factorio Modding Reference Guide 


=Prologue=
This is a guide to modding.
It should cover (eventually) all the following tasks of modding:

* Adding and modifying items and entities
* Using scripts to modify how the game behaves
* Creating a scenario complete with mission

During this guide, a mod demonstration all the above opportunities is created.

The guide contains large chapters that mostly contain theory that should hopefully bring an understanding of the modding workings.
Each of those chapters contains a subchapter devoted solely to the example mod creation. The cumulative code of all those subchapters forms a working mod, you can also download the complete mod from the mod portal using this [https://mods.factorio.com/mods/Adil/First_mod link]. There might be several releases of this mod, all of them are relevant to a certain part of the guide. Start with 0.1.0, the chapters of this guide will state when next version of the mod should be examined.

Based off FreeER's Step By Step Guide to Modding Factorio.

== The journey ahead ==
To do modding, you'll definitely need to use lua. It is a wonderful language, but I won't be able to devote enough time it deserves in this tutorial. Guess you can finish this tutorial anyway, but later when you embark on your own, you may have to skim at least a [https://learnxinyminutes.com/docs/lua/ short gude] (beware obsoletion!) or [https://www.lua.org/manual/5.3/ lua reference]. There's also almost up-to-date freely-available [http://www.lua.org/pil/contents.html book] written by language creator himself.

Of course, you won't write a mod with a pure lua alone. When the game executes your scripts, it provides a set of special functions and variables for script to use. 
Through the use of those your code can interact with the game world. If you're trying to implement some new behavior you'll definitely need to familiarize yourself with them. 
The best place to do so is the official [[http://lua-api.factorio.com/ api help]], also, the game itself is distributed with copy of that ("doc-html" folder). That documentation is rather laconic, but complete and up to date. Mandatory mention is deserved by [[http://lua-api.factorio.com/latest/Data-Lifecycle.html DataLifecycle]] page of that documentation, it is like well-hidden shorter and crispier version of this opus. 
You can also search through the wiki [[Modding]] section, although its relevance is diminishing over time. (You don't need to read up all that just now, but remember those places when the need arises.)

Obviously you will need a text editor, get one with (lua) syntax highlighting. Examples are: Notepad++, TextPad and Geany.

For the creating of images and icons you may use Photoshop, Paint.net and Gimp.

For testing purposes, it is better to have separate instance of the game with just the base mod installed. This is easily done by copying non-steam version of the game. [[Mods]] and [[Application Directory]] pages might bring additional insight on that if needed.

The game is writing logs, those are useful when something doesn't work. Default file for the last session is factorio-current.log.
Functions like error() and print() output their stuff there. You can also launch the game executable through terminal or command line and then the text output will be duplicated there in real time.

And remember: keep backups! More than one potential mod was lost to freak accidents and miscalculated cleanups.

== Time is not your enemy. Api change is. ==
This guide is not written at the moment you are reading it. The game is in development and so the rules of modding change with it. It is possible, that not everything in this guide will work. If you get runtime script errors, consult with changelog located in '''/data''', use ctrl-f for any related keyword. If the game stops loading see the errors in the logs. Most likely it's some prototype error, those can be overcome by comparing your prototypes with those defined in the base mod.

Of course there's also forums you can turn to for help.

== What is a nature of a mod? ==

During the startup process the game scans '''/mods''' (actually, '''/data''' and '''/mods''') folder for any subfolders and looks up for '''info.json''' file in it. When it finds that, you have a minimal mod.

After that, it runs script files named.
* data.lua
* data-updates.lua
* data-final-fixes.lua
As a result of execution of these files from all mods leave the game with the table describing all objects it can have.
Thus, this is the place to turn to, if you want another faster assembler.

When the gameplay itself begins (new game started, save is loaded) the programm checks the mod folders for control.lua file and executes that. The task of the control.lua file is to register functions that will be called upon one or another event happening. By creatively using those, one can make things act like if they are other things. Teleporters, sentient constructs and quests, it all goes here.

= Time for adventure =

So, by now you have been provided a vague outline of what does it mean to write a mod.
And probably have already found the folder, where mods are to be stored.
From now on lets just assume you did, it's time to do some modding.

This chapter will cover the creation of a basic mod: creation of info file, definition of prototypes, adding translations and coding a new mechanic to the game. The examples below use the code from the "First_mod_0.1.0".

== What is your name? - info.json  information file==
 
Let's begin with the single mandatory item inside the mod: a file that describes what is this mod.
The game evolves, and its format changes somewhat, so it is probably best to peek into the info.json of the most recent "base" mod for guidance. (It is located in factorio/data/base).

So, the format may change by the time you get to read this line, but currently, it is as follows:
<pre>
{
	"name": "1337mod",
	"version": "0.1.0",
	"title": "My super mod",
	"author": "Me",
        "contact": "superboss@mymail.org",
	"dependencies": [
		"base", "133mod >= 0.1.1", 
		"?somemod",
	],
	"description": "My super mod that adds cool stuff. Mandatory install and do not steel.",
	"factorio_version": "0.14",
	"homepage": "my_site.com"
}
</pre>
Quotes, colons, commas and brakets are all important, don't skip them. `title`, `author`, `contacts`, `description`, and `homepage` can be anything. A concatenation of `name` and `version` with underscore, should match the name of the folder of your mod (for example: 1337mod_0.1.0). `factorio_version` is there to break your mod from time to time, note that base mod lacks this line, but yours won't work without it. `dependencies` is a list of the names of mods, that are needed for yours to function, you can simply list a name, or specify a condition for the version of the needed mod. If you put "?" in front of the name, it makes dependency optional.
The mods that you depend on are loaded before yours, and their handlers are also executed first. If two mods are independent, their scripts are executed in alphabetical order.

===My name is===
For the project we're building in this tutorial the following info.json will be used.
<pre>
{
"name":"First_mod",
"version":"0.1.0",
"title":"The first mod",
"author":"Me",
"description":"This mod is example of how to mod",
"factorio_version":"0.14",
"dependencies":["base"]
}
</pre>

== The nature of all things - data.lua and prototypes creation==

Now we move on to creation of things in Factorio. As mentioned before, anything that is exists in Factorio is first defined as a prototype, a table with specific structure and specific values of its fields. During the game boot, the executable launches a single lua machine and initializes a bunch of global variables in it, namely: `data` and `util`. (And almost all the default lua variables.)
And then all the data.lua scripts are run in that machine, then all data-updates.lua scripts and, finally, data-final-fixes.lua.
Those files are true lua scripts and can do anything: search n-th prime, implement Dijkstra's algorithms, etc...

But it is expected that during their execution modifications and additions to `data` will be performed.
The `data` is a table, which will be used by game to setup the Factorio universe.
In fact, it contains the function `extend(self,prototypes)` and a table `raw`. The former is customary way to add new stuff to the latter.
It is actually `data.raw` that holds the prototypes for the game. (You can view the implementation in the file /factorio/data/core/lualib/dataloader.lua)

Note, that prototypes are created during the game boot and any changes to data.lua will only take effect after the game execution is terminated and launched again.

So, the `data.raw` is a table, where everything is stored by its type and then by its name: all the chests are stored in `data.raw.container` (except the logistic chests, that have their own type), all biters are stored in `data.raw.unit` (sometimes mods add other units as well). You can get the iron chest prototype, for example, by doing this:
<pre> chest = data.raw.container['iron-chest']
</pre>

The function `extend` is usually called with semicolon syntax (lua stuff) and is a table of prototypes written by you. It performs minimal error check and stores prototype in corresponding index inside `data.raw`.

To sum it up, if you want to make something new, you do:
<pre>
data:extend({
    {type="item",
     name="megachest",
     ...
    },
    {type="container",
     ...
    },
})
</pre>
If you want to change something in already existing stuff, you do
<pre>
data.raw["container"]["iron-chest"].max_health=300
</pre>

What should be put instead of ellipsis in the above is a different question. You won't find a complete answer here. A dozen of highly trained people on salary was unable to document all that, what to expect from an odd guy from internet then?
Furthermore, the prototype format also changes between the versions, sometimes, notably.
Thus, the best course of actions is to search the item of interest in other mods (including the base) and replicate the found format in your own mod. There will be a chapter in the end of this guide to list some tricks modders have learnt about the prototypes, but for now just check base mod.

An emphasis here should be put on the fact, that the prototype must have a certain format and certain fields set. You can set additional fields if you want to use them during the prototype creation stage, but any field that is not coded into a particular type definition will be completely discarded by the game when `data.raw` is parsed. What this means, is that you can't just add <pre>inventory_size = 80</pre> to an entity of type `assembling-machine` and have it also double as a storage chest. Such tricks require the use of runtime scripting in control.lua.

The least taxing method of creating a new prototype is outright copying the working one from the base mod and altering the needed fields, whilst leaving the rest be.
And I don't necessarily mean ctr-c\ctr-v here, among the other lua files, the core mod provides util.lua, which adds the `deepcopy` function to `table` library:
<pre>
--just in case: "--" is a comment
require "util"
local new_chest=table.deepcopy(data.raw['container']['iron-chest'])
new_chest.name="mychest"
new_chest.inventory_size=30
new_chest.minable = {mining_time = 1, result = "item-mychest"},--for this to compile there should be item with name "item-mychest" defined as well
data:extend{new_chest}--just in case: in lua you can write ({...}) simply as {...}
</pre>


As a final note on the data generation, it should be pointed out that all the data scripts from all the mods are run by the same lua-machine, and, thus, share all the global variables. That is, if you define a variable say:
<pre>
settings={gen_turrets=true, gen_guns=false}
</pre>
then all the data scripts executed afterwards will see this variable as well. Normally, this is not much of a problem, after all, by that time your script should already have done its job. But one must ensure that default variables such as `table`, `string` or `debug` remain usable after the script is done. That is, if you absolutely need to do something like this:
<pre>
string='my super letters'
</pre>
then do it like this:
<pre>
old_string=string
string='my super letters'
--do your business here
string=old_string
</pre>

===Let there be chest===
For this mod lets make a simple teleport chest. In order to do so, we'll need to write a bit of scripting in control.lua, but for now let's focus on defining stuff.
We will need an entity to represent sender end of teleport, an entity to imitate receiver, items to place and mine them , recipes to create the items, and a tech that will unlock the recipes.

I'm creating them here as copies of already existing prototypes and alter the relevant fields in the copies. You should probably view the code below through specialized editor with syntax highlighting, it will help to see the comments at least.

Firstly, some auxiliary stuff. Technology, recipes, items, those things are quite simplistic and boring. 

<pre>
--data.lua
local technology={
    type = "technology",
    name = "logistics-teleportation",
    icon = "__base__/graphics/technology/logistics.png",
    effects ={
		{type = "unlock-recipe",
		recipe = "teleportation-chest"},
		{type = "unlock-recipe",
		recipe = 'teleportation-chest-receiver'},
      },
    prerequisites = {"logistics-3", "automation-3"},
    unit = table.deepcopy(data.raw.technology['logistics-3'].unit),
    order = table.deepcopy(data.raw.technology['logistics-3'].order),
}
technology.unit.count=technology.unit.count*3


local recipe={
    type = "recipe",
    name = "teleportation-chest",
    enabled = false,--this one may be set to TRUE to make recipe available from the start
    ingredients ={
		{'advanced-circuit',5}, {'steel-plate',5}, {'electronic-circuit',5},
    },
    result = "teleportation-chest-item",--note: you can give same name to the tech, recipe, item and entity if you want, but you don't have to
  }
</pre>

This is so boring that we will do a complete copying whenever we can. We do the copy and then alter the fields that are important to us.
<pre>  
local receiver_recipe=table.deepcopy(recipe)
receiver_recipe.name='teleportation-chest-receiver'
receiver_recipe.result='teleportation-chest-receiver'

local item=table.deepcopy(data.raw.item['steel-chest'])
item.name="teleportation-chest-item"
item.place_result="teleportation-chest-entity"
item.icons={--we can make compound icons using this format
  {
    icon = item.icon,
  },
  {--and we can tint them
    icon = "__base__/graphics/icons/iron-plate.png",
    tint = {r= 1, g = 1, b = 0, a = 0.3},
  },
}


local receiver_item=table.deepcopy(item)
receiver_item.name='teleportation-chest-receiver'
receiver_item.place_result='teleportation-chest-receiver'
receiver_item.icons[2].tint={r= 0, g = 1, b = 1, a = 0.3}
</pre>


Entities definition is a bit more complicated. Entities have quite a lot fields depending on their type and many of them matter. That does not mean that steal'n'paint approach doesn't work here, though.
A sender will be a chest for which we will write some additional scripts later on. 
<pre>
local entity=table.deepcopy(data.raw['container']['steel-chest'])
--quite a bit of fields is going to be changed, let's do that in orderly fashion
local fields_to_change={
	name="teleportation-chest-entity",
	icons=item.icons,
	minable={hardness = 0.2, mining_time = 0.5, result = "teleportation-chest-item"},
	inventory_size = 5,
}
for k,v in pairs(fields_to_change) do
	entity[k]=v
end
entity.picture.tint={r= 1, g = 1, b = 0, a = 0.8}
</pre>
We will also spawn a special unseen entity of ElectricEnergyInterface type for each sender chest. We will use that to implement energy costs for teleportation, remember, we can't directly make a prototype that will behave as a container and use energy on its own.
<pre>
local power_entity=table.deepcopy(data.raw["electric-energy-interface"]["electric-energy-interface"])
local fields_to_change={
	name="teleportation-chest-power",
	icon=entity.icon,
	minable=nil,
	picture={
		filename = "__core__/graphics/empty.png",
		priority = "high",
		width = 1,
		height = 1,
		shift = {0,0}
	},
	selection_box=nil,
	collision_box=nil,
	order='z-z-z',--the game believes all the stuff should be accessible through map editor and needs order string to sort that
}
for k,v in pairs(fields_to_change) do
	power_entity[k]=v
end
</pre>

A receiver will be simply a fancy named chest for our mod. Its prototype will not be at all different from sender, they're both chests after all.

<pre>
local receiver=table.deepcopy(entity)
--for comparison, this one will be done unfancifuly 
receiver.name='teleportation-chest-receiver'
receiver.minable.result='teleportation-chest-receiver'
receiver.inventory_size=20
receiver.icons=receiver_item.icons
receiver.picture.tint={r= 0, g = 1, b = 1, a = 0.8}
</pre>


And now the most important thing: we push our prototypes into `data`.
<pre>
data:extend{technology,receiver_recipe,recipe,item,receiver_item,entity,receiver,power_entity,}
</pre>

If you look into the base and some other mods, you may see that those only do a bunch of requires in the data.lua. Any of those `require`d files is capable of accessing global variable `data`. Using such structured approach is a wise thing to do, but is not absolutely required.

== Ĉu vi parolas la anglan? - Translation of the mod ==

Another boring but needed part of the modders' work is translating or making their mods translatable.
Any name defined in data lua, is norally not shown in the game itself, instead, the game scans locale files for a string to substitute it with. 

Every mod can have a `locale` folder, inside folders named with language name abbreviations should be located, for example `en` is a folder to store localization strings for English language. Inside the folder "*.cfg" files should be, all of them, regardless of name and size are loaded as a dictionary for names. If no translation is available for the language chosen by player, the English translation is used.

Currently, files look similar to following:
<pre>
[item-description]
teleportation-chest-item=Once per second teleports items to nearest receiver.

[item-name]
teleportation-chest-item=Teleportation chest

[recipe-name]
teleportation-chest=Teleportation chest
</pre>

Category keywords in square brackets specify the situation, where the string should be used, each line starts with the non-localized string, and translation follows after the equation sign. The order of categories is unimportant. Once again, check the base mod for most up to date format.

A few of ticks of trade currently are:

*You can pass localized strings in many places that accept ordinary strings by encompassing the string in the table:
<pre>
game.players[1].print({'entity-name.iron-chest'})
</pre>

*A string without a category is allowed, you can use such strings to translate your guis or print messages to players. Such strings are defined at the beginning of the file, before any of the identifiers in square brackets.

*One underrepresented category is `[controls]`, it's sole usage example can be found by closely studying `core` mod, that category is used for translation of key settings menu if you define custom input keys.


===tlhIngan neH pejatlh!===
For this mod we will make English translation:
<pre>
#this is comment
#locale/en/stuff.cfg
[entity-description]
teleportation-chest-entity=Once per second teleports items to nearest receiver.

[entity-name]
teleportation-chest-receiver=Teleportation chest receiver
teleportation-chest-entity=Teleportation chest
teleportation-chest-power=Teleportation chest

[item-description]
teleportation-chest-item=Once per second teleports items to nearest receiver.

[item-name]
teleportation-chest-item=Teleportation chest
teleportation-chest-receiver=Teleportation chest receiver

[recipe-name]
teleportation-chest=Teleportation chest

[technology-name]
logistics-teleportation=Teleportation
</pre>

==Are you a wizard? - control.lua and runtime scripting ==

And here we arrive to the most interesting part: lua scripting. 

When you see the the factory working, biters running around, stuff happening, you see it because the game engine is performing updates of the in-game state: calculates power consumption, checks where items should be grabbed by inserters, and  does miriads of other atomic actions needed for the in-game universe to tick. All those low level calculations are implemented in C++. The modders do not have the power to tamper with that mechanism. 

However, during the update calculation the game can detect, that a particular operation was notable one, for example, it has just determined that a particular unit has its health below zero, or some player clicked an empty ground with a particular item etc...
So when something worth of note happens, it is called the '''event'''. The game packs some relevant information about the event into a lua table and then passes that information to a '''handler functions'''  which were registered to that event by mods. To register those handlers is a prime task of the "control.lua" script file.

These handler functions are (preferably) brief set of instructions that should do whatever it should quickly and return control to the main loop of the game. Usually, any additional logic you want to introduce with your mod is split over several different handlers. The existence of global variables in lua allows one handler to influence the execution process of other functions.

A more educational example will be given in the sub-chapter below, but a quick sample of handler registration may be:
<pre>
local handler=function(event_info)--there are many places where you can put handler definition, this is one of them
    game.players[event_info.player_index].print("You have built "..event_info.created_entity.name)
end

script.on_event(defines.events.on_built_entity,handler)--this is registration of handler to a particular event
</pre>
The function above uses the factorio-api object accessible through global variable `game` and other data provided by the game during the event, in this case, it is the unique `player_index` of a player, that has built something and an object representing the entity, which was built. The handler function uses that to print the name of the built entity for the player.

The game has quite a lot of special objects bundled with lots of methods the mod can make use of. The official [http://lua-api.factorio.com/ api site] is the best place to educate oneself about the available possibilities. It also mentions available global variables and documentation for events. When you embark with your own mod, that page will be your most frequently used.

For now let's talk a bit more about the life of variables in control.lua .
During the control.lua execution, you can declare variables to aid your event handlers.
For example:
<pre>
function on_build(e)
	last_built=e.created_entity.name--this initializes a global variable
end
function on_mine(e)
	--in this function we will use
	if last_built then game.players[e.player_index].print("Last thing that was built is "..last_built) end
end
script.on_event(defines.events.on_built_entity,on_build)
script.on_event(defines.events.on_mined_entity,on_mine)
</pre>
Unlike data.lua, each control.lua is executed by independent lua machine (in the isolated environment), thus the only constraint to your naming splee is common sense.
However, the example above has one problem: it is inconsistent against save\load process.

When the game is saved it stores a bunch of data that will allow the simulation to continue from where it was left. 
But to save the state of your lua machine is a difficult task, thus game does not try to save it completelly.
Instead, you're provided with a special global variable named `global`. 
Its purpose is to be preserved along the savegame. When the savegame is loaded next time, the `global` is inititalized with its contents from the last time.
Its name is the longstanding testament that coming up with descriptive names is hard. To avoid the confusion with Lua-global (which is any variable not defined as local) notice the `format` that this guide uses when listing variable names.

<pre>
a=1--this is lua global
global.b=2--this is factorio global
--you can acces these variables in the following way
print(a)--this prints the variable to std output
print(global.b)
--you can't access the factorio-global this way
print(b)
</pre>

Generally, any variable that changes its value during runtime you should store in the `global` table.

One more thing about the control.lua, its execution finishes before most of ingame data is set up or restored. So you should only use the code outside handlers to set up some general data structures, and do not try give items to the player there for example.

If you need to do something when the factorio universe does come to existence (quite frequent need), you register two special handlers: `on_init` and `on_load`, try putting the following example in the "control.lua".
<pre>
--this output you will always see in stdout
print('The control.lua start')
a=1
print("The global a is",a)
print("The global b is",b)
print("The `global` c is",global.c)--global is always empty at this point
local initialization=function()--define handler
	--this output will happen when your mod is loaded to the current game for the first time (even if the game itself is not new)
	print"On init is running"
	print("The global a is",a)
	b=2
	print("The global b is",b)
	global.c=3
	print("The `global` c is",global.c)
	print"On init is done"
end
script.on_init(initialization)--register handler
--you can also define handler during the registration istself:
script.on_load(function()
	--this output will happen when the savegame is loaded and the mod was present during the save process
	print("On load is running")
	print("The global a is",a)
	print("The global b is",b)
	print("The `global` c is",global.c)
	print"On load is done"
end)
print('The control.lua end')--guess when this output will take place
</pre>

The handler you register with `on_init` is called the first time the game is started with your mod enabled. It may be the very beginning of the new game or loading of the savefile.
The `on_load` handler is called during each load after that, this includes the multiplayer, where this handler is executed for the player that connects to the game.

The purpose of the `on_init` is obvious: if you need to initialize some variable with something from the game wold, you do that here.
The `on_load` event however... You may remember that the game can't store the whole lua state, some lua data, such as metatables local variables or closures, simply cannot be saved (serialized) easily. What data can be serialized, and needs to be saved, you store that in the `global`. However the unsaveable data is sometimes needed and is used quite videly in lua programming. So, the on_load event is provided to you, so that you can generate the unsaveable data anew. A simple enoug mod doesn't need  the `on_load` handler at all (nor it needs `on_init`). Also, don't ever try to change the values stored in `global` during this event. As was noted `on_load` is run for only one person, so in multiplayer that would lead  to people having different values of the same variable.

=== Want to see some magic?===

That's enough theory to finally do scripts for our mod. Beware, the code below was written with the intent of being brief and understandable in each separate step. Later we will talk about the improvements of the logic used in the mod, but the optimized version will require clear understanding of the whole picture at once. So, here you see a good-enough example of using factorio api in a real moding situations but not good-enough script logic.
  
So the "design" of the mod is the following: player builds sender and receiver chests, then once per second each sender chest searches for the nearest receiver in a certain range and transfers items to that, the transfer costs some energy, the cost is exacted per transferred item type. The last part is also a simplification for clarity. 

This design will be implemented this way: when something is built, the mod checks whether the built entity is either sender or receiver, and stores those in `global`, then each second senders stored inside `global` will be checked for items, energy, and then the corresponding receiver will be searched and item transfer will be attempted.

Here go the contents of control.lua file. 
We begin with some constants definitions. The differences between local and global are nonexistent for the current mod, we will discuss the some time later.
<pre>
--control.lua
local evs=defines.events--defines is always accessible 
MAX_TELEPORTATION_RANGE=100--some glboal parameter for the mod
TELEPORTATION_ENERGY=10000--this is equivalent to 10kJ I guess.
</pre>

We do some initialization. We could get away without this but let it be for now.
<pre>
script.on_init(function() global.senders={} global.receivers={} end)--lets init some tables, though we might get away without that for this mod
</pre>

We subscribe our handler for building events.
<pre>
script.on_event({evs.on_built_entity,evs.on_robot_built_entity},--you can pass a table with several event-id's to register the same handler to all of those
	function(e)
		--this is reaction to our entities being built
		local en=e.created_entity
		--first we check if it's our entity
		if en.name=='teleportation-chest-receiver' then
			local f=en.force.name
			global.receivers[f]=global.receivers[f] or {}--this is common table initialization\check trick
			local uid=en.unit_number--many entities have this field, which is guaranteed to be unique
			global.receivers[f][uid]=en--we store the reference to our receivers on per-force basis
		elseif en.name=="teleportation-chest-entity" then
			--yes, with a bit of thought it was possible to avoid code duplication
			local f=en.force.name
			global.senders[f]=global.senders[f] or {}
			local uid=en.unit_number
			--let's spawn our additional power interface
			local pow=en.surface.create_entity{name="teleportation-chest-power",position=en.position,force=en.force}
			pow.destructible=false--let this one be untouchable
			--now we'll store both entities for the future use
			global.senders[f][uid]={chest=en, power=pow}
		end
	end
)
</pre>

And here we murder the fps (not too much, honestly). Actually, there are numerous ways of making this even slower, and those don't even include explicitly unnecessary actions. As said before, improving over this simple function will require modifications not only to this handler but rethinking the whole implementation (all 50 lines of code), so let it be this way for now.

<pre>
--here we'll make our chests teleport items to nearest receiver from time to time
script.on_event(evs.on_tick,function(e)
--this function is called on each game tick(update of the game state)
--it will murder the game's fps if done badly	
	
	if not (e.tick%60)==0 then return end --this is common way not to do much work on every tick, we just dont need that frequent updates for our mod
	for force_name,receivers in pairs(global.receivers) do--for each force that has built receivers
		if global.senders[force_name] then --we check if it also has senders
			for uid,tab in pairs(global.senders[force_name]) do--and run updates on those
				local chest=tab.chest
				if not chest.valid then--something broke the chest is no more
					if tab.power.valid then tab.power.destroy() end--remove its power drain from the game as well
					global.senders[force_name][uid]=nil--forget about it
				else
					--let's find where to send items, let's put that logic in a separate function for example
					local nearest,distance =find_nearest(receivers,chest.position,MAX_TELEPORTATION_RANGE)
					if nearest then 
					--lets try to transfer items
						local receiver_inventory=nearest.get_inventory(defines.inventory.chest)
						local sender_inventory=chest.get_inventory(defines.inventory.chest)
						local items=sender_inventory.get_contents()
						local p=tab.power
						if p.energy> TELEPORTATION_ENERGY then--very primitive logic for tutorial
							for item_name,count in pairs(items) do
								local inserted = receiver_inventory.insert{name=item_name,count=count}
								sender_inventory.remove{name=item_name, count=inserted}
								p.energy=p.energy-TELEPORTATION_ENERGY
							end
						end
					end
				end
			end
		end
	end
end)

find_nearest=function(entities,position,max_distance)
	--this is auxilary function used in the above handler
	--it is stored in global variable, thus it will be seen during the `on_tick` handler, despite the fact that it is defined after the handler. The important thing is that the handler is definitely called later than this function is created
	
	local distance=max_distance^2
	local nearest
	for k,e in pairs(entities) do
		if not e.valid then
			--in the current disposition, this is the only place to check for receiver validity
			entities[k]=nil
		else
			--this part is pretty standard linear search algorithm 
			local p=e.position
			local d=(p.x-position.x)^2+(p.y-position.y)^2
			if d < distance then
				nearest=e
				distance=d
			end
		end
	end
	--if we have found something, we return it
	if nearest then return nearest, math.sqrt(distance) end
end
</pre>

This concludes the "First_mod_0.1.0". 
The remaining sections deal with creation of scenarios, some tricks of trade and updating the mods.
At this point you pr[/code]obably have enough knowledge to, with a bit of luck, make your own functional mod. You may read on, if that is your thing, or you may try to mod and run back here if something fails.


=The return of the modder=

There is more to factorio modding than has been already said.
In this part of the guide we'll talk about creation of scenarios, there probably will be a few more things to tell about lua coding and performance, and finally there will be talk about updating your mod.

==A tale of tales - Scenarios ==

The examples of this chapter are from the "First_mod_0.2.0".
Basically, a scenario is a set of completely optional parameters to start a game. 
When player clicks "custom scenario" button in the menu, the game searches the folders named "scenarios", it looks for them in the "mods" and "data", it also checks the game directory itself. Any folder inside "scenarios" is a scenario. 

Thus, a trivial example of a scenario is an empty folder. If you start such a scenario ("First_mod/trivial_example" ,for ex.), the map generator settings window is brought up and after that the game starts. The only difference of such scenario from the "freeplay" is that it won't pester you about rockets without satellite (and it won't tell you that you've won and you'll start without items). That functionality (both the pestering and starting items) is provided by scripting.

A scenario is allowed to contain a "control.lua" script file. Whatever a mod script can do, scenario's script can do as well. The difference between them is that mod script file is executed at every load when a mod is active, and scenario script is executed when the scenario is loaded. The scenario script is also, copied into control lua, so you need to start a new game to see the changes you've made. (or use migration, we'll talk about it later).
A final note is that the script control.lua and the mod control.lua are executed in the independent environments thus both of them have `global`, these are different `global`s.

Thus it is entirely possible to move mod's script into a scenario and have the mod features only work in that particular scenario, but the conditions under which that would be reasonable are exotic at best.

A conventional use of the scenario script is to add some goal or a final condition for the game. 
A simple example of that can be seen in the "First_mod\win_by_chest" scenario, which has the following script:
<pre>
script.on_event({defines.events.on_built_entity,defines.events.on_robot_built_entity,}, function(e)
	if e.created_entity.name=='wooden-chest' then
		game.set_game_state{game_finished=true, player_won=true, can_continue=true}
	end
end)
</pre>
Something not as silly can be observed in the freeplay scenario, the point however is: the scenario script uses all the same methods as ordinary script but strives for a different goal.

=== I need a turtle, and a bunch of elephants ===
Sandbox and freeplay use map generator, but it is of course possible to create a scenario with predefined map in it. If there is a "blueprint.dat" file in the scenario folder then that one is used instead of randomly generated map. That file is the one you can generate with the map editor tool, or map converter tool.
The editor is available in the main menu of the game, the converter is semi-hidden feature of the executable.

The converter is a tool to convert an existing savegame into a blueprint for scenario.
----
Construction in progress: actually the guide is still under construction below this line, please check back later. 


=Lua caveats =
====Saving functions====
Storing the execution state of program is not easy.
You can easily store the data, your program generates, but saving the state of functions is complicated.
In lua functions '''are data''', but saving their state if they have one is difficult.
Default distribution of lua does not provide that functionality. And neither does Factorio.
So, you can store functions but you cannot save closures. That is a function you're storing can only reference global variables outside its scope. For example if you enter the following lines in terminal (prepending then with "/c "):
<pre>
a=3
global.f1=function() print(a) end
local b={4}; global.f2=function() print(b[1]) end; global.f3=function() b[1]=5 end
</pre>
by calling them in the following order:
<pre>
global.f1()
global.f2()
global.f3()
global.f2()
</pre>
You'll get:
<pre>
3
4
5
</pre>
But if you save and load game, the following commands:
<pre>
global.f1()
a=2
global.f1()
</pre>
will yield:
<pre>
nil 
2
</pre>
The function f1 correctly references global variable (both of them, if you can see the second one) and prints value of a global variable with same name.
But if you try to call function f2 however, you'll get runtime error stating that _ENV upvalue is nil.

====Tables as keys====
In lua the following code is valid:
<pre>
a={}
b={}
b[a]=4
</pre>
But be careful, if some table contents will cause your savegame not to load, and raise get error during running deserialization.

[[Category:Tutorial]]
[[Category:English page]]
