Lua программы для программирования
Lua for Windows is a 'batteries included environment' for the Lua scripting language on Windows. NOTICE: Looking for maintainer.
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Latest commit
Git stats
Files
Failed to load latest commit information.
README.md
Lua for Windows is a 'batteries included environment' for the Lua scripting language on Windows.
Lua for Windows (LfW) combines Lua binaries, Lua libraries with a Lua-capable editor in a single install package for the Microsoft Windows operating system. LfW contains everything you need to write, run and debug Lua scripts on Windows. A wide variety of libraries and examples are included that are ready to use with Microsoft Windows. LfW runs on Windows 2000 and newer versions of Windows. Lua and its associated libraries are also available for other operating systems, so most scripts will be automatically cross-platform.
Download Lua For Windows installer from GitHub
Lua for Windows installs Lua language, SciTE based Lua IDE and Lua modules to the directory of you choice at install time. Lua for Windows and it's modules all depend on the MSVC++ 2005 runtime library. Lua for Windows install will automatically download this runtime and install it for you if you don't have runtime installed on your computer. The runtime is contained in the file vcredist_x86.exe, if you don't want the runtime to download during installation time (for offline instalation), just place the vcredist_86.exe in same directory as Lua for Windows install exe.
Installer Lua Interpreter, Lua Reference Manual, Quick Lua Tour Sample, Examples directory, Libraries with documentation. Lua Compiler (luac) Text Editors (SciTE and I think maybe wxLua editors too) C header files/libraries/etc. for building C module
Library | Version | Description |
---|---|---|
Alien | 0.5.0 | Provides access to functions in an unknown or new .dll. |
IUP | 3.5.0 | Light Portable Graphical User Interface library. |
CD | 5.4.1 | Canvas Draw: A platform-independent graphic library. |
IM | 3.6.3 | A toolkit for Digital Imaging. |
Ex | Jan 07 | Adds environment, file system, I/O (Locking and pipes), and process control. |
LPeg | 0.9 | Pattern-matching library based on Parsing Expression Grammars (PEGs). |
Lua-GD | 2.9.33r2 | Image manipulation library based on Thomas Boutell’s GD library. |
LuaCOM | 1.4 | Enable use & implementation of Microsoft’s Component Object Model. |
LuaCURL | 1.0 | Interface to Internet browsing capabilities based on the cURL library. |
Date | 2 | Date and Time library for Lua. |
LuaDoc | 3.01 | Documentation tool for Lua source code. |
LuaExpat | 1.1.0 | Lua interface to XML Expat parsing library. |
LuaFileSystem | 1.4.2 | Access the directory structure and file attributes. |
LuaLogging | 1.2.0 | Logging features in Lua, based on log4j. |
LuaProfiler | 2.0.1 | Time profiler designed to find bottlenecks in Lua programs. |
LuaSocket | 2.0.2 | Lua interface to support HTTP,FTP,SMTP, MIME, URL & LTN12. |
LuaSQL | 2.1.1 | Lua interface for PostgreSQL, ODBC, MySQL, SQLite, Oracle, and ADO dbms. |
LuaUnit | 2.0 | Testing framework for Lua. |
LuaZip | 1.2.3 | Read files from zip files. |
stdlib | 25 | Library of modules for common programming tasks, including list, table and functional operations, regexps, objects, pretty-printing and getopt. |
lrexlib | 2.2 | Regular expression library for Lua. |
MD5 | 1.1.2 | Basic cryptographic facilities for Lua. |
Copas | 1.1.5 | Dispatcher based on coroutines that can be used by TCP/IP servers. |
Coxpcall | 1.13 | Encapsulates the protected calls with a coroutine based loop, so errors can be dealed without the usual pcall/xpcall issues with coroutines. |
Rings | 1.2.2 | Provides a way to create new Lua states from within Lua. It also offers a simple way to communicate between the creator (http://loop.luaforge.net/) and the created (slave) states. |
LOOP | 2.3 Beta | LOOP stands for Lua Object-Oriented Programming and is a set of packages for supporting different models of object-oriented programming in the Lua language. |
LuaTask | 1.6.4 | Implements a concurrent and independent Lua execution environment model. |
LuaInterface | 1.5.3 | Integration between the Lua language and Microsoft .NET platform's Common Language Runtime (CLR). |
wxLua | 2.8.10 | Lua binding to the wxWidgets library. |
lpack | 29 Jun 2007 19:27:20 | Lua library for packing and unpacking binary data. |
VStruct | 1.0.2 | Provides functions for manipulating binary data. |
LuaBitOps | 1.0.1 | Lua BitOp is a C extension module for Lua 5.1 which adds bitwise operations on numbers. |
LuaXML | 1.3 | A module that maps between Lua and XML without much ado. |
Lanes | 2.0.4 | Provides the possibility to run multiple Lua states in parallel. |
MetaLua | 0.5-rc1 | A complete macro system with full compatibility with Lua 5.1 sources and bytecode: clean, elegant semantics and syntax, amazing expressive power, good performances, near-universal portability. |
LuaGL | 1.3 | Provides access to all of the OpenGL functionality from Lua 5.x . |
Penlight | 1.3.2 | Common lua code patterns for tables, arrays, strings, paths and directories, data, and functional programming. |
lbase64 | for Lua 5.1 | A base64 library for Lua. |
gzio | 0.9.0 | The Lua gzip file I/O module emulates the standard I/O module, but operates on compressed gzip format files. |
LuaRS232 | 1.0.0 | RS232 serial communications library |
LeMock | 0.6 | Mock creation module intended for use together with a unit test framework such as lunit or lunity. |
LuaRocks | 2.0.2 | A deployment and management system for Lua modules. |
Oil | 0.4-beta | It is a simple, efficient and flexible object request broker written in the Lua language. |
LuaJSON | 1.2.2 | JSON parser/encoder for Lua Parses JSON using LPEG for speed and flexibility. Depending on parser/encoder options, various values are preserved as best as possible. |
SubLua | 1.8.10-35352 | Subversion binding. |
30Log | 1.0.0 | 30 lines library for object orientation in Lua. |
Moses | 1.4.0 | Utility library for functional programming in Lua. |
Binary-Heaps | 1.5.1 | Implementation of binary heaps data structure in pure Lua. |
strictness | 0.2.0 | Tracks accesses and assignments of undefined variables in Lua. |
delaunay | 0.1.0 | Delaunay triangulation for convex polygon. |
5.1.3.12 9/July/2008 - First release
5.1.3.13 16/July/2008 - Second release
- New libs LOOPS, LuaTask, LuaInterface.
- Add Lua headers and Lua lib needed for embedding Lua.
5.1.3.15 7/August/2008 - Third release
- Added an environment variable called "LUA_DEV" to help C module developers configure their build files. This allows for the paths to be common and easily added to the project settings. (e.g. $(LUA_DEV)/include; $(LUA_DEV)/lib)
- Added the ability to download the 'vcredist_x86.exe'.
- Fixed Visual C++ 8.0 run-time problems. There now has to be a run-time for every dll loaded.
- Removed 'msvcr80.dll' from the root application directory.
- Updated the Visual C++ 8.0 run-time to SP1.
- Updated StdLib to version 6.
- Fixed missing Scite install issue with 5.1.3.14 release.
5.1.4.17 9/September/2008 - Fourth release.
- Fixed the readyiss.bat file to work with the new 'lua' directory.
- Added wxLua support.
- Updated to Lua v5.1.4.
- Changed the 'lualibs' to 'lua' to support the default locations.
- Updated SciTE property file to make the help show up correctly.
- Removed setting the LUA_PATH and LUA_CPATH environment variables.
5.1.4.18 11/September/2008 - Fifth release.
- Updated Stdlib to version 8.
- Updated the quickluatour.lua.
- Updated the luaforwindows document.
- Fixed LuaInterface module.
5.1.4.19 08/October/2008 - 6th release.
5.1.4.20 26/November/2008 - 7th release.
- Added lpack (29 Jun 2007 19:27:20) module.
- Added VStruct v 1.0 beta2 Lua module.
- Added BitLib release 25 module.
- Added LuaXML v1.3 module.
- Updated IUP to version 2.7.
- Updated CD to version 5.1.
- Updated IM to version 3.4.
5.1.4.21 5/December/2008 - 8th release.
- Fixed a SciTE bug when opening the Lua manual.
- Added lExecutor. This is a wxLua application that allows users to run console Lua scripts in a simple GUI. Look at the documentation (\docs\lexecutor) for more information.
- Added 'wildcard'.lexe files to run using lExecutor.
- Associated 'wildcard'.lexe files to a custom icon.
5.1.4.22 12/January/2009- 9th release.
- Added LuaBitOp v1.0.1 library.
- Fixed a bug in lExecutor to properly pass file loading error to the user.
- Fixed LuaDoc templates a bit for 'tables' and 'functions'.
- Fixed !LuaXML so it actually works. Opps.
- Updated Copas to version 1.1.4.
- Updated IUP to version 2.7.1.
- Updated CD to version 5.1.1.
- Updated IM to version 3.4.1.
- Removed BitLib. Use LuaBitOp instead.
5.1.4.23 06/Febuary/2009 - 10th release.
- Added MetaLua v0.5-rc1.
- Added the 'strict.lua' file shipped in the Lua in the 'etc' directory.
- Added Lanes v2.0.3 library.
- Updated LuaFileSystem to version 1.4.2.
5.1.4.24 rc1 14/April/2009 - 11th release
- Updated LPeg to version 0.9.
- Updated Copas to version 1.1.5.
- Updated the Lua executables so they run on Windows 64
5.1.4.25 rc2 15/April/2009 - 12th release
- Updated lua51.dll manifest to allow running on Windows 64.
5.1.4.26 rc3 23/April/2009 - 13th release
- Added an option to start the quickluatour.lua after installation completes.
- Added a link to the lExecutor documentation in the start menu.
- Now you can launch quickluatour.lua at the end of the installer
- Updated luaforwindows.html to be the right version in the example.
- Updated the LuaQuickTour thanks to Dirk Feytons.
- Fixed SciTE saving a debugger file to the current running scripts directory. Now it saves it to your local temp directory.
- Fixed SciTE toolbar icons being incorrect.
5.1.4-27 rc4 27/April/2009 -14th release
- Fixed SciTE debugger looking for the temp file in the %TMP% location.
- Fixed debugging files with spaces in the filename.
- Updated the IM, CD, and IUP examples.
- Made SciTE use the lua5.1.dll.
- Changed the version number to use a '-' as a build number of the LfW package.
- Changed the installer display name to 'Lua For Windows'.
5.1.4-28 29/June/2009 - 15th release
- Fixed SciTE debugger to allow it to debug modules in the same directory as the file using the module.
- Updated Stdlib to version 11.
5.1.4-29 03/Sept/2009 - 16th release
- Added Penlight v0.7.2 Lua module.
- Updated LuaCOM to version 1.4.
- Updated LuaGL to version 1.3.
- Updated VStruct to version 1.0.2.
5.1.4-30 10/Sept/2009 - 17th release
- Added lbase64 module.
- Added gzio module
- Updated stdlib to Release 12.
5.1.4-31 07/Dec/2009 - Internal only, not released
- Added markdown v0.32 Lua module.
- Fixed C Runtime Error R 6034. Problem 3.
- Fixed LuaInterface manifest loading issue.
- Updated luanet.dll to CoInitialize and search in the LUA_CPATH.
5.1.4-32 12/March/2010 - 18th release
- Added LuaRS232 v1.0.0
- Added iLua.cmd to easily launch iLua. Also added it to the start menu.
- Fixed SciTE to properly run interactive Lua session.
- Updated the clidebugger to take the same paramaters to allow for debug level.
- Updated Penlight to version 0.8.0.
- Updated IUP to version 3.0.0.
- Updated CD to version 5.3.0.
- Updated IM to version 3.6.0.
5.1.4-33 12/March/2010 - 19th release
5.1.4-34 18/March/2010 - 20th release
5.1.4-35 07/April/2010 - 21th release
- Updated lExecutor to version 1.01
- Updated Penlight to version 0.8.2
5.1.4-36 09/April/2010 - 22th release
5.1.4-37 04/May/2010 - 23th release
5.1.4-38 18/May/2010 - 24th release
5.1.4-39 17/June/2010 - 25th release
- Added LuaRocks version 2.0.2.
- Updated wxLua to version 2.8.10.
- Updated stdlib to release 15.
- Updated stdlib to release 14.
- Updated stdlib to release 13.
5.1.4-40 26/July/2010 - 26th release
5.1.4-41 11/Jan/2011 - 27th release
5.1.4-42 01/June/2011 - 28th release
- Updated LuaLogging to version 1.2.0.
- Updated stdlib to release 20.
- Updated Penlight to version 0.9.4.
5.1.4-43 06/June/2011 - 29th release
5.1.4-44 08/June/2011 - 30th release
5.1.4-45 14/June/2011 - 31st release
5.1.4-46 07/August/2012 - 32nd release
5.1.4-47 18/March/2015 - 33rd release
- Updated stdlib to release 28.
- Updated Penlight to 1.3.2.
- Updated SubLua to 1.8.10.
- WARNING: Moved all downloads and code hosting to GitHub. Older releases will not function when Google Code is shut down. Make sure to upgrade.
5.1.4-48 16/September/2015 - 34rd release
- Added 30Log v1.0.0 - 30 lines library for object orientation in Lua
- Updated SubLua to 1.8.11.
5.1.4-49 23/September/2015 - 35th release
- Added delaunay Lua module
- Added Binary Heaps Lua module
- Added Moses Lua module
5.1.4-50 22/October/2015 - 36th release
5.1.5-51 29/March/2016 - 37th release
- Updated to Lua 5.1.5.
- Updated SubLua to 1.8.10-35352
About
Lua for Windows is a 'batteries included environment' for the Lua scripting language on Windows. NOTICE: Looking for maintainer.
Вся серия не будет подчиняться какой-то системе. Уроки будут последовательно вводить ряд конструкций языка, чтобы уже к третьему или четвёртому уроку вы уже могли писать свои программы. Моя цель - подтолкнуть вас к самостоятельному изучению языка, помочь ощутить его, а не разъяснить от А до Я - если хотите освоить язык полностью, читайте справочное руководство (которое, хоть и скверно, переведено на русский язык: http://www.lua.ru/doc/). Чем раньше вы перейдёте от уроков "для чайников" в Сети к изучению справочника, тем лучше.
Если что-то непонятно - обязательно задайте вопрос в комментариях, и я и другие участники постараемся вам помочь.
Lua - популярный, несложный для освоения встраиваемый интерпретируемый динамически типизированный язык программирования общего назначения. Нет, вам необязательно понимать и половины слов, сказанных в предыдущем предложении - главное знайте, что он популярный и несложный. Кстати, простотой, а также маленьким размером дистрибутива (около 150 килобайт), он и заслужил свою популярность. Скрипты на Lua поддерживаются большим количеством приложений, в том числе играми. World of Warcraft и S.T.A.L.K.E.R. используют язык Lua. Мой любимый игровой движок, LÖVE, позволит вам с помощью Lua с лёгкостью создавать разнообразные игры. Как видите, Lua открывает вам немалые горизонты!
Прежде чем мы начнём, вам следует обустроить среду для программирования: то есть, найти программу, которая принимала бы написанный вами код на Lua и исполняла его: интерпретатор. Тут есть три варианта:
Пользователям операционных систем на базе Linux в этом смысле проще: им достаточно воспользоваться пакетным менеджером и установить Lua из репозиториев. В Debian и Ubuntu это делается командой apt-get install lua, а в Fedora, Red Hat и производных дистрибутивах - yum install lua. Однако не доверяйте мне слепо и обратитесь к справочнику вашей операционной системы, чтобы узнать, как именно это делается у вас.
2. Использовать онлайн-интерпретатор.
3. Использовать IDE.
В ходу сейчас две несколько различающиеся версии Lua: 5.1 и 5.2. Я буду ориентироваться на самую последнюю версию - версию 5.2, но обязательно укажу на важные различия между ей и 5.1, так как последняя тоже достаточно распространена. Кстати, Lua 5.1 исполняет код в полтора раза быстрее, чем Lua 5.2, чтобы вы знали.
Итак, начнём. Создайте в изолированной от посторонних файлов папке файл main.lua и напишите в него:
После чего запустите в командной строке (не забудьте переместиться в директорию с main.lua с помощью команды cd):
Комментарии в Lua (да и в любом языке программирования в принципе) — это та часть кода, которая не читается языком. Чтобы там ни находилось, язык это не прочтёт. Для него этого в принципе не существует.
Обычно применяется для описания скрипта, чтобы другие знали, что он из себя представляет, а также для создания пометок, чтобы можно было быстро найти скрипт среди тысяч строк кода.
А также полезен для того, чтобы можно было убрать часть скрипта при этом с возможностью возврата.
§1.1. Строчные комментарии.
В Lua выглядят следующим образом: два дефиса, стоящие друг к другу, — «--».
§1.2. Многострочные комментарии.
По названию всё ясно — при помощи них можно комментировать сразу несколько строк. Начало — «--[[», а конец — «]]».
Так ведь намного быстрее, не правда ли?
§1.3. Комментирование части строки.
Иногда бывает полезно сделать и такое. А сделать это можно при помощи многострочных комментариев.
Для тестирования эта вещь достаточно полезная. В интерпретаторе это функция print.
Достаточно элементарно.
--========================
§3. Типы данных в Lua.
Их всего восемь:
1. nil — абсолютное ничего. Означает отсутствие данных. Иногда появление nil может быть чревато ошибками.
2. boolean — логический тип данных. К нему относятся true (истина) и false (ложь). При выполнении логических операций false равнозначен nil.
3. number — и так всё прекрасно понятно. Десятичный разделитель в Lua — точка. В остальном проблем не должно возникнуть.
4. string — строка. Это отдельные параграф.
5. function — функция. Также отдельный параграф.
6. table — таблица. И снова отдельный параграф.
7. userdata — пользовательские данные.
8. thread — поток.
§3.1. Определение типов данных.
Принудительно этого делать не надо — Lua сам поймёт, что это за тип данных. Но иногда появляется необходимость понять, какой же тип данных использует та или иная переменная. Для этого придумали функцию type().
Все возможные строки, которые эта функция возвращает: «nil» (как строка, а не значение nil), «number», «string», «boolean», «table», «function», «thread» и «userdata».
--========================
§4. Несколько полезных базовых функций Lua.
dofile() — открывает файл по указанному пути и выполняет его содержимое как Lua задачу.
В скобках в кавычках должен быть написан путь до файла, его имя и, конечно же, расширение, потому что расширение файла может быть не *.lua, а любым другим, но при этом внутри него будут коды на Lua.
Путь должен должен быть записан в кавычках.
tonumber() — преобразует переменную в число. Не очень понимаю, как это работает. Если параметр уже является числом или строкой, конвертируемой в число, то tonumber() возвращает это число, иначе возвращает nil.
Основание может быть любым целым числом в диапазоне от 2 до 36 включительно.
Если основание больше 10, то символ «A» (как в верхнем, так и в нижнем регистре) представляет 10, «B» представляет 11 и так далее, символ «Z» представляет 35. При основании 10 (по умолчанию),
число может быть представлено в экспоненциальной форме.
Для других оснований можно указывать только беззнаковые целые числа.
_VERSION — глобальная переменная (не функция), возвращающая строку с версией интерпретатора.
-- при вызове этой переменной на самой последней официальной версии Lua эта перменная возвращает следующее:
print(_VERSION); -- Lua 5.3.1
Их здесь всего не четыре, как учили в школе, а шесть:
+
-
*
/
% (остаток от деления)
^ (возведение в степень)
Для более корректных вычислений можно применять скобки.
--========================
§6. Логические выражения.
Предисловие.
Логические выражения выполняют действие (или не одно), если вы полнилось какое-то другое действие (или, опять же, не одно).
§6.1. Логические операторы.
Прежде чем переходить к изучению логических выражений (по-простому — условий), надо бегло пройтись по условным операторам. Вот все они:
not (не);
and (и);
or (или);
== (равно);
~= (не равно) вместо привычного многим !=;
> (больше);
< (меньше);
>= (больше или равно);
§6.2. Простейшие условия.
Самое простое условие выглядит так:
Не стоит ничего объяснять — на примере всё станет понятно:
if a then -- если переменная «а» существует
a = 1; -- тогда переменная имеет значение 1.
end -- конец
Запись «if a then» эквивалентна «if a ~= nil then» (если «а» не равна nil). То есть просто идёт проверка на существование переменной в принципе.
§6.3. Условия с «else».
«else» выполняет другое действие, если условие c «if» не выполнилось.
Пример:
a = 1;
if a == 1 then -- если переменная «а» равна единице
print("a is 1"); -- тогда..
else -- если не выполнится
print("a is not 1"); -- тогда.
end -- конец
Важно знать, что блок «else» всегда один (то есть два и более else не допустимы) и всегда ставится в конце других условий.
§6.4. Условия с «elseif».
Блок «elseif» выполняет ряд других условий (или только одно), если предыдущие (или только одно) не выполнились.
if a > 2 then -- если а больше двух
a = 3; -- тогда а равна трём
elseif a < 2 then -- если же а меньше двух
a = 1; -- тогда а равна единице
else -- иначе
a = nil; -- тогда удалить а
end -- конец
Тут можно сразу вставить блок «else».
Блоков elseif может быть сколько угодно много. Располагаются они всегда после if и перед else (если он есть).
§6.5. Оператор not.
Долго о нём разглагольствовать не надо. Просто отрицание какой-либо операции.
Пример:
Хотя в данном примере лучше not a > 4 заменить на a
Рассмотрим другой пример:
Здесь проверятся несуществование переменной a. В данном случае эта переменная не указана, соответственно, условие выполнится.
§6.6. Несколько условий в одном if/elseif.
Для этого есть операторы and и or:
Ни a, ни b, ни c не должны быть равны nil в данном примере. Если хоть одна переменная окажется равной nil, условие не выполнится.
Другое дело с or:
Условие не выполнится только в том случае, если все три переменные окажутся равны nil. Если хотя бы одна переменная окажется не равной nil, то условие выполнится.
Также бывают случаи, когда необходимо исключить из условия сразу несколько переменных, например a и c. Можно конечно сделать так:
Но есть более упрощённый вариант — использовать скобки:
Так же можно поступить и с or:
С подобными вполне конструкциями можно поэкспериментировать.
А с elseif всё абсолютно идентично.
§6.7. Функция rawequal.
Дополнительная функция, поверяющая равенство двух переменных. Возвращает тип данных boolean.
if rawequal(a,b) == true then
print(a+b); -- 2
end
if a == b then
print(a+b); -- 2
end
§7.1. Глобальные переменные.
Это присваивание переменной какого-либо значения до тех пор, пока ей не присвоится какое-либо другое значение:
Можно записывать сразу несколько переменных:
if a == 1 then
a = b;
end
if rawequal(a,b) then
print(a); -- 2
end
§7.2. Локальные переменные.
Отличаются от глобальных тем, что локальная переменная может принимать любое значение, а для глобального присвоение присваиваемое значение должно при этом существовать как переменная.
Также присваивание теряется, дойдя до ближайшего end либо else, либо elseif. Если объявить переменную вне всяких выражений, она останется навсегда. Объявляется с помощью оператора local:
Не следует забывать, что перед знаком равно пишется значение, которое присваивается переменной, а после — сама переменная.
К этому оператору ещё вернёмся.
Как уже было сказано выше, локальные переменные объявляются на время скрипта:
Таким образом, одну и ту же переменную можно объявлять много раз в разных скриптах.
По возможности лучше всегда использовать локальные переменные — они помогают избежать хаоса в скриптах, лишних имён и прочего.
Да и длинные обращения можно урезать до одной буквы, тогда это сильно сэкономит время.
0
Также бывают случаи, когда необходимо исключить из условия сразу несколько переменных, например a и c. Можно конечно сделать так:
Код
if not a and not b and c then
.
end
Но есть более упрощённый вариант — использовать скобки:
Код
if not (a and b) and c then // not (a or b) and c
.
end
Так же можно поступить и с or:
Код
if not (a or b) and c then -- not (a [color=blue]and b) or[color=blue] c
.
end
С подобными вполне конструкциями можно поэкспериментировать.
Разработка компьютерных игр. С чего начать? Это просто! С нуля до разработчика игр: как начать создавать свою игру. Заказать создание игры.
Getting started
Lua is a powerful and fast programming language that is easy to learn and use and to embed into your application.
Lua is designed to be a lightweight embeddable scripting language. It is used for all sorts of applications, from games to web applications and image processing.
See the about page for details and some reasons why you should choose Lua.
See what Lua programs look and feel like in the live demo.
A good place to start learning Lua is the book Programming in Lua, available in paperback and as an e-book. The first edition is freely available online. See also course notes based on this book.
The official definition of the Lua language is given in the reference manual.
See the documentation page and the wiki for more.
Our community is friendly and will most probably help you if you need. Just visit the mailing list, the chat room, and stackoverflow.
If you need help in Portuguese, join the Lua BR mailing list and visit pt.stackoverflow.
See also the FAQ, the community-maintained wiki and LuaFaq, and the much longer uFAQ.
If you need to complement the standard Lua libraries to handle more complex tasks, visit LuaRocks, the main repository of Lua modules. See also Awesome Lua, a curated list of quality Lua packages and resources. The lua-users wiki lists many user-contributed addons for Lua.
You can also help to spread the word about Lua by buying Lua products at Zazzle.
Use the live demo to play with Lua if you don't want to install anything on your computer.
To run Lua programs on your computer, you'll need a standalone Lua interpreter and perhaps some additional Lua libraries. Pre-compiled Lua libraries and executables are available at LuaBinaries. Use your favorite text editor to write your Lua programs. Make sure to save your programs as plain text. If you want an IDE, try ZeroBrane Studio.
If you use Windows, try LuaDist, a multi-platform distribution of the Lua that includes batteries.
If you use Linux or Mac OS X, Lua is either already installed on your system or there is a Lua package for it. Make sure you get the latest release of Lua (currently 5.4.4).
Lua is also quite easy to build from source, as explained below.
Lua is very easy to build and install. Just download it and follow the instructions in the package.
Here is a simple terminal session that downloads the current release of Lua and builds it in a Linux system: If you don't have curl, try wget.
If you use Windows and want to build Lua from source, there are detailed instructions in the wiki.
Implementations, Interpreters, and Bindings
-
- Lua's original ANSI C interpreter.
-
- The official Lua repo, as seen by the Lua team, mirrored to GitHub.
Note: From LuaJIT to Lua to lua.vm.js to Moonshine, a basic benchmark sees performance drop by roughly a factor of 6 with each hop.
-
- De-facto tool for installing Lua modules as packages called "rocks", plus public rock repository and website. Much like npm or pip.
Build Tools and Standalone Makers
-
- A build engine written in Lua, similar to Ruby's rake. - Highly customizable Lua 5.2 build system. - Simple tool for turning Lua programs into standalone executables. - A batteries-included creator of standalone executables, built on top of luastatic.
Debugging and Profiling
-
- Simple profiler that works with LuaJIT and produces a report file. - Toolset for tracing/analyzing/profiling script execution and generating detailed reports. - Drop-in upgrade to Lua's stack traces which adds local context and improves readability. - Powerful remote debugger with breakpoints and stack inspection. Used by ZeroBraneStudio. - Browser-based debug console. Originally made for LÖVE, but works in any project with LuaSocket support.
IDEs and Plugins
-
- Eclipse plugin which provides code completion, debugging, and more. Built on Metalua. - IntelliJ IDEA plugin which, among other things, provides code completion, smart highlighting, and experimental debugging. - Lightweight, customizable, cross-platform Lua-dedicated IDE with code completion and analysis, written in Lua. Has broad debugging support for numerous Lua engines. - Lua editor/debugger extension for VS2012-13 with highlighting, auto-completion, linting, and formatting capabilities. - Emacs major mode for editing Lua. - VSCode intellisense and linting.
-
- High-performance functional programming library designed for LuaJIT. - Functional programming utility belt, inspired by Underscore.js. - Broad, heavyweight utility library, inspired by Python's standard libs. Provides the batteries that Lua doesn't. - Middle-weight standard library extension; adds some useful data structures, utility functions, and basic functional stuff. - A little library of useful Lua functions; the 'extra light' version of Penlight. - Compatibility module providing Lua-5.3-style APIs for Lua 5.2 and 5.1. - Reactive Extensions, Observables, etc.
-
- Desktop game development platform. Cross-platform, feature-complete, well-adopted. - Development platform for iOS and Android. Proprietary, but used by numerous top games and apps, totaling over 150 million downloads. - Open source, cross-platform, mobile game development framework. Minimalist C++ engine powered by Lua scripting. - Open source, games can run on Linux or on any platform with a recent web browser. - Open source, audio/visual toolkit suitable for small games and experimentation. It runs on Windows, Mac, Linux, HTML5 and iOS. - 3D framework for creating virtual reality experiences, inspired by LÖVE 2D.
-
Corona
-
- Simple cloud platform supporting analytics, data objects, user management, and more.
-
- A list like this one, but focused on game dev and the LÖVE platform. - Shortens the iteration cycle by auto-swapping changed Lua files in a running LÖVE project. - A set of lightweight helpers for LÖVE; a game-oriented utility belt.
-
- Edit and share short scripts for the MOAI game engine and run them in the browser using WebGL.
-
- Minimal rectangle-based collision detection which handles tunnelling and basic collision resolution. - Detect collisions between arbitrarily positioned and rotated shapes of any type.
-
- A fast, lightweight tweening library for Lua with easing functions and the ability to group tweens together. - Small library for tweening, with several easing functions.
-
- A tetris clone, written in literate style with "an emphasis on learn-from-ability". - A Pac-man clone, made with LÖVE. - Fusion of Mario and Portal, made with LÖVE. See also its wikipedia entry. - 2D platformer based on Community's Digital Estate Planning episode, made with LÖVE.
-
- Asynchronous logging library with pluggable writers for file system, network, ZeroMQ, and more. - Log4j-inspired logging library supporting various appenders. - Log to syslog, based on LuaLogging.
Search this page for 'OpenResty' to find related packages under other categories (data stores in particular).
-
- Simple function for printing to the console in color. - A simple command-line argument parsing module. - Terminal operations and manipulations. - A feature-rich command line parser inspired by argparse for Python.
Concurrency and Multithreading
-
Coroutine-based multitasking:
-
- Simple concurrent task scheduling. - Implements an Erlang-style message-passing concurrency model. - Library for managing sockets, signals, and threads based on an event loop with coroutines.
-
- A simple wrapper for low-level pthreads & WIN32 threads. - Newer rewrite of llthreads. - Library implementing a message passing model with one OS thread per Lua thread. - Message-passing model which allows multiple threads per OS thread and easily generalizes across a network. See also the paper where it originated.
For more on the differences (particularly between lanes and luaproc ), see this comparison of options; somewhat dated, but covers how each one works and the significant differences.
-
- Mustache template implementation. - Embedded Lua templates, ERB-style. - Lua-oriented template engine for OpenResty, somewhat Jinja-like.
-
- Documentation generator which modernizes and extends LuaDoc. - Lua port of Docco, the "quick-and-dirty, hundred-line-long, literate-programming-style documentation generator". - Parse comments into a Lua table to generate documentation.
-
- Minimalist OOP library with basic classes, inheritance, and mixins in 30 lines. - Simple but robust OOP library with inheritance, methods, metamethods, class variables and mixins.
File system and OS
-
- Extends and complements Lua's built-in set of file system functions. - Bindings for POSIX APIs, including curses. - Bindings to common Unix system APIs, striving for thread-safety. - File system path manipulation library.
-
- Date and time module with parsing, formatting, addition/subtraction, localization, and ISO 8601 support. - Time-related functions for Lua, inspired by JavaScript's setTimeout and setInterval. - Time, date, and timezone library.
Digital Signal Processing
-
- An easy to use Fast Fourier Transformation package in pure Lua. - Sound/music/DSP engine written for LuaJIT.
Hardware and Embedded Systems
-
- Lua, extended with optimizations and specific features for efficient and portable embedded software development.
Math and Scientific Computing
-
- Numerical/scientific computing framework built on LuaJIT, with an interface to R. - Scientific computing framework with wide support for machine learning algorithms, used by Facebook, Google, and more. - Assorted libraries and tools, many math- or data-related.
Parsing and Serialization
-
JSON
-
- Blazing fast JSON encoding/decoding implemented in C and exposed to Lua. - JSON encoder/decoder implemented in Lua on top of LPeg. - JSON encoder/decoder implemented in pure Lua. - A fast and tiny JSON library in pure Lua.
-
- SAX XML parser via binding to the Expat library. - Pure Lua SAX-like streaming XML parser.
-
- Pure Lua implementation of MessagePack. - A MessagePack C implementation with Lua bindings, as used by Redis.=
-
- A pattern-matching library for Lua, based on Parsing Expression Grammars. - A collection of LPeg patterns. - A pure Lua implementation of LPeg v0.12. - A pure LuaJIT implementation of LPeg v1.0. - An extension of LPeg adding support for labeled failures.
-
- Internationalization library with locales, formatting, and pluralization. - Human-readable representation of Lua tables. - Serializer and pretty printer. - Dead simple serializer with good performance. - Simple string key-value store for i18n.
-
- Simple streaming interface to zlib for gzip/gunzip. - Lua binding to libzip. Reads and writes zip files.
-
- Simple interface for connecting to ODBC, ADO, Oracle, MySQL, SQLite and PostgreSQL. - Lua PostgreSQL driver for OpenResty, LuaSocket, and cqueues. - Lua MySQL driver for OpenResty. - Lua Cassandra client driver for OpenResty and others.
Redis
-
- Pure Lua client library for Redis. - Lua Redis client driver for OpenResty. - Asynchronous Redis client with pipelining and Pub/Sub support; based on cqueues.
-
- Lua bindings to ZeroMQ. - A newer Lua binding to ZeroMQ. - Kafka client driver based on OpenResty cosockets. - RabbitMQ client library based on OpenResty cosockets.
-
- BDD-style unit testing framework with great docs and Moonscript support. - Flexible and highly customizable testing library. - Assertion library extending Lua's built-in assertions. - Minimal test framework.
Foreign Function Interfaces
-
- LuaJIT's mechanism for calling external C functions and using C data structures from pure Lua code. - Standalone FFI library, compatible with the LuaJIT FFI interface.
Analysis Tools and ASTs
-
- Lua Decompiler for Lua version 5.1. - Simple coverage analyzer, used by busted and telescope for checking test coverage.
-
- LuaCov reporter for coveralls.io.
-
- Moonshine + LÖVE API reimplementation = run LÖVE games in the browser. - Node.js's underlying architecture (libUV) with Lua on top instead of JavaScript. - Lua implementation of GraphQL.
Scriptable by Lua
-
- Fast, small, webkit based browser framework extensible by Lua. - A powerful, extensible OS X automation tool. A community-maintained fork of Mjolnir. - A scripting utility to juggle windows. - A console-based mail client, with extensive scripting capabilities. - A highly configurable and extensible window manager for X, scripted and configured by Lua. - Extremely lightweight, customizable, cross-platform editor, written (mostly) in (and scripted by) Lua. - An ebook reader application supports PDF, DJVU, EPUB, FB2 and much more, running on Kindle, Kobo, PocketBook and Android devices.
-
- Moonscript is a dynamic scripting language that compiles to Lua. It reduces verbosity and provides a rich set of features like comprehensions and classes. Its author calls it 'CoffeeScript for Lua'. - A static site generator which uses MoonScript and supports HTML and Markdown, page grouping, and plugins.
-
- The official Lua mailing list, and one of the focal points of the Lua community. - The Lua community blog. - An association of individuals with the mission of supporting and promoting Lua and its community and ecosystems. - A site for and by users of Lua, featuring an IRC channel, a web archive of lua-l, and a large wiki.
Conferences/Meetups
-
- Annual 2-day meeting of the Lua community, in rotating locations. - Annual 1-day Lua conference in Brazil. - Annual 2-day gathering of F/OSS developers in Brussels which sometimes has a "Lua devroom".
-
- The official definition of the Lua language. - A large community-maintained collection of Lua information and resources, supplementing the official website. - Answers all sorts of Lua-related questions, including many of the form 'How to ___?'.
-
- A general, high-level style guide; unopinionated, easily agreed on. - A more opinionated and specific, and therefore more rigorous, guide.
-
- Short crash course readover, or reference for when you forget the basics. - A well-commented example file which covers the basics. - An overview of the similarities and differences between Lua and JS; a great start for JavaScript folks looking to pick up Lua. - In-depth collection of tutorials aimed at newcomers. - A series of 'Missions' to work through which are designed to teach aspects of Lua along the way. - Walks through setting up and using OpenResty to build a simple image processing server; a great starting point for playing with OpenResty.
-
- An introductory walkthrough of embedding Lua in a C program. A bit dated, but still a great walkthrough. - A thorough summary of the good, different, bad, and ugly aspects of Lua, including many subtle quirks, by the author of ZeroBraneStudio. - Diagrams and explains some more advanced concepts of the Lua VM, particularly when interfacing with C.
-
- History of talks given by Lua's chief architect, with slides for each. - High-quality talks are given at each ~annual Lua Workshop, and a history of them is online, slides included.
-
- The authoritative intro to all aspects of Lua programming, written by Lua's chief architect. Three editions released; first edition available online. - A quick reference on how to program in and embed Lua 5.1 through 5.3, by the creator of Textadept. - A collection of articles covering existing wisdom and practices on programming well in Lua, in a broad variety of use cases. - A shorter overview of the language, up to date for Lua 5.2, and available online.
-
- A list like this one, but focused on OpenResty. - A list like this one, but focused on game dev and the LÖVE platform. - A comprehensive list of stand-alone programs written in or extensible using Lua.
Contributions welcome and wanted! Read the contribution guidelines first.
To the extent possible under law, Lewis Ellis has waived all copyright and related or neighboring rights to this work.
Читайте также: