Skip to content
Search

Lua

lastmod 2025-09-25created 2014-08-1572 edits

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

The Lua programming language is a lightweight imperative/procedural language, designed primarily as a scripting language that can be used as an extension language. Lua is the Portuguese word for "moon".

Category

  • Lua:Binding
  • LuaJIT
  • LuaRocks: Lua package manager
  • LuaDist: Designed to create self-contained, standalone directories using Lua and modules (dist). Everything in LuaDist is CMake-based, which means it can be easily compiled with any compiler / IDE supported by CMake. LuaDist also has an extensive repository containing Lua modules and many C dependencies / libraries, so you can create a truly self-contained Lua "distribution".

Libraries

  • luabind: A library that makes C++ functions and classes usable from Lua.
  • LuaTinker: LUA to C++ Binding Library
  • luaj: Lightweight, fast, Java-centric Lua interpreter.
  • tolua: A solution that generates binding code by creating a separate template.
  • CPB: A solution for accessing C++ functions and variables from Lua.
  • 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

The reserved words of LUA are as follows.

and       break     do        else      elseif    end    false     for       function  goto      if        in
local     nil       not       or        repeat    return    then      true      until     while

The list of tokens is as follows.

+     -     *     /     %     ^     #    &     ~     |     <<    >>    //
==    ~=    <=    >=    <     >     =    (     )     {     }     [     ]     ::    ;     :     ,     .     ..    ...

Example

Ansi Terminal Colors

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

Include another lua file

Assume the following file exists.

-- scriptTest.lua (in your scripts directory)
local M = {}

local function testFunction()
      print("Test function called")
end
M.testFunction = testFunction

return M

Use it as follows.

-- 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

If you want to use the file above:

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 cannot be used.

Symbol 'LUA_GLOBALSINDEX' could not be resolved

According to the Lua 5.2 manual, the API change is as follows.

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)
Lua 5.3 Reference Manual (Korean)
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

Sometimes the readline library cannot be found.

lua.c:80:31: fatal error: readline/readline.h: No such file or directory
 #include <readline/readline.h>

On Ubuntu, install it as follows.

$ 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 ↩

author Zer0 sitemap