아래 글을 아직 안읽으셨다면 튜토리얼 시작1부터 보고 오시면 됩니다.
Lua(루아) 튜토리얼 시작1(기초 - 변수, 연산자)
반복문
반복문에는 기본적으로 for while 을 많이 쓰죠.
루아에서는 repeat until도 있습니다.
다른 언어와 특이점은 배열의 시작이 0부터가 아닌 1부터라는 점입니다.
for init,max/min value, increment
do
statement(s)
end
while(condition)
do
statement(s)
end
repeat
statement(s)
until( condition )
생소한 repeat until에 대한 예제코드입니다.
코드블록을 실행하고 조건을 확인하는 방식입니다.
조건문
다음은 조건문입니다.
if 문이죠.
if(boolean_expression)
then
--[ statement(s) will execute if the boolean expression is true --]
end
if(boolean_expression)
then
--[ statement(s) will execute if the boolean expression is true --]
else
--[ statement(s) will execute if the boolean expression is false --]
end
if 이후엔 then이 필수 입니다. 그리고 마지막엔 end로 끝나지요.
else, elseif 로 추가 구성도 가능합니다.
함수
function을 만드는 방법입니다.
optional_function_scope function function_name( argument1, argument2, argument3........,
argumentn)
function_body
return result_params_comma_separated
end
--[[ function returning the max between two numbers --]]
function max(num1, num2)
if (num1 > num2) then
result = num1;
else
result = num2;
end
return result;
end
함수의 타입을 출력하면 function으로 나타납니다.
max 함수 자체를 출력하면 해당 함수의 메모리주소위치가 나타납니다.
Formatting Strings
출력을 할 때는 %s %d %f 등을 사용할 수 있습니다.
%s는 문자열을 의미하고,
%d는 정수를 의미합니다. %02d의 경우는 가운데 02가 2자리수까지 비어있으면 0으로 채우라는 의미입니다.
%f는 소수점 아래를 의미합니다. %.4f의 경우는 소수점 4자리까지만 보여주게 됩니다.
Array
루아에서 강력한 기능이라고도 볼 수 있는데, 테이블과 비슷한면이 있지요.
이중배열을 생각하면 이해가 쉬울 것 같습니다.
배열의 첫번째 값은 1부터 시작한다는 점 잊지 않으셨죠?
Table
--sample table initialization
mytable = {}
--simple table value assignment
mytable[1]= "Lua"
--removing reference
mytable = nil
-- lua garbage collection will take care of releasing memory
테이블은 다른 유형의 변수들을 그룹화한 형태도 지원을 합니다.
a = {"a", 1, 2, test="tutorial", check=false}
for k, v in pairs(a) do
print(k, v)
end
index로 앞에서부터 1 2 3으로 나올 수도 있지만, key=value 형태로 들어온 경우는 pairs 를 통해 index 없이 값을 하나씩 꺼낼 수 있습니다.
변수형태로 되어 있다면 .을 이용해 값에 접근할 수 있습니다.
'Lua' 카테고리의 다른 글
Lua 의 언어적인 장단점, 특징 (1) | 2022.03.02 |
---|---|
Lua(루아) 튜토리얼 시작1(기초 - 변수, 연산자) (0) | 2022.02.24 |
댓글