728x90
반응형
안녕하세요! 오늘은 루아(Lua) 프로그래밍 언어의 기초 문법을 체계적으로 정리해보겠습니다.
루아는 간단하면서도 강력한 스크립팅 언어로, 게임 개발, 임베디드 시스템, 웹 개발 등 다양한 분야에서 활용되고 있습니다.
루아(Lua)란 무엇인가? 프로그래밍 언어 특징과 장점
루아는 1993년 브라질에서 개발된 경량 스크립팅 언어입니다. "달"을 의미하는 포르투갈어에서 이름을 따온 이 언어는, C언어로 구현되어 있으며 확장성과 이식성이 뛰어납니다.
주요 특징:
- 간결하고 배우기 쉬운 문법
- 빠른 실행 속도
- 작은 메모리 사용량
- 다른 언어와의 뛰어난 통합성
- 동적 타입 시스템
루아 설치 및 개발 환경 구축하기
루아를 시작하기 위해서는 먼저 개발 환경을 설정해야 합니다. Windows, Mac, Linux 모든 운영체제에서 쉽게 설치할 수 있습니다.
# Ubuntu/Debian
sudo apt-get install lua5.4
# Mac (Homebrew 사용)
brew install lua
# Windows (Chocolatey 사용)
choco install lua
설치 확인:
lua -v
# Lua 5.4.4 Copyright (C) 1994-2022 Lua.org, PUC-Rio
루아 기본 문법: 변수와 데이터 타입 이해하기
루아의 변수는 동적 타입을 가지며, 선언 시 타입을 명시하지 않습니다.
-- 변수 선언과 할당
local name = "루아" -- 문자열
local age = 30 -- 숫자
local isActive = true -- 불리언
-- 전역 변수 (local 키워드 없이)
globalVar = "전역 변수입니다"
-- nil 타입
local nothing = nil
루아의 기본 데이터 타입:
- nil: 값이 없음을 나타냄
- boolean: true 또는 false
- number: 정수와 실수 모두 포함
- string: 문자열
- table: 루아의 유일한 자료구조
- function: 함수
- userdata: C 데이터
- thread: 코루틴
루아 연산자와 제어문 완벽 가이드
산술 연산자
local a = 10
local b = 3
print(a + b) -- 13 (덧셈)
print(a - b) -- 7 (뺄셈)
print(a * b) -- 30 (곱셈)
print(a / b) -- 3.33... (나눗셈)
print(a % b) -- 1 (나머지)
print(a ^ b) -- 1000 (거듭제곱)
비교 연산자
local x = 5
local y = 10
print(x == y) -- false (같음)
print(x ~= y) -- true (다름)
print(x < y) -- true (작음)
print(x > y) -- false (큼)
print(x <= y) -- true (작거나 같음)
print(x >= y) -- false (크거나 같음)
조건문 (if-then-else)
local score = 85
if score >= 90 then
print("A 등급")
elseif score >= 80 then
print("B 등급")
elseif score >= 70 then
print("C 등급")
else
print("재시험 필요")
end
루아 반복문: for, while, repeat-until 사용법
for 반복문
-- 숫자 반복
for i = 1, 10 do
print(i)
end
-- 역순 반복 (step 사용)
for i = 10, 1, -1 do
print(i)
end
-- 테이블 순회
local fruits = {"사과", "바나나", "오렌지"}
for index, value in ipairs(fruits) do
print(index, value)
end
while 반복문
local count = 0
while count < 5 do
print("카운트: " .. count)
count = count + 1
end
repeat-until 반복문
local num = 0
repeat
print("숫자: " .. num)
num = num + 1
until num > 5
루아 함수 정의와 활용: 기본부터 고급까지
기본 함수 정의
-- 함수 선언
function greet(name)
return "안녕하세요, " .. name .. "님!"
end
-- 함수 호출
local message = greet("루아")
print(message) -- 안녕하세요, 루아님!
익명 함수와 함수를 인자로 전달
-- 익명 함수 할당
local multiply = function(a, b)
return a * b
end
-- 함수를 인자로 받는 함수
function applyOperation(x, y, operation)
return operation(x, y)
end
local result = applyOperation(5, 3, multiply)
print(result) -- 15
가변 인자 함수
function sum(...)
local args = {...}
local total = 0
for _, v in ipairs(args) do
total = total + v
end
return total
end
print(sum(1, 2, 3, 4, 5)) -- 15
루아 테이블: 강력한 데이터 구조 활용하기
테이블은 루아의 유일한 데이터 구조로, 배열, 해시, 객체 등 다양한 용도로 사용됩니다.
배열로 사용하기
-- 배열 생성
local colors = {"빨강", "파랑", "초록"}
-- 요소 접근 (1부터 시작)
print(colors[1]) -- 빨강
-- 요소 추가
table.insert(colors, "노랑")
-- 요소 제거
table.remove(colors, 2) -- 파랑 제거
해시 테이블로 사용하기
-- 해시 테이블 생성
local person = {
name = "김루아",
age = 25,
city = "서울"
}
-- 속성 접근
print(person.name) -- 김루아
print(person["age"]) -- 25
-- 속성 추가/수정
person.job = "개발자"
person.age = 26
중첩 테이블
local company = {
name = "루아 테크",
employees = {
{name = "김개발", position = "개발자"},
{name = "이디자인", position = "디자이너"}
}
}
-- 중첩 데이터 접근
print(company.employees[1].name) -- 김개발
루아 문자열 처리와 패턴 매칭
문자열 기본 조작
local str = "Hello, Lua Programming!"
-- 문자열 길이
print(string.len(str)) -- 또는 #str
-- 대소문자 변환
print(string.upper(str))
print(string.lower(str))
-- 부분 문자열
print(string.sub(str, 1, 5)) -- Hello
-- 문자열 연결
local combined = str .. " 재미있어요!"
패턴 매칭
-- 패턴 찾기
local text = "이메일: user@example.com"
local email = string.match(text, "[%w_]+@[%w_]+%.[%w_]+")
print(email) -- user@example.com
-- 문자열 치환
local replaced = string.gsub("Hello World", "World", "Lua")
print(replaced) -- Hello Lua
루아 모듈과 패키지 시스템 이해하기
모듈 생성하기
-- mymodule.lua
local M = {}
function M.sayHello(name)
return "안녕하세요, " .. name .. "!"
end
function M.add(a, b)
return a + b
end
return M
모듈 사용하기
-- main.lua
local mymodule = require("mymodule")
print(mymodule.sayHello("루아"))
print(mymodule.add(10, 20))
루아 에러 처리와 디버깅 기법
pcall을 이용한 에러 처리
function divide(a, b)
if b == 0 then
error("0으로 나눌 수 없습니다!")
end
return a / b
end
-- 안전한 함수 호출
local success, result = pcall(divide, 10, 0)
if success then
print("결과:", result)
else
print("에러:", result)
end
assert를 이용한 검증
function processFile(filename)
assert(filename ~= nil, "파일명이 필요합니다")
-- 파일 처리 로직
end
루아 메타테이블과 메타메서드: 고급 기능 활용
메타테이블은 루아의 강력한 기능 중 하나로, 객체의 동작을 커스터마이즈할 수 있습니다.
-- 벡터 클래스 구현
Vector = {}
Vector.__index = Vector
function Vector.new(x, y)
local self = setmetatable({}, Vector)
self.x = x or 0
self.y = y or 0
return self
end
-- 메타메서드 정의
function Vector:__add(other)
return Vector.new(self.x + other.x, self.y + other.y)
end
function Vector:__tostring()
return string.format("Vector(%d, %d)", self.x, self.y)
end
-- 사용 예시
local v1 = Vector.new(3, 4)
local v2 = Vector.new(1, 2)
local v3 = v1 + v2
print(v3) -- Vector(4, 6)
루아 코루틴: 협력적 멀티태스킹 구현
코루틴은 함수 실행을 일시 중단하고 재개할 수 있는 강력한 기능입니다.
-- 코루틴 생성
local co = coroutine.create(function()
for i = 1, 5 do
print("코루틴 실행:", i)
coroutine.yield(i)
end
end)
-- 코루틴 실행
while coroutine.status(co) ~= "dead" do
local success, value = coroutine.resume(co)
if success then
print("메인 스레드에서 받은 값:", value)
end
end
루아 실전 예제: 간단한 게임 로직 구현
-- 간단한 가위바위보 게임
function getComputerChoice()
local choices = {"가위", "바위", "보"}
return choices[math.random(1, 3)]
end
function determineWinner(player, computer)
if player == computer then
return "무승부"
elseif (player == "가위" and computer == "보") or
(player == "바위" and computer == "가위") or
(player == "보" and computer == "바위") then
return "플레이어 승리!"
else
return "컴퓨터 승리!"
end
end
-- 게임 실행
math.randomseed(os.time())
local playerChoice = "가위"
local computerChoice = getComputerChoice()
print("플레이어: " .. playerChoice)
print("컴퓨터: " .. computerChoice)
print(determineWinner(playerChoice, computerChoice))
마무리: 루아 학습 로드맵과 추천 자료
루아는 간결하면서도 강력한 언어로, 다양한 분야에서 활용할 수 있습니다.
이 글에서 다룬 기초 문법을 바탕으로 다음 단계로 나아가시길 추천드립니다:
- 게임 개발: Love2D, Corona SDK 등의 프레임워크 학습
- 임베디드 시스템: NodeMCU, OpenWrt 등에서 루아 활용
- 웹 개발: OpenResty를 이용한 웹 애플리케이션 개발
- 스크립팅: Redis, Nginx 등의 설정 및 확장
루아는 배우기 쉬우면서도 실무에서 강력한 성능을 발휘하는 언어입니다.
꾸준한 학습과 실습을 통해 루아 전문가가 되시길 바랍니다!
728x90
반응형
'프로그래밍 언어 실전 가이드' 카테고리의 다른 글
루아 테이블 완전 정복 – 연관 배열부터 메타테이블까지 (1) | 2025.05.16 |
---|---|
루아 함수와 클로저 – 함수형 프로그래밍 맛보기 (0) | 2025.05.15 |