LUA Tutorial
[edit]
이 문서의 목적 #
이 문서는 Lua 프로그래밍 언어에 대한 안내를 목적으로 한다. 이것은 언어 레퍼런스보다 예제를 통해서 배우는 것이 더 빠르다고 생각하는 이들을 위한 것이다.
[edit]
Lua? #
Lua는 호스트 어플리케이션에 내장될 목적으로 작성된 스크립트 언어이다. Lua의 공식적인 웹사이트는
http://www.lua.org이다. 확실한 Lua의 잇점은 단순성과 크기이다.
[edit]
예제를 실행하기 #
Lua의 설치에 따라, 여러분은 예제를 실행할 수도, 못할 수도 있다. 앞에서 언급했듯이, Lua의 주된 제작목적은 호스트 어플리케이션에 내장되는 것이다. 어쨌거나 예제를 돌려보기 위해서 "lua"라고 불리는 독립 어플리케이션을 컴파일하자. "lua.exe"는 커맨드 라인에 정의된 화일을 읽거나 (가능하다면) stdin에서 데이타를 얻어서 Lua 코드들을 실행해준다.
[edit]
Hello, world #
모든 언어들의 서두가 그렇듯이 여기서도 "Hello, world!"로 시작해보자.
-- Hello, world!
print("Hello, world!")
Hello, world!
"--"은 그 줄끝까지는 주석문이라는 것을 나타낸다.
[edit]
Lua 타입 #
Lua는 6개의 기본 타입이 있다 : nil, number, string, function, userdata, table. 주어진 변수의 타입을 알아내려면 다음 예제를 참조해라:
-- 타입을 알아내기 위해 테그를 사용한다.
function a_function()
-- 이것은 단지 텅빈 함수이다.
end
print(tag(undefined))
print(tag(1))
print(tag("Hello, world"))
print(tag({1,2,3}))
print(tag(a_function))
1
2
3
4
5
선택적으로, "type"키워드가 사용될 수 있다:
-- 타입명을 출력한다.
function a_function()
-- 단지 텅빈 함수
end
print (type(undefined))
print (type(1))
print (type("Hello, there!"))
print (type({1,2,3}))
print (type(a_function))
nil
number
string
table
function
[edit]
테이블 #
Lua는 "테이블"이라는 데이타타입으로 확장된 용도를 제공한다. 테이블은 다음과 같이 정의된다:
-- 테이블을 정의하기
table = {1, 2, 3, 4} -- 4개의 요소를 가진 테이블
-- 이것을 출력해보자
i = 1 -- 테이블은 1부터 센다. 0이 아니다.
-- index내에 값이 들어있으면 table[index]는 true이다. while table[i] do
print (table[i])
i = i + 1
end
1
2
3
4
Lua 의 테이블은 숫자(number)가 아닌 다른타입으로도 인덱스화될 수 있다. table.name 과 table[ "name" ]은 동등하다는것에 주목하라. 또한 table.number 같은 표현은 불가능하다는것에도 유의하라.
-- Table example
function stupid_function()
print "I do nothing! Nothing!"
end
table = {}
table.name = "Just a table"
table["passcode"] = "Agent 007"
table[table] = "Penguin"
table[stupid_function] = "This is a stupid function"
table["do_stuff"] = stupid_function
print ( table["name"], table.passcode, table[table] )
print ( table[table["do_stuff"]] )
table["do_stuff"]()
table.do_stuff() -- 이 두 문장은 같은 의미이다.
Just a table Agent 007 Penguin
This is a stupid function
I do nothing! Nothing!
I do nothing! Nothing!
[edit]
Lua의 흐름제어 #
Lua는 조건 분기를 위해 "if" 라는 키워드를 사용한다.
-- If example
variable = "This is a string"
variable_2 = 10
if 0 then -- Note: Zero IS true(!)
print ("Zero is true")
else
print ("Zero is false")
end
if type(variable) == "string" then
print (variable, "is a string")
else
print (variable, "is not a string")
end
if type(variable_2) == "string" then
print (variable_2, "is a string")
elseif pigs_can_fly then
print ("Pigs really CAN fly.")
else
print (variable_2, "is not a string")
end
Zero is true
This is a string is a string
10 is not a string
Lua는 주어진 조건식이 거짓으로 평가될 때 까지 반복하거나, 주어진 수치의 범위만큼 반복할 수 있는 일반적인 제어구조를 가지고 있다:
-- Small examples of Lua loops
-- Something to iterate
list = {"One", "Two", "Three", "Four", "Five", "Six"}
-- For-loops
print ("Counting from one to three:")
for element = 1, 3 do
print (element, list[element])
end
print ("Counting from one to four,")
print ("in steps of two:")
for element = 1, 4, 2 do
print (element, list[element])
end
-- While-loops
print ("Count elements in list")
print ("on numeric index")
element = 1
while list[element] do
print (element, list[element])
element = element + 1
end
-- Repeat-loop
print ("Count elements in list")
print ("using repeat")
element = 1
repeat
print (element, list[element])
element = element + 1
until not list[element]
Counting from one to three:
1 One
2 Two
3 Three
Counting from one to four
in steps of two:
1 One
3 Three
Counting elements in list
on numeric index
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
Counting elements in list
using repeat
1 One
2 Two
3 Three
4 Four
5 Five
6 Six
[edit]
함수 #
Lua는 사용자가 함수를 정의할 수 있도록 한다. 함수는 정해진 갯수의 파라미터를 받을 수 있다:
-- 함수를 정의하고 그것을 호출해보자
function add_two (parameter1, parameter2)
return parameter1 + parameter2
end
print ( add_two(3, 4) )
7
Lua는 또한 가변적인 갯수의 파라미터를 전달 할 수도 있다. 다음 예제를 참고하라:
-- 가변인수를 받는 함수
function table_parameters(a, b, ...)
print ("a is:", a, " b is:", b)
local i
i = 1
while arg[i] do
print ("More arguments:", arg[i])
i = i + 1
end
end
table_parameters("Hello", "there", 1, 2, "Hey")
a is: Hello b is: there
More arguments: 1
More arguments: 2
More arguments: Hey
가변인수 지시자(varargs-indicator) (...) 을 사용해 전달된 이름없는 파라미터들은 "arg" 라는 테이블을 통해 지역적으로 엑세스 될 수 있다.
[edit]
변수와 변수의 통용범위(scope) #
Lua는 함수 안에서 전역 변수를 엑세스할 수 있다:
-- 변수와 범위(scope) 를 테스트하는 예제
function access_global()
i = i + 1
end
function create_a()
a = 2
end
i = 0
print (i)
access_global()
print (i)
create_a()
print (a)
0
1
2
다음 예제에서 "local" 키워드를 사용한것과 비교해 보라:
-- 변수와 범위(scope) 를 테스트하는 예제
function access_global()
local i
i = 0 -- i 는 현재 정의되지 않았다 (nil)
i = i + 1
end
function create_a()
local a
a = 2
end
i = 0
print (i)
access_global()
print (i)
create_a()
print (a) -- 이것은 nil 을 출력할것이다.
-- 전역범위에서 a가 정의되지 않았기 때문이다.
0
0
nil
[edit]
"객체 지향" 프로그래밍 #
Lua는 객체지향 비스무리한 무언가를 할 능력이 있다. 이 예제는 상속을 포함하지 않는다. 기본적으로, 이예제의 함수는 테이블과 그것에 연관된 메서드(method)들을 생성한다. 그리고 그것을 위한 두가지 다른 표기법을 보여준다. 또한 인스턴스와 연관된 데이터를 어떻게 엑세스 하는지도 보여준다. 메서드를 호출할때 . 을 사용하는 대신에 : 을 사용하면 자동적으로 테이블의 인스턴스가 메서드의 첫번째 인자로 전달된다.
-- 객체지향 프로그래밍 테스트
function car(brand)
-- 이 함수는 생성자(constructor)처럼 동작한다.
local data
data = {}
-- 브랜드가 없으면 기본 브랜드를 골라주자.
if brand == nil then
data.Brand = "Volvo"
else
data.Brand = brand
end
data.report = function(self)
print ("I'm a", self.Brand)
end
-- 콜론( : ) 을 써서 표기하면 자동적으로 "self" 파라미터를 추가해 준다.
function data:say_something_smart()
print ("I'm STILL a", self.Brand, "! Wroom!")
end
return data
end
my_car = car()
my_other_car = car("Ferrari")
print (my_car.Brand)
print (my_other_car.Brand)
my_car:report() -- 메서드를 호출할때 . 대신 : 을 사용한다.
my_other_car:report()
my_car:say_something_smart()
my_other_car:say_something_smart()
Volvo
Ferrari
I'm a Volvo
I'm a Ferrari
I'm STILL a Volvo ! Wroom!
I'm STILL a Ferrari ! Wroom!
원본 위치 <http://www.redwiki.net/wiki/wiki.php/LUA%20Tutorial>