Lua
|
|
루아(Lua) 프로그래밍 언어는 가벼운 명령형/절차적 언어로, 확장 언어로 쓰일 수 있는 스크립팅 언어를 주 목적으로 설계되었다. 루아는 "달"을 의미하는 포르투갈어 단어이다.
Category
- Lua:Binding
- LuaJIT
- LuaRocks: Lua 패키지 관리자
- LuaDist: 루아 및 모듈(dist)을 사용하여 독립적 인 독립 실행 형 디렉토리를 만들도록 설계되었습니다. LuaDist의 모든 것은 CMake 기반이며, 이는 CMake가 지원하는 모든 컴파일러 / IDE를 사용하여 쉽게 컴파일 할 수 있음을 의미합니다. LuaDist는 또한 루아 모듈과 많은 C 의존성 / 라이브러리를 포함하는 광범위한 repository 를 가지고있어서 진정한 독립적 인 루아 "배포판"을 만들 수 있습니다.
Libraries
- luabind: C++의 함수와 클래스들을 루아에서 사용할 수 있게 하는 라이브러리.
- LuaTinker: LUA to C++ Binding Library
- luaj: Lightweight, fast, Java-centric Lua interpreter.
- tolua: 별도의 템플릿을 만들어 바인드코드를 생성해주는 솔루션.
- CPB: C++ 함수와 변수들을 루아에서 접근하기 위한 솔루션.
- LuaBridge: A lightweight, dependency-free library for binding Lua to C++
- MoonScript: A language that compiles to Lua.
- LuaRocks: package manager for Lua modules.
- Torch: A scientific computing framework for LuaJIT
- sol2
- luacheck: A tool for linting and static analysis of Lua code.
Micro frameworks
- Lapis: A web framework for Lua/MoonScript.
MVC frameworks
- Sailor: https://github.com/Etiene/sailor
- Orbit (GPL): https://github.com/keplerproject/orbit
Event-driven frameworks
Web server
- lua-http: HTTP Library for Lua. Supports HTTP(S) 1.0, 1.1 and 2.0; client and server.
CMS, Wikis
- Ophal: https://github.com/ophal
- LuaPress: https://github.com/Fizzadar/Luapress
- Sputnik: https://github.com/yuri/sputnik/
GUI
IDE
Language
Syntax
LUA의 예약어는 아래와 같다.
and break do else elseif end false for function goto if in
local nil not or repeat return then true until while
토큰 목록은 아래와 같다.
Example
Ansi Terminal Colors
Include another lua file
아래와 같은 파일이 존재한다고 가정한다.
-- scriptTest.lua (in your scripts directory)
local M = {}
local function testFunction()
print("Test function called")
end
M.testFunction = testFunction
return M
아래와 같이 사용한다.
Print all global variables
Memory module
int my_loader(lua_State* state) {
// get the module name
const char* name = lua_tostring(state);
// find if you have such module loaded
if (mymodules.find(name) != mymodules.end())
{
luaL_loadbuffer(state, buffer, size, name);
// the chunk is now at the top of the stack
return 1;
}
// didn't find anything
return 0;
}
// When you load the lua state, insert this into package.loaders
Lua path
int setLuaPath( lua_State* L, const char* path )
{
lua_getglobal( L, "package" );
lua_getfield( L, -1, "path" ); // get field "path" from table at top of stack (-1)
std::string cur_path = lua_tostring( L, -1 ); // grab path string from top of stack
cur_path.append( ";" ); // do your path magic here
cur_path.append( path );
lua_pop( L, 1 ); // get rid of the string on the stack we just pushed on line 5
lua_pushstring( L, cur_path.c_str() ); // push the new one
lua_setfield( L, -2, "path" ); // set the field "path" in table at -2 with value at top of stack
lua_pop( L, 1 ); // get rid of package table from top of stack
return 0; // all done!
}
Default module and calss
-- 'point.lua' file
local Sqrt = math.sqrt
local M={}
function M.New(x,y)
local pt = {x=x or 0, y = y or 0} -- 먼저 멤버변수를 테이블로 새로 생성
function pt:GetLength() -- 첫 번째 멤버함수를 pt안에서 생성
return Sqrt(self.x*self.x + self.y*self.y)
end
function pt:DistTo(pt2) -- 두 번째 멤버함수를 pt 안에서 생성
local dx = self.x - pt2.x
local dy = self.y - pt2.y
return Sqrt(dx*dx + dy*dy)
end
return pt -- 생성된 테이블(인스턴스)를 반환한다.
end
return M
위 파일을 사용하고싶다면:
local CPoint = require "point" -- 외부모듈을 읽어들인다.
local pt1 = CPoint.New(10,20) -- 첫 번째 인스턴스 생성
local pt2 = CPoint.New(30,40) -- 두 번째 인스턴스 생성
print("length of pt1:".. pt1:GetLength() ) -- 길이 22.36이 찍힘
print("length of pt2:".. pt2:GetLength() ) -- 길이 50이 찍힘
print("distance:".. pt1:DistTo(pt2) ) -- 두 점의 거리 28.28이 찍힌다
File IO : Implicit File Descriptors
Implicit file descriptors use the standard input/ output modes or using a single input and single output file. A sample of using implicit file descriptors is shown below.
-- Opens a file in read
file = io.open("test.lua", "r")
-- sets the default input file as test.lua
io.input(file)
-- prints the first line of the file
print(io.read())
-- closes the open file
io.close(file)
-- Opens a file in append mode
file = io.open("test.lua", "a")
-- sets the default output file as test.lua
io.output(file)
-- appends a word test to the last line of the file
io.write("-- End of the test.lua file")
-- closes the open file
io.close(file)
Troubleshooting
Undefined LUA_GLOBALSINDEX
LUA_GLOBALSINDEX
를 사용할 수 없다.
Lua 5.2 메뉴얼을 참고하면 API 변경사항은 아래와 같다.
Pseudoindex LUA_GLOBALSINDEX was removed. You must get the global environment from the registry (see §4.5).
-
LUA_REGISTRYINDEX
-
LUA_RIDX_MAINTHREAD
: At this index the registry has the main thread of the state. (The main thread is the one created together with the state.) -
LUA_RIDX_GLOBALS
: At this index the registry has the global environment.
Local Download
- LUA 5.3.2 (2015-11-25)
- Lua-5.3.2.tar.gz (md5: 33278c2ab5ee3c1a875be8d55c1ca2a1)
- 루아 5.3 참조 매뉴얼 (한글)
- https://wariua.github.io/lua-manual/5.3/manual.html
-
Lua_5.3_Reference_Manual_-_ko.pdf
Troubleshooting
readline.h: No search file or directory
readline라이브러리를 찾을 수 없는 경우가 있다.
lua.c:80:31: fatal error: readline/readline.h: No such file or directory
#include <readline/readline.h>
Ubuntu에서는 아래와 같이 설치하면 된다.
See also
- Python
- Codea
- Codea Reference: Lua 관련 API 사용법도 잘 정리함.
Favorite site
- LUA web site
- Wikipedia (en) LUA에 대한 설명
- Lua 5.3 Reference Manual
- [추천] Programming in Lua (first edition)
Tutorials
- 루아 기초
- ARM 루아
- [추천] Learn Lua in 15 Minutes
- Kor ver: 루아 15분에 배우기 2
Guide
- 안드로이드용 루아 라이브러리 빌드하기
- 루아 기초 프로그래밍 01 5
- 루아 기초 프로그래밍 02 6
- Using Lua with C++ - A short tutorial 7
- 루아 모듈의 이름 충돌 방지(3/n)
- 루아 스택 관련 함수.
- luaL_newthread() - gc를 피하는 방법~
- (Lua) 테이블 - CodeShared
Example
- World of Warcraft LUA APIs
- Gist - kizzx2/fun.cpp - Illustrative C++ Lua binding example/tutorial
- Gist - Youka/lua_myobject.cpp - Example of Lua in C++ and userdata objects
- lua-users wiki: User Data With Pointer Example
- lua-users wiki: Binding With Metatable And Closures
- lua-users wiki: Library With Userdata Example
- lua-users wiki: Peter Shook
- lua-users wiki: User Data Example
- lua-users wiki: Sample Code