Learning
레슨 8 / 8·5개 토픽

Lua 레퍼런스

Lua 주요 API 레퍼런스

Lua 5.4 표준 라이브러리의 주요 함수들을 분류별로 정리합니다. 학습과 개발 중 빠르게 참조할 수 있는 치트시트입니다.

문자열 함수 (string)

함수설명예시
string.len(s)문자열 길이string.len("abc") → 3
string.sub(s, i, j)부분 문자열string.sub("hello", 2, 4) → "ell"
string.upper(s)대문자 변환string.upper("abc") → "ABC"
string.lower(s)소문자 변환string.lower("ABC") → "abc"
string.rep(s, n)n번 반복string.rep("ab", 3) → "ababab"
string.reverse(s)뒤집기string.reverse("abc") → "cba"
string.find(s, p)패턴 검색string.find("hello", "ll") → 3, 4
string.match(s, p)패턴 매칭string.match("2024-01", "%d+") → "2024"
string.gmatch(s, p)반복 매칭for w in s:gmatch("%w+") do ... end
string.gsub(s, p, r)패턴 치환string.gsub("abc", "b", "B") → "aBc"
string.format(f, ...)포맷팅string.format("%d + %d = %d", 1, 2, 3)
string.byte(s, i)바이트 값string.byte("A") → 65
string.char(n, ...)바이트→문자string.char(65) → "A"

테이블 함수 (table)

함수설명예시
table.insert(t, v)끝에 삽입table.insert(t, "x")
table.insert(t, i, v)i 위치에 삽입table.insert(t, 2, "x")
table.remove(t, i)i 위치 제거table.remove(t, 1)
table.sort(t, fn)정렬table.sort(t, function(a,b) return a > b end)
table.concat(t, sep)문자열 결합table.concat({"a","b","c"}, ", ") → "a, b, c"
table.move(t, f, e, d)요소 이동table.move(t, 1, 3, 2)
table.unpack(t)테이블→여러 값local a, b = table.unpack({1, 2})

수학 함수 (math)

함수설명예시
math.abs(x)절대값math.abs(-5) → 5
math.ceil(x)올림math.ceil(3.2) → 4
math.floor(x)내림math.floor(3.8) → 3
math.max(x, ...)최대값math.max(1, 5, 3) → 5
math.min(x, ...)최소값math.min(1, 5, 3) → 1
math.random(m, n)난수math.random(1, 100)
math.sqrt(x)제곱근math.sqrt(16) → 4.0
math.pi원주율3.1415926535898
math.huge양의 무한대if x < math.huge then ...

자주 쓰는 패턴과 관용구

lua
-- 기본값 패턴 (or)
local function greet(name)
    name = name or "손님"
    print("안녕, " .. name)
end

-- 삼항 연산자 패턴 (and/or)
local x = 10
local label = (x > 0) and "양수" or "음수/영"

-- 안전한 테이블 접근
local config = { db = { host = "localhost" } }
local host = config and config.db and config.db.host or "default"

-- 테이블 복사 (얕은 복사)
local function shallow_copy(t)
    local copy = {}
    for k, v in pairs(t) do copy[k] = v end
    return copy
end

-- 테이블에 값 존재 여부 확인
local function contains(t, value)
    for _, v in ipairs(t) do
        if v == value then return true end
    end
    return false
end

-- 문자열 분리 (split)
local function split(str, sep)
    local result = {}
    for part in string.gmatch(str, "([^" .. sep .. "]+)") do
        table.insert(result, part)
    end
    return result
end

local parts = split("a,b,c", ",")  -- {"a", "b", "c"}

-- 메서드 체이닝
local Builder = {}
Builder.__index = Builder

function Builder.new()
    return setmetatable({ parts = {} }, Builder)
end

function Builder:add(part)
    table.insert(self.parts, part)
    return self  -- 체이닝용 self 반환
end

function Builder:build()
    return table.concat(self.parts, " ")
end

local result = Builder.new():add("Hello"):add("Lua"):build()
print(result)  -- "Hello Lua"
  • x or default — 기본값 패턴 (x가 nil/false면 default)
  • cond and a or b — 삼항 연산자 (a가 false/nil이면 안 됨)
  • pairs(t) — 모든 키-값 순회, ipairs(t) — 배열 순회
  • #t — 배열 길이, select("#", ...) — 가변 인자 개수
  • type(x) — 타입 확인 ("string", "number", "table" 등)
  • tostring(x), tonumber(s) — 타입 변환
  • setmetatable(t, mt) — 메타테이블 설정으로 OOP 구현
💡

Lua 공식 레퍼런스 매뉴얼(lua.org/manual/5.4)을 북마크해 두세요. 표준 라이브러리의 모든 함수와 동작이 상세히 문서화되어 있습니다.