수색…


비고

루아 로고

루아 는 최소한의 가볍고 삽입 가능한 스크립팅 언어입니다. 브라질 리오 데 자네이로의 Pontifical Catholic University PUC-Rio 이 설계, 구현 및 유지 관리하고 있습니다. 메일 링리스트 는 열려 있습니다.

Lua의 일반적인 사용 사례에는 비디오 게임 스크립팅, 플러그인 및 구성으로 애플리케이션 확장, 고급 비즈니스 로직의 래핑 또는 TV, 자동차 등의 장치에 포함 만 포함됩니다.

고성능 작업을 위해 LuaJIT 라고하는 Just-In-Time 컴파일러를 사용할 수있는 독립적 인 구현이 있습니다.

버전

번역 노트 출시일
1.0 초기 공개. 1993-07-28
1.1 첫 공개. 그것을 설명하는 회의 논문 . 1994-07-08
2.1 루아 2.1부터 루아는 상업적 용도를 포함한 모든 목적으로 자유롭게 사용할 수있게되었습니다. 그것을 설명하는 저널 용지 . 1995-02-07
2.2 긴 문자열, 디버그 인터페이스, 더 나은 스택 추적 1995-11-28
2.4 외부 luac 컴파일러 1996-05-14
2.5 패턴 일치 및 가변 기능 1996-11-19
3.0 루아 라이브러리 작성을 돕기위한 라이브러리 인 auxlib가 도입되었습니다. 1997-07-01
3.1 익명 함수 및 "upvalues"를 통한 함수 클로저. 1998-07-11
3.2 라이브러리 및 새 테이블 함수 디버그 1999-07-08
3.2.2 2000-02-22
4.0 여러 상태, "for"문, API 개편. 2000-11-06
4.0.1 2002-07-04
5.0 코 루틴, 메타 테이블, 완전한 어휘 스코핑, 꼬리 호출, 부울은 MIT 라이센스로 이동합니다. 2003-04-11
5.0.3 2006-06-26
5.1 모듈 시스템 개정, 증분 가비지 컬렉터, 모든 유형의 메타 테이블, luaconf.h 개정, 완전히 재진입 파서, 가변 인수 2006-02-21
5.1.5 2012-02-17
5.2 긴급 가비지 컬렉터, goto, 테이블 파이널 라이저. 2011-12-16
5.2.4 2015-03-07
5.3 기본 UTF-8 지원, bitwise ops, 32 / 64bit 정수. 2015-01-12
5.3.4 최신 버전. 2017-01-12

설치

바이너리

루아 바이너리는 대부분의 GNU / 리눅스 배포본에 패키지로 제공됩니다.

예를 들어 데비안, 우분투 및 그 유도체에서 다음을 실행하여 얻을 수 있습니다.

sudo apt-get install lua50
sudo apt-get install lua51
sudo apt-get install lua52

Windows, MacOS 및 SourceForge 에서 호스팅되는 다른 운영 체제 용으로 제공되는 일부 공식 빌드가 있습니다.

Apple 사용자는 Homebrew를 사용하여 쉽게 Lua를 설치할 수 있습니다.

brew install lua

(현재 Homebrew는 5.2.4, 5.3은 Homebrew / 버전 참조).

출처

출처는 공식 페이지 에서 볼 수 있습니다. 소스를 획득하고 자체를 구축하는 것은 사소한 일입니다. Linux 시스템에서는 다음 사항만으로 충분합니다.

$ wget http://lua.org/ftp/lua-5.3.3.tar.gz
$ echo "a0341bc3d1415b814cc738b2ec01ae56045d64ef ./lua-5.3.3.tar.gz" | sha1sum -c -
$ tar -xvf ./lua-5.3.3.tar.gz
$ make -C ./lua-5.3.3/ linux

위 예제에서 우리는 기본적으로 공식 사이트에서 소스 tarball 을 다운로드하고, 체크섬을 확인하고, make 추출하고 실행 make . 공식 페이지 에서 체크섬을 두 번 확인 하십시오 .

주 : 원하는 빌드 대상을 지정해야합니다. 이 예제에서는 linux 를 지정했습니다. 사용 가능한 다른 빌드 타겟으로는 solaris , aix , bsd , freebsd , macosx , mingw 등이 있습니다. 자세한 내용은 소스에 포함 된 doc/readme.html 확인하십시오. ( 온라인 README의 최신 버전을 찾을 수도 있습니다 .)

