표준 라이브러리

표준 라이브러리 (The Standard Libraries)

표준 라이브러리는 루아 배포판에 포함된 내장 기능들을 제공해요. 독립 실행(standalone) 인터프리터와 luaL_openlibs로 라이브러리를 연 상태에서는 다음 표준 라이브러리들이 전역에 노출돼요.

  • 기본 함수 (Basic Functions)assert, print, type, tonumber, tostring, pcall 등. 전역 네임스페이스에 바로 노출돼요 (6.1).
  • 코루틴 조작 (Coroutine Manipulation)coroutine 테이블 (6.2).
  • 모듈 (Modules)require, package 테이블 (6.3).
  • 문자열 조작 (String Manipulation)string 테이블 (6.4).
  • UTF-8 지원 (UTF-8 Support)utf8 테이블 (6.5).
  • 테이블 조작 (Table Manipulation)table 테이블 (6.6).
  • 수학 함수 (Mathematical Functions)math 테이블 (6.7).
  • 입출력 시설 (Input and Output Facilities)io 테이블과 file 객체 (6.8).
  • 운영체제 시설 (Operating System Facilities)os 테이블 (6.9).
  • 디버그 라이브러리 (The Debug Library)debug 테이블 (6.10).

각 라이브러리는 C로 구현되어 있고, 루아 코드에서 전역 테이블(또는 전역 함수)로 접근할 수 있어요. require로 모듈을 열 때도 이들 표준 라이브러리가 사용돼요.

기본 함수 (Basic Functions)

기본 함수는 전역 네임스페이스에 직접 노출되는 함수들이에요. 자세한 내용은 "[기본 함수 (Basic Functions)]" 절을 참조해요. 여기서는 대표 몇 가지를 소개해요.

  • print(...) — 인자들을 공백으로 구분해 표준 출력에 출력.
  • type(v) — 값의 타입 이름 문자열 반환 ("nil", "number", "string", "table", "function", "thread", "userdata", "boolean").
  • tonumber(e [, base]) — 문자열/값을 숫자로 변환, 실패 시 nil.
  • tostring(v) — 값의 문자열 표현 반환.
  • assert(v [, message])v가 거짓이면 오류, 아니면 v 반환.
  • pcall(f, ...) / xpcall(f, msgh, ...) — 보호된 호출.
  • pairs(t) / ipairs(t) — 테이블 순회 반복자.
  • next(table [, index]) — 다음 키-값 쌍 반환.
  • error(message [, level]) — 오류 발생.
  • load(chunk [, chunkname [, mode [, env]]]) — 청크 컴파일.
  • dofile([filename]) — 파일의 청크 실행.
  • loadfile([filename [, mode [, env]]]) — 파일 청크 컴파일.
  • select(index, ...) — 여러 값에서 선택/개수.
  • rawget, rawset, rawequal, rawlen — 메타메서드 없는 원시 테이블 접근.
  • getmetatable(obj) / setmetatable(table, metatable) — 메타테이블 조회/설정.
  • collectgarbage([opt [, arg]]) — 가비지 컬렉터 제어.
  • warn(msg1, ...) — 경고 메시지 출력.
  • _G — 전역 테이블.
  • _VERSION — 루아 버전 문자열("Lua 5.4").

Coroutine Manipulation (코루틴 조작)

coroutine 테이블은 코루틴을 만들고 제어하는 함수를 제공해요.

  • coroutine.create(f) — 코루틴 생성.
  • coroutine.resume(co, ...) — 재개.
  • coroutine.yield(...) — 양보.
  • coroutine.status(co) — 상태 조회.
  • coroutine.running() — 현재 코루틴.
  • coroutine.wrap(f) — 코루틴을 감싼 호출 가능 함수.
  • coroutine.close(co) — 코루틴 닫기.
  • coroutine.isyieldable([co]) — 양보 가능 여부.

Modules (모듈)

require(modname)는 모듈을 로드하고, package 테이블은 모듈 로딩 경로와 상태를 관리해요. 자세한 내용은 "[모듈 (Modules)]" 절을 참조해요.

String Manipulation (문자열 조작)

string 테이블은 문자열 처리 함수를 제공해요. string.len, string.sub, string.byte, string.char, string.find, string.match, string.gmatch, string.gsub, string.format, string.rep, string.reverse, string.lower, string.upper, string.dump, string.pack, string.unpack, string.packsize 등이 대표적이에요. 패턴 매칭(patterns)도 지원해요 (6.4.1).

UTF-8 지원 (UTF-8 Support)

utf8 테이블은 UTF-8 인코딩 문자열을 다루는 함수를 제공해요. utf8.char, utf8.codes, utf8.codepoint, utf8.len, utf8.offset, utf8.charpattern 등.

Table Manipulation (테이블 조작)

table 테이블은 테이블을 다루는 함수를 제공해요. table.concat, table.insert, table.remove, table.sort, table.unpack, table.pack, table.move 등.

Mathematical Functions (수학 함수)

math 테이블은 수학 상수와 함수를 제공해요. math.abs, math.floor, math.ceil, math.sqrt, math.pow(^), math.max, math.min, math.random, math.randomseed, 삼각함수(math.sin, math.cos, math.tan 등), 로그/지수(math.log, math.exp), 그리고 상수 math.pi, math.huge, math.maxinteger, math.mininteger 등.

Input and Output Facilities (입출력 시설)

io 테이블은 입력/출력을 다루는 함수를 제공해요. io.open, io.read, io.write, io.lines, io.close, io.flush, io.input, io.output, io.popen, io.tmpfile, io.type 와 파일 객체의 메서드(file:read, file:write, file:close, file:seek, file:lines, file:flush, file:setvbuf)가 있어요.

Operating System Facilities (운영체제 시설)

os 테이블은 운영체제와 상호작용하는 함수를 제공해요. os.clock, os.date, os.difftime, os.execute, os.exit, os.getenv, os.remove, os.rename, os.setlocale, os.time, os.tmpname 등.

The Debug Library (디버그 라이브러리)

debug 테이블은 디버깅을 위한 함수와 후크(hook)를 제공해요. debug.traceback, debug.getinfo, debug.getlocal, debug.setlocal, debug.getupvalue, debug.setupvalue, debug.getmetatable, debug.setmetatable, debug.gethook, debug.sethook, debug.getregistry, debug.getuservalue, debug.setuservalue, debug.upvalueid, debug.upvaluejoin, debug.debug 등.

출처: 표준 라이브러리 (The Standard Libraries)

본문

표준 라이브러리 로딩

독립 실행 인터프리터는 기본 청크를 실행하기 전에 모든 표준 라이브러리를 로드해요. 호스트 프로그램이 luaL_openlibs(L)을 호출하면 같은 효과를 얻어요. 특정 라이브러리만 선택적으로 열려면 C API에서 각 라이브러리의 여는 함수(luaopen_base, luaopen_string, luaopen_math 등)를 직접 호출할 수 있어요.

모듈로 접근

string, table, math, io, os, coroutine, utf8, debug, package는 모두 전역 테이블이에요. 루아 코드에서는 string.format(...)처럼 테이블의 필드로 함수를 호출해요.

더 알아보기