Lua for windows


rjpcomputing/luaforwindows: Lua for Windows is a 'batteries included environment' for the Lua scripting language on Windows.

Overview

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

Download Lua For Windows installer from GitHub

Install Notes

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 this download to occur at installation then place the vcredist_86.exe in same directory as Lua for Windows install exe.

LfW Components

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

Libraries included

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.

History

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

  • Updated Penlight to version 0.8.1

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

  • Updated Penlight to version 0.8.3

5.1.4-37 04/May/2010 - 23th release

  • Updated Penlight to version 0.8.4

5.1.4-38 18/May/2010 - 24th release

  • Fixed #10 - LuaDoc incomplete. Added luadoc_start.bat.
  • Fixed #09 - luanet kill lua.exe
  • Updated the SciTE .api file. Now includes lfs, bit and pack.

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

  • Fixes #14 - Just a simple mistake in the link to LuaEx.
  • Fixes #18 - Lua tutorial typo.
  • Reverted to wxLua version 2.8.7 because there are issues with the new versions stability. It will get updated later.
  • Fixed pplot examples that ship with IUP.
  • Closed #20 - Updated IUP to version 3.2.0.
  • Updated Lanes to version 2.0.4.
  • Added Oil version 0.4-beta.

5.1.4-41 11/Jan/2011 - 27th release

  • Fixes #34 - LuaXML clib delivered with LuaForWindows causes memory leaks.

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

  • Fixes #1 - LuaSocket example not upto date - cddb.lua.
  • Fixes #24 - Commented-out visible whitespace acquires coment colour.
  • Closed #19 - Added LuaJSON v1.2.2 library.
  • Closed #41 - Updated Alien to version 0.5.0.
  • Updated LPeg to version 0.10-1.
  • Updated stdlib to release 21.

5.1.4-44 08/June/2011 - 30th release

  • Fixed pl.dir so you can use strict module

5.1.4-45 14/June/2011 - 31st release

  • Fixes #42 - Please update Tecgraf libs (CD, IM, IUP)
  • Updated IUP to version 3.5.0.
  • Updated CD to version 5.4.1.
  • Updated IM to version 3.6.3.

5.1.4-46 07/August/2012 - 32nd release

  • Fixes #43 - require('lpeg') -- system error 14001
  • Updated stdlib to release 25.
  • Updated the Visual C++ 8.0 run-time to SP1-4053.
  • Updated lpeg.dll manifest to allow running on older vcredist_x86.
  • Updated alien/core.dll manifest to allow running on older vcredist_x86.
  • Updated alien/struct.dll manifest to allow running on older vcredist_x86.
  • Updated examples/alien/tests/alientest.dll manifest to allow running on older vcredist_x86.
  • Updated LuaXML_lib.dll manifest to allow running on older vcredist_x86.
  • Updated w32.dll manifest to allow running on older vcredist_x86.
  • Updated Penlight to version 1.0.3.
  • Updated LuaUnit to version 2.0.
  • Added SubLua version 1.7.4 - Subversion binding

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

  • Fixes #98 - Lua For Windows Installer - 'h' is an invalid URL.
  • Changed app URL to point to GitHub.
  • Changed minimum version to reflect the GitHub version.

5.1.5-51 29/March/2016 - 37th release

  • Updated to Lua 5.1.5.
  • Updated SubLua to 1.8.10-35352

github.com

как перестать встраивать и начать жить / Хабрахабр

Lua: как перестать встраивать и начать жить

За Lua прочно закрепилась слава полуязыка — инструмента, который при случае можно встроить, чтобы заскриптовать приложение, написанное на компилируемом языке вроде С++. Тем не менее Lua является вполне самостоятельным языком, имеющим свой интерпретатор, возможность создания модулей, большое число библиотек, и при этом данный ЯП обладает минимальным размером среди аналогов. Проще говоря у нас есть все, чтобы создавать такие же приложения как на perl, python, и вообще любом другом распространенном языке программирования.

Я могу предложить вам следующие доводы в пользу Lua:

  • — приложения будут легко переносимы между Windows и Linux (не факт что код будет работать без изменений, но портирование правда пройдет безболезненно, если не были использованы платформоспецифичные библиотеки)
  • — малый оверхед создаваемых программ
  • — высокая скорость работы и загрузки приложений
  • — возможность оперативно «приклеить» к вашему приложению любую С-библиотеку — лучшего «клея» для библиотек вы не найдете
  • — приятный минималистичный синтаксис языка, с возможностью реализации на нем современных парадигм программирования
  • — программы на Lua очень легко развертывать
  • — малое потребление памяти

Чтобы продемонстрировать возможности Lua, я покажу как с его использованием создать небольшую программу для построения графиков по точкам с возможностью сохранения графика в виде файла изображения.