모듈

표준 라이브러리는 프리미티브로 제한됩니다.

  • coroutine - 코 루틴 관리 기능
  • debug - 디버깅 후크 및 도구
  • io - 기본 IO 프리미티브
  • package - 모듈 관리 기능
  • string - 문자열과 루아 특정 패턴 일치 기능
  • table - 필수적이지만 복잡한 루아 타입을 다루기위한 프리미티브들 - 테이블들
  • os - 기본 OS 운영
  • utf8 - 기본 UTF-8 프리미티브 (루아 5.3 이후)

모든 라이브러리는 특정 빌드에 대해 비활성화되거나 런타임에로드 될 수 있습니다.

모듈 배포를위한 써드 파티 루아 라이브러리와 인프라는 드물지만 개선되고 있습니다. LuaRocks , Lua ToolboxLuaDist 와 같은 프로젝트가 상황을 개선하고 있습니다. 많은 정보와 많은 제안이 오래된 Lua Wiki 에서 발견 될 수 있지만,이 정보 중 일부는 꽤 오래되고 시대에 뒤 떨어진 것으로 알고 있습니다.

코멘트

Lua의 한 줄 주석은 -- 시작하고 줄 끝까지 계속됩니다.

-- this is single line comment
-- need another line
-- huh?

블록 코멘트는 --[[ 와 함께 끝 ]] :

--[[
    This is block comment.
    So, it can go on...
    and on...
    and on....
]]

블록 코멘트는, 긴 캐릭터 라인과 같은 스타일의 단락 문자를 사용합니다. 주석을 구분하기 위해 대괄호 사이에 임의 개수의 등호를 추가 할 수 있습니다.

--[=[
    This is also a block comment
    We can include "]]" inside this comment
--]=]

--[==[
    This is also a block comment
    We can include "]=]" inside this comment
--]==]

코드 덩어리를 주석 처리하는 깔끔한 트릭은 --[[--]] 로 둘러 싸는 것입니다.

--[[
    print'Lua is lovely'
--]]

청크를 다시 활성화하려면 주석 열기 순서에 - 를 추가하면됩니다.

---[[
    print'Lua is lovely'
--]]

이 방법은 순서 -- 첫 번째 줄에 그냥 마지막 줄처럼, 한 줄 주석을 시작하고, print 문은 주석 처리되지 않습니다.

이 단계를 더 진행하면 첫 번째 블록이 주석 처리되고 두 번째 블록이 주석 처리되지 않고 두 번째 블록이 주석 처리되지 않고 두 번째 블록이 주석 처리 된 경우 두 개의 코드 블록이 설정 될 수 있습니다.

---[[
  print 'Lua is love'
--[=[]]
  print 'Lua is life'
--]=]

첫 번째 체크를 해제하면서 활성 번째 청크, 선두를 삭제 - 첫 번째 줄에 :

--[[
  print 'Lua is love'
--[=[]]
  print 'Lua is life'
--]=]

루아 프로그램 실행

일반적으로 루아는 두 개의 바이너리와 함께 배송됩니다 :

  • lua - 독립형 인터프리터와 인터랙티브 쉘
  • luac - 바이트 코드 컴파일러

다음과 같이 예제 프로그램 ( bottles_of_mate.lua )이 bottles_of_mate.lua .

local string = require "string"    

function bottle_take(bottles_available)

    local count_str = "%d bottles of mate on the wall."
    local take_str = "Take one down, pass it around, " .. count_str
    local end_str = "Oh noes, " .. count_str
    local buy_str = "Get some from the store, " .. count_str
    local bottles_left = 0

    if bottles_available > 0 then
         print(string.format(count_str, bottles_available))
         bottles_left = bottles_available - 1
         print(string.format(take_str, bottles_left))
    else
        print(string.format(end_str, bottles_available))
        bottles_left = 99
        print(string.format(buy_str, bottles_left))
    end

    return bottles_left
end

local bottle_count = 99

while true do
    bottle_count = bottle_take(bottle_count)
end

쉘 자체에서 다음을 실행하여 프로그램 자체를 실행할 수 있습니다.

