Skip to content

Lua

Lua API Index

  • basic
  • _G
  • _VERSION
  • assert
  • collectgarbage
  • dofile
  • error
  • getmetatable
  • ipairs
  • load
  • loadfile
  • next
  • pairs
  • pcall
  • print
  • rawequal
  • rawget
  • rawlen
  • rawset
  • require
  • select
  • setmetatable
  • tonumber
  • tostring
  • type
  • xpcall
  • coroutine
  • coroutine.create
  • coroutine.isyieldable
  • coroutine.resume
  • coroutine.running
  • coroutine.status
  • coroutine.wrap
  • coroutine.yield
  • debug
  • debug.debug
  • debug.gethook
  • debug.getinfo
  • debug.getlocal
  • debug.getmetatable
  • debug.getregistry
  • debug.getupvalue
  • debug.getuservalue
  • debug.sethook
  • debug.setlocal
  • debug.setmetatable
  • debug.setupvalue
  • debug.setuservalue
  • debug.traceback
  • debug.upvalueid
  • debug.upvaluejoin
  • io
  • io.close
  • io.flush
  • io.input
  • io.lines
  • io.open
  • io.output
  • io.popen
  • io.read
  • io.stderr
  • io.stdin
  • io.stdout
  • io.tmpfile
  • io.type
  • io.write
  • file:close
  • file:flush
  • file:lines
  • file:read
  • file:seek
  • file:setvbuf
  • file:write
  • math
  • math.abs
  • math.acos
  • math.asin
  • math.atan
  • math.ceil
  • math.cos
  • math.deg
  • math.exp
  • math.floor
  • math.fmod
  • math.huge
  • math.log
  • math.max
  • math.maxinteger
  • math.min
  • math.mininteger
  • math.modf
  • math.pi
  • math.rad
  • math.random
  • math.randomseed
  • math.sin
  • math.sqrt
  • math.tan
  • math.tointeger
  • math.type
  • math.ult
  • os
  • os.clock
  • os.date
  • os.difftime
  • os.execute
  • os.exit
  • os.getenv
  • os.remove
  • os.rename
  • os.setlocale
  • os.time
  • os.tmpname
  • package
  • package.config
  • package.cpath
  • package.loaded
  • package.loadlib
  • package.path
  • package.preload
  • package.searchers
  • package.searchpath
  • string
  • string.byte
  • string.char
  • string.dump
  • string.find
  • string.format
  • string.gmatch
  • string.gsub
  • string.len
  • string.lower
  • string.match
  • string.pack
  • string.packsize
  • string.rep
  • string.reverse
  • string.sub
  • string.unpack
  • string.upper
  • table
  • table.concat
  • table.insert
  • table.move
  • table.pack
  • table.remove
  • table.sort
  • table.unpack
  • utf8
  • utf8.char
  • utf8.charpattern
  • utf8.codepoint
  • utf8.codes
  • utf8.len
  • utf8.offset

