빠른 참조

Lua 치트시트

Lua 종합 참조 가이드: 기본 문법, 테이블 및 배열, 루프, 메타테이블, 객체 지향 프로그래밍, 표준 라이브러리 API.

· 게시일

Lua는 애플리케이션 확장을 위해 설계된 강력하고 효율적이며 가벼운 임베디드 스크립트 언어입니다.

기본 문법

주석

-- 한 줄 주석

--[[
  여러 줄 주석
--]]

함수 호출 괄호 생략

함수가 정확히 하나의 문자열 리터럴 또는 테이블 생성자만을 인수로 받을 때 괄호를 생략할 수 있습니다:

print("Hello World")  <==>  print "Hello World"
dofile('app.lua')     <==>  dofile 'app.lua'
config({ x = 1 })     <==>  config{ x = 1 }

테이블 및 배열

테이블은 Lua의 유일한 데이터 구조화 메커니즘입니다. 배열은 **1부터 시작하는 인덱스 (1-based)**를 사용합니다:

-- 빈 테이블
local t = {}

-- 키-값 테이블 (딕셔너리)
local user = { name = "Alice", age = 30 }
user.role = "admin"
user["email"] = "[email protected]"

-- 순차적 배열 (1부터 인덱싱)
local fruits = { "apple", "banana", "cherry" }
print(fruits[1])  -- "apple" 출력
print(#fruits)    -- 길이 연산자 (3)

제어 흐름 및 루프

조건문

Lua에서는 false와 nil만이 거짓(falsy)으로 처리됩니다. 0과 ""는 **참(truthy)**입니다:

if score >= 90 then
  grade = "A"
elseif score >= 80 then
  grade = "B"
else
  grade = "C"
end

루프

-- While 루프
local count = 1
while count <= 5 do
  count = count + 1
end

-- Repeat...until 루프 (최소 한 번 실행)
repeat
  count = count - 1
until count == 0

-- 숫자 for 루프: for var = start, stop [, step]
for i = 1, 10, 2 do
  print(i) -- 1, 3, 5, 7, 9
end

-- 제네릭 for 루프: ipairs(배열) 및 pairs(딕셔너리)
for index, value in ipairs(fruits) do
  print(index, value)
end

for key, value in pairs(user) do
  print(key, value)
end

함수

함수 정의 및 다중 반환값

-- 여러 값 반환
local function min_max(a, b)
  if a < b then
    return a, b
  else
    return b, a
  end
end

local minimum, maximum = min_max(10, 5)

-- 가변 인자 (varargs)
local function sum(...)
  local s = 0
  for _, v in ipairs({...}) do
    s = s + v
  end
  return s
end

메타테이블 및 객체 지향 프로그래밍

메타테이블 및 메타메서드

local Vector = {}
Vector.__index = Vector

function Vector.new(x, y)
  local instance = setmetatable({}, Vector)
  instance.x = x
  instance.y = y
  return instance
end

-- 벡터 덧셈 메타메서드
function Vector.__add(a, b)
  return Vector.new(a.x + b.x, a.y + b.y)
end

function Vector:__tostring()
  return string.format("(%d, %d)", self.x, self.y)
end

local v1 = Vector.new(1, 2)
local v2 = Vector.new(3, 4)
local v3 = v1 + v2
print(v3) -- "(4, 6)"

메타메서드 레퍼런스

메타메서드 발생 이벤트
__index 존재하지 않는 필드 읽기 (t[k])
__newindex 존재하지 않는 필드에 대입 (t[k] = v)
__tostring 문자열 변환 (tostring(t))
__call 테이블을 함수처럼 호출 (t())
__add, __sub 덧셈 (+), 뺄셈 (-)
__mul, __div 곱셈 (*), 나눗셈 (/)
__eq, __lt, __le 비교 (==, <, <=)
__concat 문자열 연결 (..)

표준 라이브러리 API

문자열 함수

string.len("hello")             -- 5 (#"hello" also works)
string.lower("HELLO")           -- "hello"
string.upper("hello")           -- "HELLO"
string.sub("hello", 2, 4)       -- "ell"
string.format("%s = %d", "x", 5)-- "x = 5"
string.gsub("banana", "a", "o") -- "bonono"
string.find("hello world", "wor") -- 7, 9

테이블 함수

table.insert(fruits, "orange")     -- 끝에 추가
table.insert(fruits, 1, "grape")   -- 인덱스 1에 삽입
table.remove(fruits, 1)            -- 첫 번째 요소 제거
table.concat(fruits, ", ")         -- 문자열 결합: "apple, banana"
table.sort(fruits)                 -- 배열 내부 정렬

수학 함수

math.abs(-10)         -- 10
math.floor(3.7)       -- 3
math.ceil(3.2)        -- 4
math.max(1, 9, 4)     -- 9
math.random(1, 100)   -- 1과 100 사이의 무작위 정수

참고 자료

관련 주제