$ lua bottles_of_mate.lua

출력은 다음과 같이 끝없는 루프에서 실행되어야합니다.

Get some from the store, 99 bottles of mate on the wall.
99 bottles of mate on the wall.
Take one down, pass it around, 98 bottles of mate on the wall.
98 bottles of mate on the wall.
Take one down, pass it around, 97 bottles of mate on the wall.
97 bottles of mate on the wall.
...
...
3 bottles of mate on the wall.
Take one down, pass it around, 2 bottles of mate on the wall.
2 bottles of mate on the wall.
Take one down, pass it around, 1 bottles of mate on the wall.
1 bottles of mate on the wall.
Take one down, pass it around, 0 bottles of mate on the wall.
Oh noes, 0 bottles of mate on the wall.
Get some from the store, 99 bottles of mate on the wall.
99 bottles of mate on the wall.
Take one down, pass it around, 98 bottles of mate on the wall.
...

쉘에서 다음을 실행하여 루아의 바이트 코드로 프로그램을 컴파일 할 수 있습니다 :

$ luac bottles_of_mate.lua -o bottles_of_mate.luac

또한 다음을 실행하여 바이트 코드 목록을 사용할 수 있습니다.

$ luac -l bottles_of_mate.lua


main <./bottles.lua:0,0> (13 instructions, 52 bytes at 0x101d530)
0+ params, 4 slots, 0 upvalues, 2 locals, 4 constants, 1 function
    1    [1]    GETGLOBAL    0 -1    ; require
    2    [1]    LOADK        1 -2    ; "string"
    3    [1]    CALL         0 2 2
    4    [22]    CLOSURE      1 0    ; 0x101d710
    5    [22]    MOVE         0 0
    6    [3]    SETGLOBAL    1 -3    ; bottle_take
    7    [24]    LOADK        1 -4    ; 99
    8    [27]    GETGLOBAL    2 -3    ; bottle_take
    9    [27]    MOVE         3 1
    10    [27]    CALL         2 2 2
    11    [27]    MOVE         1 2
    12    [27]    JMP          -5    ; to 8
    13    [28]    RETURN       0 1

function <./bottles.lua:3,22> (46 instructions, 184 bytes at 0x101d710)
1 param, 10 slots, 1 upvalue, 6 locals, 9 constants, 0 functions
    1    [5]    LOADK        1 -1    ; "%d bottles of mate on the wall."
    2    [6]    LOADK        2 -2    ; "Take one down, pass it around, "
    3    [6]    MOVE         3 1
    4    [6]    CONCAT       2 2 3
    5    [7]    LOADK        3 -3    ; "Oh noes, "
    6    [7]    MOVE         4 1
    7    [7]    CONCAT       3 3 4
    8    [8]    LOADK        4 -4    ; "Get some from the store, "
    9    [8]    MOVE         5 1
    10    [8]    CONCAT       4 4 5
    11    [9]    LOADK        5 -5    ; 0
    12    [11]    EQ           1 0 -5    ; - 0
    13    [11]    JMP          16    ; to 30
    14    [12]    GETGLOBAL    6 -6    ; print
    15    [12]    GETUPVAL     7 0    ; string
    16    [12]    GETTABLE     7 7 -7    ; "format"
    17    [12]    MOVE         8 1
    18    [12]    MOVE         9 0
    19    [12]    CALL         7 3 0
    20    [12]    CALL         6 0 1
    21    [13]    SUB          5 0 -8    ; - 1
    22    [14]    GETGLOBAL    6 -6    ; print
    23    [14]    GETUPVAL     7 0    ; string
    24    [14]    GETTABLE     7 7 -7    ; "format"
    25    [14]    MOVE         8 2
    26    [14]    MOVE         9 5
    27    [14]    CALL         7 3 0
    28    [14]    CALL         6 0 1
    29    [14]    JMP          15    ; to 45
    30    [16]    GETGLOBAL    6 -6    ; print
    31    [16]    GETUPVAL     7 0    ; string
    32    [16]    GETTABLE     7 7 -7    ; "format"
    33    [16]    MOVE         8 3
    34    [16]    MOVE         9 0
    35    [16]    CALL         7 3 0
    36    [16]    CALL         6 0 1
    37    [17]    LOADK        5 -9    ; 99
    38    [18]    GETGLOBAL    6 -6    ; print
    39    [18]    GETUPVAL     7 0    ; string
    40    [18]    GETTABLE     7 7 -7    ; "format"
    41    [18]    MOVE         8 4
    42    [18]    MOVE         9 5
    43    [18]    CALL         7 3 0
    44    [18]    CALL         6 0 1
    45    [21]    RETURN       5 2
    46    [22]    RETURN       0 1