Lua C API Index

  • state manipulation
    • lua_newstate
    • lua_close
    • lua_newthread
    • lua_atpanic
  • basic stack manipulation
    • lua_gettop
    • lua_settop
    • lua_pushvalue
    • lua_remove
    • lua_insert
    • lua_replace
    • lua_checkstack
    • lua_xmove
  • access functions
    • lua_isnumber
    • lua_isstring
    • lua_iscfunction
    • lua_isuserdata
    • lua_type
    • lua_typename
    • lua_equal
    • lua_rawequal
    • lua_lessthan
    • lua_tonumber
    • lua_tointeger
    • lua_toboolean
    • lua_tolstring
    • lua_objlen
    • lua_tocfunction
    • lua_touserdata
    • lua_tothread
    • lua_topointer
  • push functions
    • lua_pushnil
    • lua_pushnumber
    • lua_pushinteger
    • lua_pushlstring
    • lua_pushstring
    • lua_pushvfstring
    • lua_pushfstring
    • lua_pushcclosure
    • lua_pushboolean
    • lua_pushlightuserdata
    • lua_pushthread
  • get functions
    • lua_gettable
    • lua_getfield
    • lua_rawget
    • lua_rawgeti
    • lua_createtable
    • lua_newuserdata
    • lua_getmetatable
    • lua_getfenv
  • set functions
    • lua_settable
    • lua_setfield
    • lua_rawset
    • lua_rawseti
    • lua_setmetatable
    • lua_setfenv
  • 'load' and 'call' functions
    • lua_call
    • lua_pcall
    • lua_cpcall
    • lua_load
    • lua_dump
  • coroutine functions
    • lua_yield
    • lua_resume
    • lua_status
  • garbage-collection function
    • lua_gc
  • miscellaneous functions
    • lua_error
    • lua_next
    • lua_concat
    • lua_getallocf
    • lua_setallocf
  • hack
    • lua_setlevel
  • Debug API
    • lua_getstack
    • lua_getinfo
    • lua_getlocal
    • lua_setlocal
    • lua_getupvalue
    • lua_setupvalue
    • lua_sethook
    • lua_gethook
    • lua_gethookmask
    • lua_gethookcount
  • From Lua 5.2
    • lua_upvalueid
    • lua_upvaluejoin
    • lua_loadx
  • Control the JIT engine.
    • luaJIT_setmode
    • LUAJIT_VERSION_SYM
  • Lua Auxiliary functions
    • luaL_openlib
    • luaL_register
    • luaL_getmetafield
    • luaL_callmeta
    • luaL_typerror
    • luaL_argerror
    • luaL_checklstring
    • luaL_optlstring
    • luaL_checknumber
    • luaL_optnumber
    • luaL_checkinteger
    • luaL_optinteger
    • luaL_checkstack
    • luaL_checktype
    • luaL_checkany
    • luaL_newmetatable
    • luaL_checkudata
    • luaL_where
    • luaL_error
    • luaL_checkoption
    • luaL_ref
    • luaL_unref
    • luaL_loadfile
    • luaL_loadbuffer
    • luaL_loadstring
    • luaL_newstate
    • luaL_gsub
    • luaL_findtable
  • From Lua 5.2.
    • luaL_fileresult
    • luaL_execresult
    • luaL_loadfilex
    • luaL_loadbufferx
    • luaL_traceback
  • compatibility only
    • luaL_buffinit
    • luaL_prepbuffer
    • luaL_addlstring
    • luaL_addstring
    • luaL_addvalue
    • luaL_pushresult
  • Lua Standard library
    • luaopen_base
    • luaopen_math
    • luaopen_string
    • luaopen_table
    • luaopen_io
    • luaopen_os
    • luaopen_package
    • luaopen_debug
    • luaopen_bit
    • luaopen_jit
    • luaopen_ffi
    • luaL_openlibs
  • more compatibility
    • lua_absindex
    • luaL_setmetatable

루아(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

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

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

print("\27[93mHello, World!\27[0m")

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

아래와 같이 사용한다.

-- main.lua
local scriptTest = require("scripts.scriptTest")
scriptTest.testFunction()
for k,v in pairs(_G) do
    print("Global key", k, "value", v)
end

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를 사용할 수 없다.

Symbol 'LUA_GLOBALSINDEX' could not be resolved

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에서는 아래와 같이 설치하면 된다.

$ sudo apt-get install libreadline6 libreadline6-dev

See also

Favorite site

Tutorials

Guide

Example

Lua GUI

References


  1. Lua_-_function_call_in_C++.pdf 

  2. Learn_Lua_in_15_Minutes_-_kor.pdf 

  3. Luarefv51.pdf 

  4. Tingcobell.tistory.com_-_LuaApi.pdf 

  5. Lua_basic_01.pdf 

  6. Lua_basic_02.pdf 

  7. Lua_short_tutorial.pdf