В качестве графического тулкита будем использовать iup — кроссплатформенную библиотеку, изначально созданную с расчетом использования из Lua.

Установка Lua SDK
В рамках идеи использования Lua как самостоятельного ЯП, была создана сборка Lua for Windows, которая содержит себе библиотеки, необходимые в повседневных задачах, возникающих при программировании под указанную ОС: работы с БД, GUI, парсинг XML и т.д. Пусть вас не смущает, что версия Lua в сборке 5.1, а не 5.2 — особой разницы в нашем случае между ними нет.

Скачайте и установите сборку.

Краткое описание концепции iup
Я долго думал, как же расписать процесс создания программы, не вдаваясь подробно в устройство iup. И решил коротко описать его основные принципы:
  • — iup.dialog является корневым элементом интерфейса программы — в этом контейнере размещаются все элементы
  • — позиционирование элементов в контейнере производится при помощи layout-ов: задания правил размещения элемента в контейнере. Iup сам расположит и отрисует элемент согласно правилам. Основные контейнеры — фрейм, вертикальный сайзер, горизонтальный сайзер.
  • — обработчики событий задаются в виде функций, прикрепленных к виджету
  • — после создания диалога запускается цикл обработки событий
Если вы ранее писали для GUI при помощи Tk, WxWidgets или WinAPI, то все это покажется знакомым. Если нет, то программа довольно подробно покрыта комментариями.
Код программы
-- подключение библиотек iup require("iuplua" ) require("iupluacontrols") require("iuplua_pplot") -- библиотека для работы с Canvas, чтобы сохранять график в файл require("cdlua") require("iupluacd") require("string") -- глобальные переменные для виджетов и настроек программы -- максимальное число графиков plots_number = 5 -- виджеты вкладок, где будут размещаться виджеы ввода данных для каждого графика tabs = {} -- контейнеры для виджетов vboxes = {} -- чекбоксы для выбора того, какие графики строить checkboxes = {} -- здесь храним виджеты с текстом данных о точках coords = {} -- виджеты подписи для каждого графика legends = {} -- виджеты обозначения осей координат global_legend = {} -- к величайшему стыду, в Lua нет стандартной функции split function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- функция рисует на плоттере график по указаным точкам function draw_plot(pwidget, pnum, data) x = data[1].value:split(",") y = data[2].value:split(",") if checkboxes[pnum].value == "OFF" then return end if not (#x == #y) or #x == 0 then iup.Message("Ошибка", "Задано неверное число точек для графика " .. pnum) return end iup.PPlotBegin(pwidget, 0) iup.PPlotAdd(pwidget, 0, 0) for i = 1,#x do iup.PPlotAdd(pwidget, x[i], y[i]) end iup.PPlotEnd(pwidget) end -- виджет отвечающий за кнопку построения графика plot_btn = iup.button{ title = "Построить"} -- колбэк для кнопки "построить график" function plot_btn:action() -- создать виджет графопостроителя plot = iup.pplot { expand="YES", TITLE = "Simple Line", MARGINBOTTOM="65", MARGINLEFT="65", AXS_XLABEL = global_legend[1].value, AXS_YLABEL = global_legend[2].value, LEGENDSHOW="YES", LEGENDPOS="TOPLEFT", size = "400x300" } -- этот блок для обхода бага - без него подпись к первому графику отображаться не будет iup.PPlotBegin(plot, 0) iup.PPlotAdd(plot,0,0) plot.DS_LEGEND = "" iup.PPlotEnd(plot) -- обходим виджеты с данными for i = 1, plots_number do -- чтобы свеженарисованный графи отобразился с правильной подписью print(legends[i].value) plot.DS_LEGEND = legends[i].value -- рисуем график draw_plot(plot, i, coords[i]) end -- кнопка сохранения графика в картинку на диске save_btn = iup.button{ title = "Сохранить" } -- теперь создаем само окно, где будет отображаться график plot_dg = iup.dialog { iup.vbox -- это вертикальный сайзер, помести в него графопостроитель и кнопку { plot, save_btn }, } -- обработчик кнопки сохранения графика function save_btn:action() -- создаем диалог выбора имени файла ля сохранения -- в связи с ограничениями библиотеки сохранять можно только в EMF fs_dlg = iup.filedlg{DIALOGTYPE = "SAVE", FILTER = "*.emf" } iup.Popup(fs_dlg) -- если файл выбран if tonumber(fs_dlg.STATUS) >= 0 then -- дописать при необходимости нужное расширение pic = fs_dlg.value if not (string.sub(pic, string.len(pic)-3) == ".emf") then pic = pic .. ".emf" end -- создаем псевдо-холст, ассоциированный с файлом tmp_cv = cd.CreateCanvas(cd.EMF, pic .. " 400x300") -- выводим график на холст iup.PPlotPaintTo(plot, tmp_cv) -- сохраняем данные в файл cd.KillCanvas(tmp_cv) end end -- отображаем диалог с графиком plot_dg:showxy(iup.CENTER, iup.CENTER) -- запускаем петлю обработки событий для диалога if (iup.MainLoopLevel()==0) then iup.MainLoop() end end -- в цикле создаем вкладки, в которых мы будем размещать виджеты -- для сбора данных for i=1,plots_number do -- создание текстовых виджетов, куда будут вводиться координаты точек coords[i] = {} for j = 1,2 do coords[i][j] = iup.text { expand="HORIZONTAL", multiline = "YES", VISIBLELINES = 5 } end -- виджет для редактирования подписи к графику legends[i] = iup.text{ expand = "HORIZONTAL" } -- создаем контейнер вкладки и заполняем его элементами vboxes[i] = iup.vbox { iup.hbox { iup.label { title = "Подпись графика:" }, legends[i] }, iup.hbox { iup.label { title="X : ", }, coords[i][1] }, iup.hbox { iup.label { title="Y : ", }, coords[i][2] }; expand="YES", } -- меняем заголовк вкладки vboxes[i].tabtitle = "График " .. i -- создаем чекбокс, который будет указывать на то, нужно ли строить -- график по данным из указанной вкладки checkboxes[i] = iup.toggle{ title= "График" .. i, value = "ON" } end -- теперь из заполненных нами контейнеров создаем вкладки tabs = iup.tabs{unpack(vboxes)} -- создаем текстовые виджеты для редактирования подписей осей global_legend[1] = iup.text{} global_legend[2] = iup.text{} -- создаем фрейм для общих настроек графика frame = iup.frame { iup.vbox { iup.label{ title="Использовать данные:", expand="HORIZONTAL" }, iup.vbox { unpack(checkboxes) }, iup.label{}, -- пустую подпись можно использовать как распорку iup.label{title = "Подписи"}, iup.hbox { iup.label{ title = "Ось X "}, global_legend[1] }, iup.hbox { iup.label{ title = "Ось Y "}, global_legend[2] }, iup.label{}, plot_btn }; expand = "VERTICAL", } -- создаем главное окно программы и наносим на него настройки и табы dg = iup.dialog { iup.hbox { frame, tabs }, title="Строим график", size = "HALF" } -- показываем главное окно и запускаем обработку событий dg:showxy(iup.CENTER, iup.CENTER) if (iup.MainLoopLevel()==0) then iup.MainLoop() end
Пара слов о развертывании
Скрипт можно запустить при помощи команды:lua plotter.exe

В данном случае библиотеки будут подключаться из поддиректории clibs/, которая находится в директории, куда был установлен Lua for Windows. Чтобы максимально компактно упаковать скрипт и библиотеки для переноса на другую машину, достаточно скопировать в одну папку следущие файлы(указаны с относительными путями от директории установки Lua):

lua.exe lib/lua5.1.dll clibs/cd.dll clibs/cdlua51.dll clibs/iup.dll clibs/iup_pplot.dll clibs/iupcd.dll clibs/iupcontrols.dll clibs/iupgl.dll clibs/iuplua51.dll clibs/iuplua_pplot51.dll clibs/iupluacd51.dll clibs/iupluacontrols51.dll clibs/freetype6.dll

Не забудьте поместить в эту папку и сам скрипт с программой. Теперь вы можете перенести эту папку на другую машину и запустить вашу программы командой, указанной выше. При этом никакие другие действия по установке библиотек и рантайма не нужны.

К сожалению файлы cd.dll, cdluad51.dll и iupcd.dll в данной версии Lua for Windows могут работать некорректно, поэтому рекомендую взять их из архива по ссылке ниже.

Итоги
Архив с рабочей версией тут, для удобства добавлена пускалка app.bat.

Скриншоты:

В результате получили, пусть и неказистую, утилиту, имеющую такой же функционал, как и если бы она была написана на «серьезном» языке программирования. При этом простую в развертывании и суммарным весом менее 2 мб. Потребление памяти — около 7 мб. Исходный код доступен для редактирования, сам Lua интерактивно понятен, что упрощает доработку подобного софта на местах.

На мой взгляд, это отличный выбор для написания учебного софта для школ и институтов, а также для внутреннего использования на предприятиях. Так как слабые машины до сих пор в изобилии присутствуют в подобных местах по всему СНГ, то использование Luа подобным образом целесообразно, особенно в свете постепнного прихода Linux на десктопы. К тому же тенденцию потери исходников самописного софта при жуткой его же забагованности можно приравнять к национальному бедствию.

habrahabr.ru

Lua - Установка Lua

Установка lua это вопрос, который возникает достаточно часто. Что, вообще-то, достаточно удивительно, потому как установка lua на самом деле, крайне проста и понятна. Можно даже сказать, что там вообще нечего делать. Но, раз уж такие вопросы возникают, давайте немного поговорим об установке Lua.

Установка Луа. Скачиваем

Первое, что нам нужно будет сделать перед установкой, это скачать исходники луа с её официального сайта: http://www.lua.org/download.html. Для установки, естественно, нам понадобится самая последняя версия, на данный момент это lua 5.1.4. После скачивания, естественно, надо разархивировать исходники lua в отдельную папку.

Установка Луа. Компиляция.

Есть два варианта компиляции луа, которые, в принципе, ничем не отличаются ))) Первый – это компиляция из Visual Studio Command Prompt:

  1. Запускаем Visual Studio
  2. Выполняем Tools->Visual Studio Command Prompt
  3. Переходим в папку с луа, в директорию etc. Вот так: cd D:/mylibs/lua-5.1.4
  4. запускаем скрипт компиляции луа: etc/luavs.bat
  5. Мы получили нужны нам файлы lua.exe и luac.exe