시작하기

변수

var = 50 -- a global variable
print(var) --> 50
do
  local var = 100 -- a local variable
  print(var) --> 100
end
print(var) --> 50
-- The global var (50) still exists 
-- The local var (100) has gone out of scope and can't be accessed any longer.

유형

num = 20 -- a number
num = 20.001 -- still a number
str = "zaldrizes buzdari iksos daor" -- a string
tab = {1, 2, 3} -- a table (these have their own category)
bool = true -- a boolean value
bool = false -- the only other boolean value
print(type(num)) --> 'number'
print(type(str)) --> 'string'
print(type(bool)) --> 'boolean'
type(type(num)) --> 'string'

-- Functions are a type too, and first-class values in Lua.
print(type(print)) --> prints 'function'
old_print = print
print = function (x) old_print "I'm ignoring the param you passed me!" end
old_print(type(print)) --> Still prints 'function' since it's still a function.
-- But we've (unhelpfully) redefined the behavior of print.
print("Hello, world!") --> prints "I'm ignoring the param you passed me!"

특별한 유형의 nil

루아의 또 다른 타입은 nil 입니다. nil 유형의 유일한 값은 nil 입니다. nil 은 Lua의 다른 모든 값과 다른 것으로 존재합니다. 그것은 일종의 가치가없는 가치입니다.

print(foo) -- This prints nil since there's nothing stored in the variable 'foo'.
foo = 20
print(foo) -- Now this prints 20 since we've assigned 'foo' a value of 20.

-- We can also use `nil` to undefine a variable
foo = nil -- Here we set 'foo' to nil so that it can be garbage-collected.

if nil then print "nil" end --> (prints nothing)
-- Only false and nil are considered false; every other value is true.
if 0 then print "0" end --> 0
if "" then print "Empty string!" --> Empty string!

표현

a = 3
b = a + 20 a = 2 print(b, a) -- hard to read, can also be written as
b = a + 20; a = 2; print(a, b) -- easier to read, ; are optional though
true and true --> returns true
true and 20 --> 20
false and 20 --> false
false or 20 --> 20
true or 20 --> true
tab or {}
  --> returns tab if it is defined
  --> returns {} if tab is undefined
  -- This is useful when we don't know if a variable exists
tab = tab or {} -- tab stays unchanged if it exists; tab becomes {} if it was previously nil.

a, b = 20, 30 -- this also works
a, b = b, a -- switches values

함수 정의하기

function name(parameter)
    return parameter
end
print(name(20)) --> 20
-- see function category for more information
name = function(parameter) return parameter end -- Same as above

불법 복제

falsenilfalse 평가하고, 0 포함하여 나머지는 true로 평가하고 빈 문자열은 true로 평가합니다.

쓰레기 수거

tab = {"lots", "of", "data"}
tab = nil; collectgarbage()
-- tab does no longer exist, and doesn't take up memory anymore.

테이블

tab1 = {"a", "b", "c"}
tab2 = tab1
tab2[1] = "d"
print(tab1[1]) --> 'd' -- table values only store references.
--> assigning tables does not copy its content, only the reference.

tab2 = nil; collectgarbage()
print(tab1) --> (prints table address) -- tab1 still exists; it didn't get garbage-collected.

tab1 = nil; collectgarbage()
-- No more references. Now it should actually be gone from memory.

이것들은 기본이지만 자세한 정보가있는 테이블에 관한 섹션이 있습니다.

정황

if (condition) then
    -- do something
elseif (other_condition) then
    -- do something else
else
    -- do something
end

for 루프

