How to download factorio mods
How to download factorio mods
How to download factorio mods
Anyone else having issues with this other than me?
Downloaded a couple mods and dropped the non zopped folder into c:\Users\user name\AppData\Roaming\Factorio\mods\
With the game running and the mods showing up on the list as enabled I try to load an old game or generate a new one and it gives me an error: attempt to index a global ‘game’ (a nil value)
Any idea what is happening here? I would assume an incorrect installation on my part would not even have it showing up on the mod list.
With the game running and the mods showing up on the list as enabled I try to load an old game or generate a new one and it gives me an error: attempt to index a global ‘game’ (a nil value)
Are you sure they are compatible? That error message means at least one of the mods hasn’t been updated for 0.12.11 and above. The name of the mod should be in the same error message.
Besides, it is recommended you keep them zipped, as Factorio can load them faster then.
This is the first mod I was dropping in just to test the gameplay with it out and with my limited experience with mods for this game all I have to go on is the description from the author which says it was tested with 0.12.2
When I look at the mod in the game to toggle it on or off under dependencies i get >= 0.12.2
This is the mod in question:
And again the full error text is:
__spring-water__/control.lua:27: attempt to index global ‘game’ (a nil value)
Originally i did extract the file folder into the mods section, but changed that out to the zip folder after reading above.
I am just trying to find alternative power sources than coal and solar is all here and if there is a better or an alternative that works and I missed something along the road here any help is appreciated.
Factorio version numbers are a little confusing for some. 0.12.2 is older than 0.12.11, so this mod is not compatible. However, replace all 7 occurences of game with script in control.lua and the mod works.
Factorio versioning
It is 0.12.[x], where x is increased by one.
First are versions 0.12.0 to 0.12.9, then come 0.12.10 to 0.12.19, and then 0.12.20 to 0.12.24 (current version).
How to download factorio mods
The %appdata%\Factorio is on C:\
I don’t have room and C:\ and want to install the game on E:\
My Steam library is on E:\
Is it possible to install the mods on E:\
i.e. you move the Factorio directory from the %APPDATA% to the target location on E:, and next you make a symbolic link to it (or alternatively a directory junction with /j option instead of /d) in the original location.
If you don’t want to write any commands in console, get some shell extension that allows you to create symbolic links or directory junctions with just drag and drop (e.g. «Link Shell Extension»).
Practically none of the mods I try from Factorio Mods are working, any clues? They can’t all be outdated, right?
The last big change in the modding interface was with 0.12.11 (October 2015), so a mod that is working with 0.12.11 and higher will probably also be working in the current version.
Practically none of the mods I try from Factorio Mods are working, any clues? They can’t all be outdated, right?
The last big change in the modding interface was with 0.12.11 (October 2015), so a mod that is working with 0.12.11 and higher will probably also be working in the current version.
i take it at some point you’ll probably have workshop support. that’ll be a huge boost for the modding side of things.
would it be possible for the game to detect out of date mods upon loading and simply set them to disabled automatically? it’ll probably be necessary before the workshop comes out to prevent having to hunt through your subscribed mods to find the ones that are no longer supported by the maker.
How to download factorio mods
The %appdata%\Factorio is on C:\
I don’t have room and C:\ and want to install the game on E:\
My Steam library is on E:\
Is it possible to install the mods on E:\
i.e. you move the Factorio directory from the %APPDATA% to the target location on E:, and next you make a symbolic link to it (or alternatively a directory junction with /j option instead of /d) in the original location.
If you don’t want to write any commands in console, get some shell extension that allows you to create symbolic links or directory junctions with just drag and drop (e.g. «Link Shell Extension»).
Practically none of the mods I try from Factorio Mods are working, any clues? They can’t all be outdated, right?
The last big change in the modding interface was with 0.12.11 (October 2015), so a mod that is working with 0.12.11 and higher will probably also be working in the current version.
Practically none of the mods I try from Factorio Mods are working, any clues? They can’t all be outdated, right?
The last big change in the modding interface was with 0.12.11 (October 2015), so a mod that is working with 0.12.11 and higher will probably also be working in the current version.
i take it at some point you’ll probably have workshop support. that’ll be a huge boost for the modding side of things.
would it be possible for the game to detect out of date mods upon loading and simply set them to disabled automatically? it’ll probably be necessary before the workshop comes out to prevent having to hunt through your subscribed mods to find the ones that are no longer supported by the maker.
Моддинг
На этой странице рассказывается, как загружать и устанавливать моды, и дает краткий обзор того, что вы должны иметь в виду при создании мода. Для получения более подробных инструкций по созданию модов вы можете ознакомиться с учебной страницей моддинга. Если вы ищете API-интерфейс для моддинга, ознакомьтесь с официальной документацией Factorio Lua API (англ.). Если вы хотите узнать, где установить мод, который находится в зашифрованном формате, ознакомьтесь с инструкциями на странице каталога приложений.
Contents
Загрузка и установка модов
Вы можете скачать моды из следующих мест:
Портал модов (веб-сайт)
Разработчики Factorio создали портал модов (веб-сайт), чтобы позволить игрокам делиться модами. Мод, который вы загружаете с веб-сайта, поставляется в виде заархивированного файла. Чтобы установить мод, вам нужно скопировать заархивированный файл в каталог модов, расположенный под каталогом данных пользователя, без его распаковки. Вы можете проверить, правильно ли вы установили его, просмотрев список мод, доступ к которому вы можете получить через главное меню игры.
Портал модов (в игре)
Подфорум модов
Зависимости
Многие моды используют базовый мод Factorio как свою единственную зависимость, которую вам не нужно устанавливать отдельно. Однако некоторые моды могут потребовать установки других модов для их работы, а также могут предложить вам установить другие моды, чтобы они могли расширить их функциональность.
Требуемая зависимость
Когда установленный мод требует установки другого мода для его работы, другой мод в этом случае является необходимой зависимостью.
Необязательная зависимость
Когда мод делает предложение установить другой мод, но если ему не нужен этот другой мод для его работы, другой мод в этом случае является необязательной зависимостью. Вы можете установить дополнительные зависимости, которые расширяют функциональность мода, чтобы улучшить игровой процесс с помощью мода.
Примечание
В настоящее время портал модов в игре не загружает автоматически ни необходимые, ни дополнительные зависимости; поэтому пользователь может их найти и установить. Однако ожидается, что в будущем такой процесс будет выполнен автоматически.
Создание модов
API документация
Lua скриптинг
Для создания любых модов в Factorio вам необходимо использовать язык программирования Lua. Система модов игры вводит ваш код в запуск и на этапе построения данных игры. Вы можете использовать любой текстовый редактор для написания кода для своего мода. Известными текстовыми редакторами, которые предлагают подсветку синтаксиса для Lua, являются Notepad++ и Sublime Text.
Полезные ресурсы для Lua:
Базовая структура мода
Моды Factorio распространяются в ZIP-архивах и содержат несколько важных файлов, которые Factorio ищет при загрузке модов. Эти файлы перечислены ниже, а требуемые файлы окрашены в красный цвет.
Лицензирование
Каждый мод требует лицензии начиная с Factorio в0.11. Если мод не имеет лицензии, предполагается, что он имеет лицензию Creative Commons — Атрибуция-Некоммерческая 4.0 Всемирная (CC BY-NC 4.0). Тем не менее, можно намеренно сделать мод нелицензированным, чтобы код в нем был доступен для общественного достояния. Наиболее популярными лицензиями на распространение модов Factorio являются лицензия MIT и лицензия GPLv3.
Другие полезные юридические ссылки включают:
Tutorial:Modding tutorial
This is a modding tutorial for Factorio version 1.1. In this tutorial, the author will explain how Factorio works behind the scenes, how to modify Factorio, where to find documentation, and explain concepts.
Contents
Overview
Before we start the tutorial, a few things to note:
This tutorial was updated to version 1.1, so any viewers in the future should take note that some minor changes may have been made, and should look at the changelogs up to the current version.
Terminology used in modding
Before we start the tutorial, a few terms and definitions should be laid out, to ensure the reader understands.
More terminology may be declared and defined later in this tutorial.
Before beginning to mod
Before we can start modding Factorio, we must understand what Factorio is. You may be tempted to answer in lieu of the about page, but that is what a player would say. Since we are trying to become a modder, we need a more detailed explanation. Factorio is a game that is coded in the language C++, with an API provided by Wube (the developers of Factorio) to mod Factorio in the programming language Lua (version 5.2.1). This API allows adding scripts to the Factorio init process, to modify it without the source code of the base game being exposed, or modifying memory. This may be different than other games that offer modding, but this is a more professional and proper way of supporting modding.
To aid in the use of this API, the devs have kindly provided fairly comprehensive documentation of scripting at their API site and documentation all around prototypes on this wiki. Get used to using these sites, as they will become frequent visits you will make while you develop mods. The scripting API site contains information on Factorio’s classes and information on events that you can hook into. Prototype definitions contains and links to information all around prototypes, listing their inheritance structure and their properties. You will need to check these sites often, so the author recommends bookmarking them. In addition to these sites, there is also many resources to be found created by the community, such as this tutorial.
Setup
The best way to develop a mod is to develop it in a place where it can be easily tested. When the tutorial gets to making the mod, this will be explained further. Additionally, using an editor that allows ease of typing and Lua language support is recommended. Emacs, Vim, Sublime Text, VSCode, and Notepad++ are all viable candidates.
How Factorio loads mods
Load order
Within stages, mods are loaded by dependency, then by alphabetical order. This is very important to understand, as it can cause you problems if you neglect it and try to add inter-mod support to your mod.
Factorio has three kinds of dependencies. There are required dependencies, and optional dependencies. The third kind, restrictive dependencies, does not affect mod order and instead prevents the game from loading if the other mod is found. Required dependencies are loaded first, always. The game will fail to initialize if one of these is not present. Optional dependencies are loaded first if present, but do not have to be present. This is useful for enabling bonus features if mods are used together. Required dependencies should be used for mod libraries, and similar infrastructure.
The settings stage
The settings stage does not have access to prototype or runtime data because it is loaded before those stages. The settings are expected to have a certain format, and all additional code will be discarded once the stage is over.
Mod settings are not covered in this tutorial, see Tutorial:Mod settings for further info on them.
The data stage
All other files to be loaded will need to be required. All the files run here should contain nothing but prototype definitions and code to produce prototype definitions. More on requiring files later.
All prototypes are documented here on the wiki: Prototype definitions.
Migrations
Migrations are scripts that are used to «fix» a save after a mod updates. Whenever prototype names change within a mod, migrations must be setup to replace all the old instances of the prototyped entity in the world. This must be done for all updated entities, or the old entities will be removed from the world, which is an unprofessional fallback that makes users dislike you. While this tutorial will not discuss migrations, there are many resources on migrations to be found around the community, and the API site.
To avoid having to write migrations, avoid changing prototype names and technology unlocks. Prototypes names cannot be dynamically changed and technology unlocks of already researched technologies do not apply automatically, making migrations necessary. Try to avoid these changes after shipping the mod out to the public. Try to come up with a finalized version of prototype names that you can base the mod around. Of course, migrations are unnecessary if the user simply starts a new world with each mod update, but do not expect the community to do this.
Runtime stage
The control stage documented is documented on lua-api.factorio.com.
The major components to any Factorio mod
Within the average mod, there are several components that make the mod function.
Mods with in-game effects will also need a control.lua file, to add scripting.
Mods with configurable user settings will use settings.lua to describe those settings.
Mods that define any game element with a readable name may also provide a locale directory and subdirectories with names/descriptions in one or more languages.
The mod that we’ll make in this tutorial will include both data.lua prototypes and control.lua scripting, to give you a feel for both.
The tutorial mod
And now for the moment you’ve been waiting for. Let’s start making your first mod. You’ll need:
Once you have all of these things, we can begin.
For this mod, we’re going to make a set of armor that leaves behind damaging fire behind you as you walk. It will be fully resistant to fire, but weaker towards physical damage than heavy armor, making it an armor for hit and run attacks.
Creation of the directory structure
The info.json file
Then, inside info.json, copy and paste the following into it:
To explain each field:
Item | Explanation |
---|---|
name | This is the internal name of your mod, it is used to identify your mod in code. |
version | This is the version of your mod. This can be anything you want, provided it’s a of the format «number.number.number». |
title | The pretty title of your mod, this will be displayed on the mods screen and when you submit it to the mod portal. |
author | Your name! You can change this in the example above. |
factorio_version | This tells the game what version the mod is for, this must match the version you’re developing the mod for, 1.1 in this case. |
dependencies | Any dependencies of your mod. |
description | A short description of your mod. |
And that’s all for info.json! Next, in the data.lua file:
We are creating this file just for our own organisation inside the mod, so there are no naming or other requirements from the game’s side. As long as we tell the game to load the file with «require», the file name or its exact location inside the mod does not matter.
Prototype creation
Now, there are two ways to create prototypes in Factorio. There’s the short way, and the long way. The long way requires to create a complete prototype definition based on the documentation, and the short way just uses a lua function to copy and modify an already existing definition. For the sake of this tutorial, we’ll do it the short way.
In item.lua, copy and paste the following:
In addition to defining the item prototype, we also define a recipe for it. This is necessary if you want to be able to craft the thing. We also set it to enabled so it doesn’t need a technology to unlock.
More on data.raw
We assign a variable called fireArmor that holds our copy of the heavy armor definition. Notice how in data.raw, there is a type table that holds all armors, and the specific armor we’re looking for is called heavy-armor. We can find heavy armor’s prototype type and internal name in the infobox of its page on this wiki and just copy it from there.
Alternatively, we can find the items prototype type and internal name by opening the game, inserting the item into our inventory and then pressing SHIFT + CTRL + F while hovering over the item. This will open the prototype explorer GUI, which has rows showing the name and type of the item.
As another example, the character’s prototype would be, according to the infobox on the page:
Because the character is the character, his type matches his name. You could define a new type of character with a mod. You can see all the available prototype fields of the charater in the documenation: Prototype/Character.
You may be thinking at this point, «Can I modify Factorio’s existing prototypes without making new ones?» Well, the answer is yes! You would simply access the data.raw table during init, in data-final-fixes.lua if you want to run after all other mods, and change a property. For example, make the iron chest instead have 1000 health:
The reason why this code is in data-final-fixes.lua is because that is the last file run, after all mod files have been run. This prevents (to a degree) your changes from being messed with by other mods. Of course, it is still possible to have incompatibilities. You should note any that you know of in your mod’s description. Again, the dev’s documentation on this should be looked at.
This can also be applied to other mods, not just Factorio’s base. You could mod a mod, as long as you add the mod (that you modified with your mod) to your dependencies so it gets loaded first.
The control scripting
And now, to finalize the mod, we have to make it be more than just simple armor. Let’s think about what we want the armor to do. We want the armor to create fire on the ground as we walk with the armor on. The event we’re going to use is called on_player_changed_position, since we want the fire to be created when the player moves.
Inside control.lua, copy and paste the following:
I’ve used lua comments in the code above to explain each step. It’s fairly easy to understand, and it shows how you would get the current armor that the player character is wearing, with defines.inventory.character_armor, which is an inventory constant. You can read the list of defines here.
Locale
If you’ve already tried loading up Factorio and trying the mod so far (which you can at this point without it crashing), you may have noticed that the item name of the armor says «Unknown key». This means that Factorio has the internal name, but it doesn’t know what it should look like to the user. So, we need to create a locale for our mod.
If you know another language, you can also translate your mod by making other language code files inside locale, such as de for German.
Notice how this is not a lua file. Locale is handled with C config files, so the format is different.
The finished tutorial mod
Well, the mod is finished. Since this mod is only a tutorial, there isn’t much balance to it.
However, you’re free to take this mod and modify it for your own use, changing recipes, adding technologies, whatever.
Resolving common errors in modding
As you continue to write mods from scratch instead of from a tutorial, you may encounter the infamous error. There are several types of errors that you can encounter in modding Factorio, and knowing how to deal with these errors will allow you to continue working.
Syntax errors
The lua programming language expects things to be laid out a certain way. If you miss a bracket, = sign, or dot, you will encounter a syntax error. As an example, see the error below:
As of version 0.15, you’ll see an error like the one above whenever you make a syntax error within the prototype definitions. The game will offer to restart, disable the troubling mod, disable all mods, or exit. Let’s dissect the error, shall we?
Right away, we see the reason why Factorio didn’t start normally. «Failed to load mods:». So, we know that it’s a mod that messed up, and by extension, we know it’s our mod. Whenever the Lua engine of Factorio has a syntax error, it will print a mini stack-trace that follows through all requires, listing the call order. First, we see that the problem was indirectly caused by line 1 of data.lua. There’s no problem there, so it must be the next entry, line 36 of prototypes/item.lua. After stating where it is line-wise, it will attempt to give you an estimate of where in the line the problem is. Don’t trust this estimate, only roughly trust the line number, plus or minus a few lines.
Going to line 36 of item.lua, we find:
Hmm, that doesn’t look right. Can you see what’s missing? We left off an = between enabled and true. Thus, syntax error. Fixing these can be difficult for new programmers, who don’t know what to look for.
Illogical actions, indexing nil
In lua, «nothing» is defined as the keyword nil. This is similar to null in other programming languages. Whenever the programmer tries to access something in a table that is nil, they will get an error like the following:
What assumption has the modder made here? Well, there’s actually two problems with this line. The first thing is that the modder has assumed that game.players[23] is a valid player, which isn’t the case; this is why we get the «index field ‘?'» bit. The game doesn’t know what the field is that we tried to index, because it hasn’t been created yet. These errors are difficult to debug unless you know the ins and outs of the modding API well.
The second issue is a lot more subtle, and won’t work. The modder is attempting to print a userdata table. A player is a table of several values. Trying to print it simply print «LuaPlayer» instead of providing useful data.
Error while running event
Another common type of error in Factorio is the «Error while running event» error. This type of error only happens in control.lua scripting, and it happens when something goes wrong in an event function, such as a syntax error. Note that syntax errors in control.lua do not stop the game from starting, but may trigger after a save is loaded. There are a great deal of errors under this broad category, here’s an example:
As you saw with the prototypes syntax error, Factorio gives a small traceback and the error name itself. In this case, we’ve attempted to spawn an entity called «fire-flam» on line 7 of control.lua, inside of an on_player_changed_position event hook. Fire-flam isn’t a real entity type, so we crashed.
These types of errors can range from being a simple fix (like the one above, add the missing e), or can be very difficult.
Internal errors
The most rare form of error and the worst form is the internal error. This is an error with the C++ code of the game, and there’s nothing you can do but report it to the devs. Mods occasionally cause these, and almost all of them are considered bugs, as mods should not be able to cause these, if that makes sense. They often get thrown into the logs.
Multiplayer and desyncs
The reader may be wondering at this point how Factorio handles multiplayer with mods. It’s fairly simple, but is still worth considering.
Factorio is deterministic, which means that when you provide a constant input, you get a constant output, with no variance. Every client and the server all reach the same points at the same time in simulation, so they all agree on what happened. When this differs, the players experience a desync.
Desync Misalignment with server and clients. Client 1 expected A, but got B. All other clients got A. Thus, Client 1 will desync. Desync can also happen when all clients have information (for example a variable) but a client that recently joined the game doesn’t. That client will be desynced. See also: Desynchronization
Desyncs happen a lot to new devs of Factorio mods, because they are unaware that a particular piece of code they used causes desyncs. As a general rule, there are a few things that should never be done.
Use local variables that are not final outside of event hooks
If the modder places a local variable outside of an event hook that gets changed during runtime, desyncs will happen when that variable is utilised to modify the game state (i.e. manipulate an entity, print text to players). If making a «global» variable is necessary, place the variable in the global table instead. The game syncs this table between all clients, so they can all be aware of and reach the same conclusion as each other.
Selective requiring
Selective requiring, aka requiring different lua files based on settings can cause connection rejections as the checksum of the mods will not match, as they load different data. All clients’ mods must require the same series of files.
Conditional event subscribing
Mods in factorio may subscribe to events in order to be notified when they happen. This allows mods to react to events when they occur. Typically, event subscription is done at the top level of a lua file.
Doing event subscription inside of a conditional, function, or other event is dangerous, as doing it incorrectly will lead to desyncs. Basically, since both the server and client need to reach the same conclusion after running code, conditional subscription can lead to certain clients or the server being subscribed to an event when the others are not, causing desyncs.
Improper use of on_load
Another way to cause desyncs is to make improper actions inside of an on_load call, which some players new to modding might try to do. According to the documentation, the on_load functionality is meant for 3 purposes only:
Doing anything else will cause desyncs. The game will catch most attempts, crashing instead and terminating the mod.
Comparison by reference
Be cautious of comparing tables by reference. In multiplayer syncing, tables deserialized from the server state will be new objects, not equal by reference to any table initialized by client code.
If a and b are tables in the above conditionals, there will for example be different results between server and client if a is created locally and b is downloaded from the server.
Note that LuaObjects provided by the game have their equality operator overwritten to prevent this behaviour, so code such as LuaEntityA
= LuaEntityB will not desync. However, this does not apply when LuaObjects are used as keys in tables:
This will desync in the same way as described for the plain tables a and b above. For entities it is recommended to use LuaEntity.unit_number as the table key instead of the whole entity.
Extended learning
One of the best ways to learn how to mod beyond this is to look at other mods. The Tutorial:Inspecting a live mod is a good starting point for touring a particularly well-commented mod. As all mods can be opened and inspected, looking at the mods of experienced modders can help significantly when making your own mod.
Keeping your mod working
As Factorio evolves, things will change. Previously, you probably ignored the modding part of the changelog, you now need to read it and see if any changes affect your mod(s). If so, you’ll need to fix them. If there’s something wrong with your mod, the game will fail to init and explain why.