Второй способ без запуска Visual Studio:

  1. В любом файл-мендеже (я лично работаю в FAR) заходим в папку где_луа/etc/
  2. Редактируем файл, первой строкой ставим: call “путь_к_вижуалстудио/VC/bin/vcvars32.bat”
  3. Добавляем вторую строку: cd .. и сохраняем файл
  4. Запускаем, получаем искомые экзешники

Установка Луа. Доступ

Что бы вы могли запускать луа откуда угодно – вам надо добавить их (путь к ним) в переменную окружения %PATH%. Думаю, Вы сами прекрасно знаете как это сделать. В любом случае, нам не нужны эти файлы, т.к. мы планируем использовать луа внтри наших программ, а не как отдельное приложение. После этого считайте, что сама установка Lua завершена, вам лишь остаётся прописать в Visual Studio пути в получившейся .lib и хидерам луа.

Установка Луа. Статическая линковка.

Меня лично выводит из себя то, что с каждый проектом, использующим луа, приходится таскать и lua.dll , поскольку без неё программы работать не будут. А что бы они работали – надо что бы луа линковалась с нашей программой статически. Делается это тоже совсем не сложно:

  1. Делаем в Visual Studio новый проект, Win32Project, назовём его “LuaLib”
  2. Тип проекта указываем “Static Library”, отключаем использование Precompiled Header, нажимаем Finish
  3. Добавляем в проект все файлы .h и .c, кроме lua.c и luac.c
  4. Что бы компилятор не выдавал нам варнингов, в настройки проекта (Protec/Propreties/Preprocessor) добавляем ;_CRT_SECURE_NO_WARNINGS (не забудьте сделать это и для релиз и для дебаг-версии!!!)
  5. В настройках линковки (Project/Properties/Librarian/General/OutputFile) указываем какие имена библиотек мы хотим. Я указал lua.lib для релиза и lua-debug.lib для дебага.
  6. Компилируем дебаг и релиз-версии. Получаем нужные нам либы
  7. Прописываем пути к ним в Visual Studio