두 가지 유형이 있습니다 for 숫자 : 루아 루프 for 루프 및 일반 for 루프.

  • 숫자 for 루프는 다음 형식을가집니다.

    for a=1, 10, 2 do -- for a starting at 1, ending at 10, in steps of 2
      print(a) --> 1, 3, 5, 7, 9
    end
    

    숫자 for 루프의 세 번째 식은 루프가 증가하는 단계입니다. 이렇게하면 쉽게 역 루프를 수행 할 수 있습니다.

     for a=10, 1, -1 do
       print(a) --> 10, 9, 8, 7, 6, etc.
     end
    

    단계 표현식을 생략하면 Lua는 기본 단계 인 1로 가정합니다.

     for a=1, 10 do
       print(a) --> 1, 2, 3, 4, 5, etc.
     end
    

    또한 루프 변수는 for 루프에 국한됩니다. 루프가 끝난 후에는 존재하지 않습니다.

  • 일반 for 루프는 반복자 함수가 반환하는 모든 값을 처리합니다.

    for key, value in pairs({"some", "table"}) do
      print(key, value)
      --> 1 some
      --> 2 table
    end
    

    루아는 반복자 (예 : pairs , ipairs )에 내장 된 몇 가지를 제공하고, 사용자는 자신의 커스텀 반복자를 정의하여 일반 for 루프와 함께 사용할 for 있습니다.

블록을 수행하다

local a = 10
do
    print(a) --> 10
    local a = 20
    print(a) --> 20
end
print(a) --> 10

까다로운 일들

때로는 루아가 문서를 읽은 후에 생각하는 것처럼 행동하지 않습니다. 이 중 일부는 다음과 같습니다.

없음과 아무것도 같은 것은 아닙니다 (일반적인 침울합니다!)

예상대로 table.insert(my_table, 20) 는 값 20 을 테이블에 추가하고 table.insert(my_table, 5, 20) 는 값 20을 5 위치에 추가합니다. table.insert(my_table, 5, nil) 는 무엇을합니까? nil 을 전혀 인자로 취급 nil 않고 테이블 끝에 값 5 를 삽입 할 수도 있지만 실제로는 테이블의 5 번째 위치에 값 nil 을 추가합니다. 이것이 언제 문제입니까?

(function(tab, value, position)
    table.insert(tab, position or value, position and value)
end)({}, 20)
-- This ends up calling table.insert({}, 20, nil)
-- and this doesn't do what it should (insert 20 at the end)

tostring() 에서도 비슷한 결과가 발생합니다.

print (tostring(nil)) -- this prints "nil"
table.insert({}, 20) -- this returns nothing
-- (not nil, but actually nothing (yes, I know, in lua those two SHOULD
-- be the same thing, but they aren't))

-- wrong:
print (tostring( table.insert({}, 20) ))
-- throws error because nothing ~= nil

--right:
local _tmp = table.insert({}, 20) -- after this _tmp contains nil
print(tostring(_tmp)) -- prints "nil" because suddenly nothing == nil

또한 타사 코드를 사용할 때 오류가 발생할 수 있습니다. 예를 들어, 일부 기능 상태의 문서가 "도넛을 반환한다면 운 좋으면 그렇지 않습니다"라고 말하면 구현 다음과 같이 보일 수 있습니다.

function func(lucky)
    if lucky then
        return "donuts"
    end
end

이 구현은 처음에는 합리적으로 보일 수 있습니다. 반환해야 할 때 도넛을 반환하고 result = func(false) 를 입력 result = func(false) nil 값이 포함됩니다.

그러나 print(tostring(func(false))) 를 쓰면 루아는 다음과 같은 오류를 던질 것입니다 stdin:1: bad argument #1 to 'tostring' (value expected)

왜 그런가요? tostring 명확하게, 비록 인수를 가져옵니다 nil . 잘못된. func는 아무것도 반환하지 않으므로 tostring(func(false))tostring() 과 동일하고 tostring(nil) 과 동일하지 않습니다.

'가치 기대치 (value expected)'라는 오류는 이것이 이것이 문제의 원인이 될 수 있음을 보여줍니다.

배열에 간격을두기

루아를 처음 접하는 사람에게는 큰 함정이며, 테이블 카테고리에는 많은 정보있습니다

안녕하세요 세계

안녕하세요 세계 코드입니다.

print("Hello World!")

어떻게 작동합니까? 간단 해! 루아는 print() 함수를 실행하고 인자로 "Hello World" 문자열을 사용합니다.



Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow