레슨 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)을 북마크해 두세요. 표준 라이브러리의 모든 함수와 동작이 상세히 문서화되어 있습니다.