Установка Луа. Проверка.

Проверим, всё ли работает. Создаём новый проект (я сделал консольный проект win32). Дописываем инклюды луа:

extern "C" { # include "lua.h" # include "lauxlib.h" # include "lualib.h" } #include <conio.h> // надо для _getch()

и доделываем сам main():

int _tmain(int argc, _TCHAR* argv[]) { lua_State *L;   L = lua_open();//Создаем стэк   luaL_openlibs(L);//подключить стандартные библиотеки   int status = luaL_loadfile(L, "test.lua");//загрузить файл /* Состояние стtка: [-1]main <--top of the stack */ if (status) { (void)fprintf(stderr, "file not found\n"); return 1; } int result = lua_pcall(L, 0, LUA_MULTRET, 0); _getch(); return 0; }

В настройки линковщика (Project/Properties/Linker/Input/Addition Dependencies) не забываем добавить нашу библиотеку (lua.lib для релиза и lua-debug.lib для дебага). Компилируем. Создаём тестовый файлик с луа-скриптом:

for i = 1, 10 do print(i) end

Запускаем и видим то, что и хотели. Теперь мы можем использовать Луа в наших программах и не таскать с собой этот ненавистный lua.dll – мне кажется, что это намного удобнее и приятнее )

На этом наш урок завершён. Теперь у вас есть собранные версии дебаг- и релиз- версий луа, собранные для статической компиляции и вы можете без каких-либо проблем использовать их в ваших проектах.

В следующих уроках мы более подробно поговорим про использование луа-скриптов в программах и, в частности, в играх.

Ещё по этой теме:

dev.mindillusion.ru

Lua Binaries

Overview

LuaBinaries is a distribution of the Lua libraries and executables compiled for several platforms.

This distribution offers a standard set of Lua libraries for the available platforms that can be used in any project that wants to be compatible with Tecgraf/PUC-Rio products and Kepler Project components.

LuaBinaries is free software and uses the same license as Lua 5.

Motivation

Since Lua offers no standard set of libraries, many projects and teams have to build their own version of the Lua libraries and this can create binary incompatibilities among the resulting products.

Tecgraf/PUC-Rio and Kepler Project teams have a lot of shared products, so it made no sense to keep maintaining two (incompatible) sets of Lua libraries in parallel. While it would be nice to have a single standard for the whole Lua community, that is still not the reality. So both teams merged their requirements and now use a common set of files. Those files are called LuaBinaries and are available here for other Lua developers that want to use them.

Using a common set of libraries has some advantages for the developer:

  • Easier interoperability with other products based on LuaBinaries
  • Faster setup time for new Lua developers

If you need to recompile from sources and would like to ensure LuaBinaries compatibility, use the source package available at the LuaBinaries Download with no modifications. In fact the only change from the Lua.org package is the name of library and executable that use "luaXX" instead of "lua", where XX is the version number.

Installation

The LuaBinaries files are intended for advanced users and programmers who want to incorporate Lua in their applications or distributions and would like to keep compatibility with LuaBinaries, so they also will be compatible with many other modules available on the Internet. Get it from SourceForge or from the dedicated servers it is hosted in.

If what you want is a full Lua installation, please check other projects such as the Lua for Windows, LuaDist or LuaRocks.

History

    [26/Jun/2017] [13/Jun/2016] [14/Dec/2015] [19/May/2015] [24/Apr/2015] [05/May/2014] [31/Mar/2014] [26/Jun/2012] [08/Jan/2012] [20/Dec/2011]
    • Lua 5.2 - Release 1The suffix is now "52" for all binaries. In Windows the executables are now built using MingW, and depends on MSVCRT.DLL.
    [15/Jan/2010] [25/Mar/2009]
    • Lua 5.1.4 - Release 2 (sources and Visual C++ 8/9 binaries only)Fixed a problem in the manifest files used by dll8 and dll9 packages that prevents the wlua executable to work on a Windows XP 64bits.
    [25/Nov/2008]
    • Lua 5.1.4 - Release 1 (sources updated)The source packages now include the Tecmake compact version, so Tecmake does not need to be installed to build the binaries the same way we do.
    [29/Aug/2008]
    • Lua 5.1.4 - Release 1Added manifests for the DLLs in dll8 and dll9 distributions to include the dependency on the run time library. Added manifests for the wlua executables to include the dependency on the ComCtl32 library that enable the Windows XP Visual Styles for GUI applications. Originals Lua makefiles are not changed anymore. LUA_CPATH default changed to also include the "clibs" subfolder in search path when in Windows. Added support for "51" suffix.
    [01/Feb/2008]
    • Lua 5.1.3 - Release 1Removed Premake generated makefiles and renamed standard Makefiles from Makefile.std to Makefile. Updated Lua icon with more size and bpp combinations. Added Windows executable that is not a console application (wlua). Executables in Windows now uses VC8 (VS2005) run time library (MSVCR80.DLL).
    [09/Apr/2007]
    • Lua 5.1.2 - Release 1Added a dll proxy called "lua51.dll" in the dll packages. It can be used to replace other "lua51.dll" previously released. It will simply forward calls to the "lua5.1.dll". There is no compiled source code involved in the forwarding.
    [14/Mar/2007]
    • Lua 5.1.1 - "luac5.1.exe" updated in the current zip to fix a problem with the "-l" parameter.
    [10/Nov/2006]
    • Lua 5.1.1 - Release 1
    • Lua 5.0.3 - Release 1 "luac5*.exe" and "lua5*.exe" in Windows now contain support for command line globing (so you can use "lua5.1 *.lua"). Each binary package has less sub-directories. Packages for Windows are in "zip" format. The source code package includes makefiles to build the same binaries as LuaBinaries. Also has IDE projects for Visual C++ 6, 7 and 8.
    [04/Mar/2006]
    • Lua 5.1 - Release 1 File names now use the suffix "5.1" instead of "51".
    [29/Nov/2005]
    • Lua 5.1 - Beta 1 Based on Lua 5.1 beta released on 18/Nov/2005.
    [16/May/2005]
    • Lua 5.0.2 - Release 2There are some important changes: Library names now use the suffix "50". The two libraries now became only one library. Windows executables now use the DLL. LuaBinaries Release 1 and Release 2 for Lua 5.0.2 are incompatible.
    [29/Mar/2005]

Credits

The binaries are built and maintained by Antonio Scuri from Tecgraf. The project was designed by André Carregal and Antonio Scuri with contributions from Danilo Tuler and Diego Nehab. We also receive valuable collaborations from Mike Pall, David Burgess, Fabio Mascarenhas and Tomas Guisasola.

Contact us

For more information please contact us. Comments are welcome!

luabinaries.sourceforge.net

Lua Binaries Manual

Using LuaBinaries

LuaBinaries can be used in a variety of ways, depending on your needs. You can use the standalone interpreter to run Lua scripts and load external modules, you can use LuaBinaries to embed Lua in your application or to dynamically load Lua/C modules into your application.

Final User - Using the Standalone Interpreter

The executable packages available for download include the standalone Lua interpreter that can load modules using require or directly load dynamic libraries using the Lua function loadlib.

In Windows, the loaded modules and libraries must follow the LuaBinaries for Windows Compatibility documentation. Also there are two Lua executables, one that is console based (lua52.exe) and one that is a Windows application with no console output (wlua52.exe). To use wlua interactively you must load a GUI module to create and manage windows and dialogs.

The Lua for Windows distribution already includes many useful modules following this specification and includes the LuaBinaries executables and DLLs (also includes and stub libraries for developers).

The Lua Rocks system deploys modules that follow this specification in Windows and UNIX.

Application Developer - Embedding Lua in your Application

Usually you will follow the same parameters we use to build the standalone interpreter. See the Configuration documentation.

In Windows, you should use the dynamic libraries or you will not be able to dynamically load modules. And to ensure that standard modules can be successfully loaded, the applications must also follow the LuaBinaries for Windows Compatibility documentation.

In UNIX, you can use the dynamic or the static libraries. But when using the static libraries remember to include the parameter "-Wl,-E" in Linux to make the application exports the Lua functions, so the loaded modules are not dependent on the LuaBinaries dynamic libraries.

Module Developer - Using Lua as an External Module of an Existing Application

External modules or components are implemented using dynamic libraries. Considering that you are going to build modules compatible with the above applications then there are a few rules to follow.

In UNIX, you should not add a dependency link with the LuaBinaries dynamic libraries, leave that to the executable that will be exporting the Lua functions. The parameter -fPIC can be used or not. The compatibility of the module dynamic library binary depends on the version C run time library used, usually glibc.

In Windows, you must follow the LuaBinaries for Windows Compatibility documentation.

You should also consult the Building Modules page written by Mike Pall about how to build C extension modules for Lua.

LuaBinaries for Windows Compatibility

In Windows your library or application must be linked with a stub library. A stub library is a library with only the function declarations that will bind your DLL with the Lua DLL. The LuaBinaries DLL is called "lua52.dll".

The C Run Time Library

In Windows, as in UNIX, the modules depend on the C run time library. But in UNIX, for the same system version/release, the libc is usually the same and modules build for that system are compatible and do not have to worry about variations in the run time library. In other words, libc changes usually occur in different versions/releases of the system. That's why there are many different binaries for the same UNIX flavor in the LuaBinaries downloads.

In Windows, there are less variations of the system but each compiler has its own version of the C run time library, each one with different names. That's why also LuaBinaries downloads have many different binaries packages for Windows.

The LuaBinaries executables for Windows are distributed as a single package so they must use only one run time library.

Notice that this affects only the users who want to build compatible modules, or use compatible modules made by others. The DLLs for all the run time libraries we support will remain available for download and use.

For Lua 5.2 and Lua 5.3

We choose the MingW gcc 4 compiler to build the LuaBinaries executables.

So despite the known MSVCRT.DLL problems we decided to use it. On the other hand it is already installed on the system and MingW supports it, so maybe this could make things easier for our users and including Lua for Windows users.

The Visual C++ 8 MSVCR80.DLL was hard to be used because of two factors: its installation and the need of a manifest file to build the user modules.

For Lua 5.1

We choose the Visual C++ 8 compiler to build the LuaBinaries executables.

Up to Visual C++ version 6, the C run time library was called "msvcrt.dll" and this DLL is today included in all modern Windows systems (W2K, WinXP, Vista and 7). But for Visual C++ 8, Microsoft released a free version of the compiler called "Express". We consider that an important step for developers using LuaBinaries DLLs. Also It is know that "msvcrt.dll" has some problems and limitations, particularly with multi-threading. So we decided to move to Visual C++ 8 version for which the C run time library is called "msvcr80.dll".

If you want to use another compiler or another version of Visual C++ you may mix run time libraries, this is safe if you do not use structures across different run times, see the MSDN article "Potential Errors Passing CRT Objects Across DLL Boundaries".

So your module DLL or application EXE must link with the stub library made for Visual C++ 8 (Visual Studio 2005), that it is distributed in the LuaBinaries "dll8" package for 32 bits or in the "dll8_64" package for 64 bits.

The LuaBinaries DLL packages have a dll proxy called "lua51.dll". It can be used to replace other "lua51.dll" released by other distributions. It will simply forward calls to the "lua5.1.dll". There is no compiled source code involved in the forwarding.

Notice that MingW can generate DLLs with different MSVCR*.DLL dependencies. To generate an import library for MingW just run (you will need the LuaBinaries source code to obtain the "lua5.1.def" file):

dlltool -d lua5.1.def -D lua5.1.dll -l liblua5.1.a

The MSVCR80 Installation for Lua 5.1

One problem that rises when using the Visual C++ 8 C run time library is that it is not installed on the system. But you can redistribute it with your application. It can be in a folder called "Microsoft.VC80.CRT" on the same folder of the executable or it can be installed by the redistributable package provided at "Microsoft Visual C++ 2005 SP1 Redistributable Package (x86)" or "Microsoft Visual C++ 2005 Redistributable Package (x64)". To install the packages you will need administrative privileges. The Visual C++ 2005 used to compile LuaBinaries has the Service Pack 1 applied.

The LuaBinaries executables includes the folder "Microsoft.VC80.CRT" so you can use it in systems that do not have the redistributable package installed and it will not conflict with systems that have the package installed.

The Lua for Windows distribution already includes the redistributable package.

luabinaries.sourceforge.net

Lua for windows

lp.InitLuaPath() ;

require( "iuplua" ) 

img1 = iup.image

{

{1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1}, {1,1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,1,1},   {1,1,1,1,1,1,1,1,1,1,1,1,1,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2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2};

  colors =  {    "0 255 0", -- 1    "BGCOLOR", -- 2    "255 0 0", -- 3    "0 0 0"    -- 4  }}mnu = iup.menu{  iup.submenu  {    iup.menu    {      iup.item{title="IupItem 1 Checked",value="ON"},      iup.separator{},      iup.item{title="IupItem 2 Disabled",active="NO"}    }     ;title="IupSubMenu 1"  },  iup.item{title="IupItem 3"},  iup.item{title="IupItem 4"}}dlg = iup.dialog

{  iup.vbox  {    iup.hbox    {     iup.frame      {  iup.vbox        {          iup.button{title="Button Text"},          iup.button{title="",image=img1},          iup.button{title="",image=img1,impress=img2}        }        ;title="IupButton"      },      iup.frame      {               

        iup.vbox        {          iup.label{title="Label Text"},          iup.label{title="",separator="HORIZONTAL"},          iup.label{title="",image=img1}        }        ;title="IupLabel"      },      iup.frame      {               

        iup.vbox        {          iup.toggle{title="Toggle Text", value="ON"},          iup.toggle{title="",image=img1,impress=img2},          iup.frame          {iup.radio            {              iup.vbox              {               iup.toggle{title="Toggle Text"},               iup.toggle{title="Toggle Text"}              }            }            ;title="IupRadio"         }        }        ;title="IupToggle"      },      iup.frame      {                 

        iup.vbox

        {          iup.text{size="80x",value="IupText Text"},          iup.multiline{size="80x60",expand="YES",value="IupMultiline Text\nSecond Line\nThird Line"}        }        ;title="IupText/IupMultiline"

      },

      iup.frame      {                  

        iup.vbox

        {          iup.list{"Item 1 Text","Item 2 Text","Item 3 Text"; expand="YES",value="1"},          iup.list{"Item 1 Text","Item 2 Text","Item 3 Text"; dropdown="YES",expand="YES",value="2"},          iup.list{"Item 1 Text","Item 2 Text","Item 3 Text"; editbox="YES",expand="YES",value="3"}        }             ;title="IupList"      }    },    iup.canvas{bgcolor="128 255 0"}    ;gap="5",alignment="ARIGHT",margin="5x5"  }

  ;title="IupDialog Title", menu=mnu }

function dlg:close_cb()  iup.ExitLoop()  dlg:destroy()  return iup.IGNOREend 

dlg:show()iup.MainLoop()

www.loriotpro.com

Installation instructions for Windows · luarocks/luarocks Wiki · GitHub

First of all, get the latest "win32.zip" package here.

The LuaRocks package for Windows is an all-in-one package which includes everything you need to run LuaRocks, including helper binaries and a Lua interpreter. (You can use your own Lua interpreter if you already have one installed, see below.)

The package includes an installer script, INSTALL.BAT, which provides a number of options for customizing your installation. Run INSTALL /? for details.

The default settings

The default settings are suitable for installing LuaRocks globally in your system while allowing both system-wide and per-user sets of rocks. Non-priviledged accounts will be able to install their own rocks in their %APPDATA% directory, and administrator accounts can install rocks that will be available for everyone.

Making a system-wide repository

All paths described above can be overridden with flags in the INSTALL.BAT script, or entries in the configuration file.

/P dir Where to install. Default is %PROGRAMFILES%\LuaRocks\version. Because LuaRocks contains 32bit executables, this will be in the c:\program files (x86)\ path on 64bit systems.
Configuring the destinations:
/TREE dir Root of the local tree of installed rocks. Default is %PROGRAMFILES%\LuaRocks\systree. On 64bit systems this default depends on the Lua interpreter used. A 64bit interpreter will have the c:\program files\ path, where a 32bit interpreter on a 64bit system will follow the c:\program files (x86)\ path.
/SCRIPTS dir Where to install commandline scripts installed by rocks. Default is {TREE}/bin.
/CONFIG dir Location where the config file should be installed. Default is to follow /P option
/SELFCONTAINED Creates a self contained installation in a single directory given by /P. Sets the /TREE and /CONFIG options to the same location as /P. And does not load registry info with option /NOREG. The only option NOT self contained is the user rock tree, so don't use that if you create a self contained installation.
Configuring the Lua interpreter:
/LV version Lua version to use; either 5.1, 5.2 or 5.3. Default is auto-detected.
/LUA dir Location where Lua is installed - e.g. c:\lua\5.1\. If not provided, the installer will search the system path and some default locations for a valid Lua installation. This is the base directory, the installer will look for subdirectories bin, lib, include. Alternatively these can be specified explicitly using the /INC, /LIB, and /BIN options.
/INC dir Location of Lua includes - e.g. c:\lua\5.1\include. If provided overrides sub directory found using /LUA.
/LIB dir Location of Lua libraries (.dll/.lib) - e.g. c:\lua\5.1\lib. If provided overrides sub directory found using /LUA.
/BIN dir Location of Lua executables - e.g. c:\lua\5.1\bin. If provided overrides sub directory found using /LUA.
/L Install LuaRocks' own copy of Lua even if detected, this will always be a 5.1 installation. (/LUA, /INC, /LIB, /BIN cannot be used with /L) within an application.
Compiler configuration:
/MW Use mingw as build system instead of MSVC.
Other options:
/FORCECONFIG Use a single config location. Do not use the LUAROCKS_CONFIG variable or the user's home directory. Useful to avoid conflicts when LuaRocks is embedded
/F Force. Remove installation directory if it already exists.
/NOREG Do not load registry info to register '.rockspec' extension with LuaRocks commands (right-click).
/NOADMIN The installer requires admin priviledges. If not available it will elevate a new process. Use this switch to prevent elevation, but make sure the destination paths are all accessible for the current user.
/Q Do not prompt for confirmation of settings

After installation, a default config file called config.lua will be installed at the directory defined by /CONFIG. For further configuration of LuaRocks paths, see the Config file format. For more information on the structure of rocks trees see rocks repositories.

Making a self-contained installation

Another option is to install LuaRocks in a self-contained manner. This is an interesting alternative when shipping an application which uses third-party modules. Bundling them as rocks reduces maintenance overhead and allows the user to perform updates.

In this scenario, it is not desired to have the user's (or the system's) configuration affect the self-contained LuaRocks install, in case the user or the system also have different LuaRocks installations. For this reason, the INSTALL.BAT script allows to hardcode the location of a configuration file. For example, the compilation process of a package bundling LuaRocks could do something like this:

SET PREFIX=C:\mypackage INSTALL /P %PREFIX% /CONFIG %PREFIX%\luarocks

The copy of LuaRocks installed in C:\mypackage will ignore customization schemes such as the %LUAROCKS_CONFIG% environment variable and will only use C:\mypackage\luarocks\config.lua.

An interesting option in those cases is for the application to provide in its configuration file an URL for their own rocks repository, so they can have control over updates to be performed. Continuing the previous example, luarocks\config.lua could contain something like this:

repositories = { "http://www.example.com/rocks/" }

Picking the Lua interpreter

LuaRocks can use its own Lua interpreter provided by the Lua for WIndows project, and will do so by default if it fails to find your Lua installation automatically. If you want to use your own interpreter, which is not on the system path, you can pass its path using the /LUA variable (or /BIN, /LIB and /INC explicitly, if you have a custom directory structure).

When looking for an interpreter, it will also try to figure out the name of the Lua binary (lua.exe, lua5.1.exe). This is set in the lua_interpreter variable in the configuration file. If you want to use an alternative name to the interpreter, you can set that variable in your configuration file directly.

An important element is the runtime libraries used by the interpreter, as LuaRocks must compile additional rocks installed with the same runtime as the interpreter. To do this LuaRocks will analyse the executable found.

Next steps

Once LuaRocks is installed, learn more about using LuaRocks.

github.com


Смотрите также