프로그래밍/Corona SDK2013. 8. 28. 15:34

Understanding Lua tables in Corona SDK

Corona SDK의 루아 테이블 이해하기


 Posted on June 21, 2011. Written by  Jonathan Beebe

원문 : http://www.coronalabs.com/blog/2011/06/21/understanding-lua-tables-in-corona-sdk/

번역 : windship (windship@gmail.com)




What Are Tables?

테이블이란 무엇인가?


If you’re familiar with other programming languages, then most likely, you’re already familiar with arrays and dictionaries. In Lua, a table is a mixture of both (which is why they are so flexible and powerful).

당신이 다른 프로그램 언어에 익숙하다면, 아마 당신은 이미 딕셔너리나 배열에 익숙한 상태일 것이다. 루아에서 테이블은 배열과 딕셔너리를 합친 개념이고, 이것이 루아 테이블이 유연하고 강력한 이유이다.


If the Corona SDK is your first foray into the programming world, however, the description above probably means nothing to you. In that case, you can think of a table as a dresser.

만약 당신이 코로나 SDK로 처음 프로그래밍을 하는 것이라면, 설명은 거의 당신에게 도움이 안 될 지도 모른다. 그렇다면, 테이블을 옷장이라고 생각하라.


The drawers of the dresser would be known as “keys”, and the stuff (data) you’d put into the drawers is what’s known as the “value”. Where Lua tables differ from real drawers, however, is that you can place complete dressers (tables) within the individual drawers!

옷장의 서랍들은 "키(key)"라고 불리며, 서랍 안에 들어갈 내용물들을 "값(value)"라고 부른다. 루아 테이블이 실제의 서랍과 다른 점은, 당신은 그 서랍 안에 또 다른 옷장을 넣을 수도 있다는 점이다!


Before we go any further, let’s break down what you’ve learned so far:

좀 더 깊숙이 연구해보기 전에, 일단 배운 것을 한번 점검해 보자.


Tables hold data (aka “stuff”). Data can be of any type, to include functions.

Tables can also hold other tables.

테이블은 데이터(내용물)을 가진다. 데이터는 어떤 타입도 될 수 있고, 함수를 포함하기도 한다. 테이블에는 또 다른 테이블이 들어갈 수도 있다.


A “key” is the location where data is stored (like a drawer).

A “value” is the data that’s stored in a specific key.

"키"는 데이터가 들어가는 곳의 위치이다(서랍처럼).

"값"은 특정 키의 위치에 저장된 데이터이다.


And that’s probably the most basic explanation of Lua tables as you can get. In the following sections, I’ll show you how to define tables, how to store/retrieve the data within tables, and also how to use tables in conjunction with a “for” loop.

그리고 이것이 보통 듣게 되는 루아 테이블의 기본적인 설명이다. 다음에 나올 섹션에서, 어떻게 테이블을 정의하고, 테이블 안에 데이터를 저장하고 참조하며, "for" 루프를 이용해 테이블에 접근하고 응용하는 방법을 배워보도록 하겠다.



Defining Tables

테이블 정의하기


And by defining, of course, I mean creating a table so you can use it whenever you want. For now, I’ll focus on creating a blank table, with no data in it. This is going to be our brand new dresser:

테이블을 정의함으로써, 언제든지 원하는 테이블을 만들고 사용할 수 있다. 지금은 데이터가 들어있지 않은 빈 테이블을 만드는 것에 대해 중점적으로 설명하겠다. 


    local myTable = {}


A table is just another variable in Lua, so it’s defined the same way: just a variable name separated by an equals sign and the data you want to store in the variable.

테이블은 루아에서 단지 좀 다른 형태의 변수에 지나지 않는다. 그러므로 테이블을 만드는 것은 변수를 만드는 것과 같은 방법으로 만들 수 있다. 


The way Lua can tell it’s a table is, you guessed it, because of the brackets. Anywhere you see an opening bracket ( “{” ) in Lua, you know it’s a start of a table. The end of a table is always denoted by a closing bracket ( “}” ). You’ll see these all along, many times as arguments within functions, so it’s important for you to be able to identify them as tables whenever you see them.

루아에서 테이블을 설정하려면 브래킷("{}")을 사용한다. 루아에서는 어디서나 "{" 기호를 볼 수 있는데, 이것을 본다면 테이블이 생성되는구나 라고 생각하면 된다. 테이블의 끝은 닫히는 "}" 브래킷 기호로 끝난다. 함수 등에서도 흔히 볼 수 있으며, 언제든 테이블을 봤을 때 그 내용을 판단하는 데에 매우 중요하다.


Now that you have a blank table (myTable), it’s time to start storing stuff in it! Next I’ll go over the different ways to store data into a table, and also how to retrieve that data.

이제 우리는 빈 테이블(myTable)을 갖게 됐다. 이제 안의 내용물을 정렬할 시간이다. 테이블 안에 데이터를 넣는 다른 방법과, 그 데이터를 검색해 찾는 방법을 설명해 보겠다.



Tables as Arrays

배열로써의 테이블


Below are three different ways you can use a table as a numerical array. Each “method” shown below is completely identical. They are simply three ways to do the same exact thing.

아래에 테이블을 수치값 배열로 사용할 수 있는 3가지 방법이 있다. 아래에 나오는 각각의 "메소드"는 완전히 동일한 효과를 가진다. 이것은 단지 정확히 같은 작업을 수행하는 3가지 다른 방법의 예를 설명한다.


The fourth method is exactly the same as the third, but it shows how line breaks aren’t necessary?you’ll see this one a lot when passing tables as arguments to functions.

네번째의 메소드는 세번째 메소드와 완전히 같지만, 라인 브레이크를 쓰지 않아도 되는 방법이다. 테이블을 함수에 인자로 보낼 때 이런 메소드를 많이 보게 된다.


METHOD 1:

메소드 1:


    local colorTable = {}


    colorTable[1] = "blue"

    colorTable[2] = "red"

    colorTable[3] = "yellow"

    colorTable[4] = "green"

    colorTable[5] = "purple"


    print( colorTable[3] )  -- "yellow"가 출력됨


METHOD 2:

메소드 2:


    local colorTable = {

        [1] = "blue",

        [2] = "red",

        [3] = "yellow",

        [4] = "green",

        [5] = "purple"

    }


    print( colorTable[3] )  -- "yellow"가 출력됨

    

METHOD 3:

메소드 3:


    local colorTable = {

        "blue",

        "red",

        "yellow",

        "green",

        "purple"

    }


    print( colorTable[3] )  -- "yellow"가 출력됨

    

METHOD 4:

메소드 4:


    local colorTable = { "blue", "red", "yellow", "green", "purple" }


    print( colorTable[3] )  -- "yellow"가 출력됨

    

Once again, the examples shown above all produce the same thing. A table with five different keys, all with the same value. As a Corona developer, you’ll see every single one because they all depend on personal preference.

한번 더 이야기하지만, 위의 예제는 전부 같은 결과를 보여준다. 5개의 키를 가진 테이블이 있고, 안에 들어있는 값도 전부 같다. 


When a table is used as a numerical array, the keys are all numerical values that go in order (starting from 1, not 0 as with most other programming languages). The print statement in each example (above) shows you how to access data in a table by placing their index number between square brackets ( “[]” ).

테이블이 수치 배열로 사용될 때, 키들은 전부 숫자값이 되며 순서를 나타내게 된다(1부터 시작한다. 다른 대부분의 프로그램 언어들처럼 0부터 시작하지 않는다). 위의 각각의 예제에 있는 print 명령은, [] 기호 사이에 인덱스 숫자값을 넣음으로써 테이블에 있는 데이터를 바꾸는 방법을 보여준다.


Also remember, whenever you define a table, keys are always separated by commas, with the final key not requiring one.

그리고 기억하자. 언제든 테이블을 정의할 때, 키들은 ","(콤마)로 정렬되고, 가장 마지막 키에는 콤마를 붙이지 않는다.


To get the total count of a table with numerical keys, you can do so by using the ‘#’ sign in front of the table name, like so:

숫자 키를 가진 테이블의 전체 갯수를 얻고 싶을 때에는, 테이블명 앞에 "#" 기호를 붙이면 된다. 다음 예제를 보자.


print( #colorTable )    -- 5가 출력됨



Tables as Dictionaries

딕셔너리로써의 테이블


Lua tables can also behave like dictionaries from other programming languages (aka, “associative arrays”). Below is an example of a table behaving like a dictionary:

루아 테이블은 또한 다른 프로그램 언어의 딕셔너리처럼 사용될 수도 있다(연관 배열이라고도 불린다). 딕셔너리처럼 사용되는 테이블의 예제를 보자.


    local colorTable = {

        sky = "blue",

        grass = "green",

        water = "blue",

        lava = "red"

    }


    colorTable.dirt = "brown"


    -- 데이터 액세스하기


    print( colorTable.grass )   -- green이 출력됨

    print( colorTable["dirt"] )  -- brown이 출력됨

    

In the above example, you can see the keys are NOT defined numerically, and that’s the main difference here. Sometimes, data is easier to identify using this method because of the way you’re able to access the data.

위 예제에서는, 키들이 숫자로 정의되어 있지 않다. 키 값이 문자로 되어 있을 때엔 위와 같은 방식으로 액세스하는 것이 데이터를 다루기 쉽다.


Instead of accessing data using numbers, you can “associate” the keys with words instead. In the example above, you see two different methods of accessing the data:

숫자를 사용해 데이터를 액세스하는 대신, 단어로 된 키값을 연관시키는 것이다. 위 예제에서는 데이터에 액세스하는 두 가지 다른 방법을 볼 수 있다.


    colorTable["sky"]


    -- and...


    colorTable.sky


The two methods shown above are exactly the same?just two different ways to access the same data. And just as with numerical keys, you can add keys later on, as you can see with the dirt key being added after the table was already defined.

위 예제에서 보여지는 두 가지 메소드는 완전히 같다. 단지 같은 데이터에 액세스하는 각각 다른 방법일 뿐이다. 여기에 숫자 키 값을 써서 읽으려고 하면 테이블이 이미 정의된 다음에 들어간 쓰레기 키값만을 볼 수 있다.


And speaking of flexibility, although Lua tables can behave like arrays and dictionaries, they can also behave like both at the same time. If you want, you could mix numerical keys with string-based keys, though this would make for a very confusing table structure. Normally, it’s best to go with either or.

유연성을 위해서, 루아 테이블은 배열이나 딕셔너리처럼 사용될 수 있고, 두 가지 특성을 동시에 나타낼 수도 있다. 원한다면 숫자 키값과 문자열 키값을 동시에 사용할 수도 있는데, 이것이 테이블 문법을 매우 헷갈리게 만든다. 보통은 한가지만 사용하는 게 좋다.



Data Types

데이터형


As mentioned before, tables can hold any kind of data within it’s individual keys. That means you can store additional tables, functions, and function references with the keys of a table, as well as the more common numbers and strings.

전에 설명한 바와 같이, 테이블은 각각의 키에 어떤 형태의 데이터도 저장할 수 있다. 이것은 테이블 안에 단지 숫자나 문자열만이 아니라, 또다른 테이블, 함수, 그리고 또다른 테이블의 키 값을 포함하는 함수 레퍼런스도 데이터로서 저장할 수 있다는 뜻이다. 


Here’s an example of how to store a table within a table (and how to access the data):

다음은 테이블 안에 또다른 테이블을 저장하고 액세스하는 방법을 보여주는 예제이다.


    local people = {

        { name="Bob", age=32, gender="male" },

        { name="Jane", age=29, gender="female" }

    }


    print( people[1].name )     -- Bob이 출력됨


    print( people[2]["gender"] )    -- female이 출력됨

    

There is no limit to how many tables you can store within other tables.

테이블 안에 저장될 수 있는 테이블의 갯수에는 제한이 없다.


Another complex form of data you’ll see stored within the keys of a table are functions and references to other functions. Here’s an example of a reference to a function stored in the key of a table:

테이블의 키에 저장될 수 있는 또 다른 데이터 조합 형태로는 함수, 다른 함수에의 레퍼런스가 있다. 테이블 키에 함수 레퍼런스를 저장하는 예제를 보자.


    local function helloWorld()

        print( "Hello World!" )

    end


    local myTable = {

        name = "Bob",

        func = helloWorld

    }


    myTable.func()  -- Hello World!가 출력됨



    ----------



    local function helloWorld()

        print( "Hello World!" )

    end


    local myTable = { 100, 100, helloWorld, true }


    myTable[3]()    -- Hello World!가 출력됨

    

And here’s how you would store an actual function (not a reference) in a table’s key:

그리고 테이블 키에 실제 함수를 저장시켜 버리는 예제이다.


    local myTable = { 100, 100, function() print( "Hello World!" ); end, true }


    myTable[3]()    -- Hello World!가 출력됨


As you’ve probably already figured out by now, each key within a table is no different than any other variable in Lua. You can store anything you want within it. That’s the best way to look at it.

이미 짐작했겠지만 테이블의 키는 루아의 다른 변수들과 차이가 없다. 키 안에 원하는 어떤 것이라도 넣을 수 있다. 


When tables start getting big and confusing, the best advice I can give is to just look at what’s between the commas separately, as if it is on a line of code by itself. From there, your confusion should start clearing up.

테이블이 커지고 복잡해지기 시작하면, 그 테이블의 구조를 파악하는 가장 좋은 방법은 ","로 나눠진 요소들이 무엇무엇인가를 보는 것이다. 그렇게 하면 구조가 확실하게 파악될 것이다.



Tables and Loops

테이블과 루프


One of the most common purposes of using tables over regular variables is the ability to “iterate” over the keys of a table with a loop.

일반적인 변수가 아니라 테이블을 사용하는 주된 목적 중의 하나는 루프로 테이블의 키와 데이터를 보다 편리하게 액세스하는 것에 있다.


Below is an example of how to iterate through a table with numerical keys:

다음 수치 키값을 가진 테이블을 검색하는 예제를 보자.


    local myTable = { "blue", "red", "yellow", "green", "white", "purple" }


    for i=1,#myTable do

        print( myTable[i] )

    end


    -- 출력:

    blue

    red

    yellow

    green

    white

    purple

    

With everything that I’ve went over so far, the above code should be pretty clear. Iterating over the contents of a table with numerical keys is pretty straight-forward.

지금까지 공부한 내용을 기억한다면 위의 코드는 꽤 알기 쉬울 것이다. 숫자 키를 가진 테이블의 내용은 for 루프에 의해 순차적으로 읽어지고 출력된다.


However, what if your table has key names instead of numbers?

그러나, 만약 여러분의 테이블이 숫자 대신에 문자 키값을 가진다면?


For that, we’ll use the pairs() function (which returns two variables):

그렇다면, pairs() 함수를 사용하자. 이 함수는 2개의 값을 변수를 통해 되돌려준다.


local colorTable = {

    sky = "blue",

    grass = "green",

    water = "blue",

    lava = "red",

    dirt = "brown"

}


for key,value in pairs(colorTable) do

    print( key, value )

end


-- 출력:


sky     blue

grass   green

water   blue

lava    red

dirt    brown


If a table uses names to identify the keys, then you can’t simply get the count and iterate over the keys numerically. Instead, you use the pairs() function with tables that don’t have numerical keys (just as you see in the example above).

테이블이 키값으로 문자열을 가진다면, 이 키들을 수치적으로 카운트하고 정렬하는 것은 간단하지 않다. 위 예제에서 보는 것처럼 pairs() 함수를 사용해야 한다.



Further Reading

더 읽어볼 것들


To get a more complete, well-rounded understanding of tables in Lua, please visit the following two web pages (both of which were extremely useful to me when I was learning):

루아의 테이블에 대해 좀 더 확실하게 이해하고 싶다면 다음 두 개의 웹페이지를 참고하라. 둘 다 필자가 공부할 때 매우 도움이 되었다.


http://www.lua.org/pil/2.5.html

http://lua.gts-stolberg.de/en/Tables.php


The more you see them and use them “out in the wild”, the more clear tables will become. When you finally have a real need for tables is when their power and flexibility will really shine through.

실제로 보고 실습해 보면 테이블이 좀 더 알기 쉽게 다가올 것이다. 테이블의 강력함과 유연성을 알게 되면 정말로 테이블이 필수적인 것이라는 것도 알게 된다.


Feel free to post your questions in the comments section, I’ll try my best to respond to them as they come (be sure to do a quick skim of the comments to make sure your question wasn’t already asked!).

댓글 란에 편하게 질문을 남겨 주시기 바란다. 가능한 한 성심껏 답글을 달도록 하겠다. 다만 이미 있는 질문이 아닌지는 한번 쓱 확인해 주시기 바란다.


Filed Under: Lua, Tutorials.

Create amazing games for iOS and Android with the Corona SDK

45 Responses to “Understanding Lua tables in Corona SDK”



Rob Miracle

Very well done Jonathan!

조나단, 짱임!


June 21st, 2011 Reply


carlos m. icaza

I even learned from reading this. Thanks Jon.

이거 읽고 많이 배웠어. 조나단 고마워.


C.


June 21st, 2011 Reply



Nick W

Nice one, thanks Jon.

멋진 글이네. 고마워 조나단.


Just a quick query does “Joe” turn into “Bob” because of a typo (or have I missed something?)

근데 "Joe"가 "Bob"으로 바뀌지 않았어? 아님 내가 헷갈렸나?


Very clear explanation, I’m not a programmer but could understand it.

아주 알기 쉬운 설명이네. 나는 프로그래머가 아닌데도 이해하기 쉬웠어.


Thanks

고마워.


Nick


local people = {


{ name=”Joe”, age=”32″, gender=”male” },


{ name=”Jane”, age=”29″, gender=”female” }


}


print( people[1].name ) ? output: Bob


print( people[2]["gender"] ) ? output: female


June 21st, 2011 Reply


Jonathan Beebe

@Nick: Nice catch! I’m not sure how or why his name got changed, lol. I updated the article.

좋은 지적이네. 왜 이름이 바뀌었는지 모르겠지만 본문 수정했어.


June 21st, 2011 Reply


Rob

Jon,


These tutorials are great and helping a lot of us get to grips with Lua & Corona. Could I suggest a metatables tutorial and using them for OO in Lua? I use these techniques in my code but I don’t really understand what is really going on ;-)

조나단, 이 튜토리얼 끝내준다. 루아와 코로나 공부에 매우 도움이 됐어. 루아의 객체지향 메타 테이블에 대한 튜토리얼을 부탁해도 될까? 내 코드에 객체지향 메타테이블을 쓰고는 있는데 사실 잘 모르겠어.


Cheers!


Rob


June 21st, 2011 Reply


Altaf

hi Jon,


Thanks for this. MY suggestion is to also to consider a coordinate , scaling tutorial based on best practices for creating apps which can run both on iOS and android.

이 글 고마워. iOS와 안드로이드 양쪽에서 돌아가는 좌표와 스케일링에 대한 튜토리얼도 제안하고 싶은데.


Keep up the good work.

계속 분발해 주시길.


June 21st, 2011 Reply


Mo

WOW! Thank you. Great stuff. Just a quick question about tables. Let say I want to setup a sprites which have position x and y. Could I use something like this:

와, 고마워, 멋진 글이야. 테이블에 대해서 조금 질문하고 싶은데, 위치 x와 y를 가진 스프라이트를 세팅하려고 할 때 이렇게 사용해도 될까?


sprite[1].x = 1000

sprite[1].y = 10

sprite[2].x = 2000

sprite[2].x = 4000

……


Thanks again for wonderful tutorials. I will also suggest one about timers and when they actual get triggered in a lua file(when they are declared or when the lua initialization is finished)

멋진 튜토리얼에 대해 다시 한번 감사를 표하고 싶어. 루아 파일에서 타이머와 타이머가 작동될 때(막 정의됐을때나 루아 초기화가 끝났을 때)에 대한 튜토리얼도 부탁하고 싶네.


Mo


June 21st, 2011 Reply


Jonathan Beebe

@Mo: Yup, you can definitely do that. Just make sure that “sprite” is a table before you start assigning values to its individual keys. Example:

응, 그렇게 정의해도 돼. 다만 "스프라이트"가 값을 넣기 전부터 이미 테이블이 되어야 한다는 것을 알아둬야 해. 예를 들면 다음처럼:


sprite = {}


Also, in your example, sprite[1] and sprite[2] are also tables, because you are assigning values to their individual keys (x & y).

그리고, 당신의 예제에서는 각각의 키(x, y)에 값을 넣었기 때문에 sprite[1]과 sprite[2]도 역시 테이블이 된다는 점을 알아둬.


And thanks for the suggestions everyone.

그리고, 튜토리얼에 대한 제안을 해준 여러분 고마워.


June 21st, 2011 Reply


Piyush

You have removed all the doubts about Tables.

테이블에 대한 모든 의혹을 없애 줬군.


June 21st, 2011 Reply


Mo

Cool. Thanks Jon

짱인데. 고마워 조나단.


Mo


June 21st, 2011 Reply


Chris

Usefull post, Jon!

아주 도움이 되는 글이야 조나단!


Maybe you should mention removing tables aswell (though i guess nil’ing them will work fine ;) )

테이블을 제거하는 방법도 써주는 게 좋을 것 같애. nil을 넣으면 될 거라고 봐.


June 22nd, 2011 Reply


Adrian Eraldo

Thanks Jon!

Loud and clear.

고마워 조나단!


June 22nd, 2011 Reply


paul

Nice ? a clear and succinct definition of tables. Thanks Jonathan!

멋진데. 테이블에 대해 깔끔하고 간결하게 정리돼 있네. 고마워 조나단!


June 22nd, 2011 Reply


Leon

Good one Jon. I have gone back to my game and started using tables now.

이거 멋져 조나단. 난 내가 만들던 게임에 이제 테이블을 적용하고 있어.


June 22nd, 2011 Reply


Dan

Is it possible to remove an item from a table/array like pop it off the list?

테이블이나 배열에서 요소를 제거할 수 있어?


I’m planning on storing a bunch of levels in a table and randomly picking one, then popping it off the table so it can’t be picked again in the same session.

테이블에 많은 스테이지를 저장해 두고 랜덤으로 하나를 가져오게끔 하려고 하는데, 한번 읽어온 건 같은 세션 내에서는 또 가져올 수가 없어.


Thanks.


June 23rd, 2011 Reply


Daniel

@Jonathan Beebe It would awesome if you could write a tutorial about modules and how to use them. I know that I can’t be the only one still lost on them.

모듈과 그 사용법에 대해서도 튜토리얼을 써 주면 고맙겠어. 아마 거기서 막힌 사람이 나 혼자만은 아닐거야.


June 23rd, 2011 Reply


Jonathan Beebe

@Dan: Yes, you can do that. Just use table.remove( table, position ) ? I should’ve went over that in the article!

응 그렇게 해도 돼. 그냥 table.remove( table, position ) 이라고 해주면 될거야.


You can also just set the key to nil, for example:

아니면 그냥 키에 nil 값을 넣어버려도 돼. 예를 들자면:


myTable[3] = nil


또는...


myTable.favoriteColor = nil


@Daniel: Great idea! I’ll definitely add that to the list of upcoming topics. Right now I’m juggling collisions or external modules.

좋은 생각인데! 다음에 쓸 글 리스트에 넣어놓을께. 지금은 충돌에 대해서 쓸지 외장 모듈에 대해서 쓸지 망설이는 중이야.


June 23rd, 2011 Reply


arma9

Why sometimes it used in if block this format, by example:

왜 가끔 블럭이 이런 형식으로 돼 있을 때도 쓰이는 거지? 예를 들어:


local colorTable = {

sky = “blue”,

grass = “green”,

water = “blue”,

lava = “red”,

dirt = “brown”

}


이건 어째서야?


for _,value in pairs(colorTable) do

print( key, value )

end


June 23rd, 2011 Reply


Jonathan Beebe

@arma9: Not exactly sure what you’re asking, but the table you are showing me cannot be indexed numerically, therefore you have to use the pairs() function, which returns two variables: a key, and a value (rather than just an index number, when dealing with numerically indexed tables)

네가 묻는게 정확히 뭔지 모르겠는데, 니가 쓴 테이블은 숫자로는 인덱싱할 수가 없으니까 pairs() 함수를 써야 하고, 그건 키와 데이터 2개의 변수값을 리턴하는거야.


June 23rd, 2011 Reply


Alex

please give a short tutorial on OO best practices

객체지향 개념에 대해서도 짧고 간결한 튜토리얼 좀 써주라.


June 28th, 2011 Reply


Garet

I use tables for pretty much everything! My character = a table, his weapons = a table.

난 거의 대부분의 요소에 테이블을 쓰고 있어. 캐릭터도 테이블, 무기도 테이블.


It’s very useful to layout your weapons and pickups as tables, such as:

무기와 다른 것들을 테이블로 만들면 짱 편해. 예를 들면:


myGun = {}

myGun.sprite = mySprite

myGun.damage = damage


기타등등


Then I can just assign it to my character like:

그러고 나면 캐릭터를 이렇게 정의할 수 있게 되지:


myCharacter.weapon = myGun


Then whenever I want to access something like damage I can simply call:

그럼 난 언제든 대미지나 기타 등등의 것들에 요렇게 아주 간단하게 액세스할 수 있어:


myCharacter.weapon.damage


They make like so much easier :)

쉽잖아?


June 29th, 2011 Reply


Mo

Hello Jon

안녕, 조나단?


One more question if I may: how would you make a table of sprites? For instance 

괜찮다면 뭐 하나 더 물어보고 싶은데, 스프라이트를 위한 테이블은 어떻게 만들어? 예를 들면:

sprites ={}

sprites[1].x = 100, sprites[1].y = 100


but about attaching an image to that table element?

요렇게 쓰는데, 테이블 요소에 이미지를 넣으려면 어떻게 하는거지?


At this I am using sprite1, sprite2 images and their x and y coordinates but I will love to use a table so to make my code more general.

지금은 sprite1, sprite2 이미지랑 x, y좌표를 쓰고 있긴 한데, 코드를 좀 더 제대로 만들고 싶어서 테이블을 써보려고 해.


Thanks a lot for any pointers

어떤 조언이라도 도움이 될거야.


Mo


July 13th, 2011 Reply


Mo

EDIT: Hi Jon. Forget it. I think I figure out ( I should have simply search better this great forum). I will come back here if I have still issues.

수정: 안녕 조나단. 내가 위에 부탁한 건 그냥 무시해줘. 아마 내가 직접 검색해보고 찾아보는 게 좋을 것 같아. 도저히 모르겠으면 다시 올께.


Thanks for a great post again!

좋은 글 써줘서 고마워!


Mo


July 13th, 2011 Reply


Michelle

Jonathan,


Thanks for the post but I do have a question. I am a newby and was still able to catch on to alot of your docment but need some clarity. My gameboard has 16 spaces and I have 16 gamepieces. To complete this game the game pieces will form a specific pattern on the board. This pattern can change but overall it still comes down to the same logic with pieces shifted slightly. I thought about your game array you showed and started doing a ( “1″, “2″, through 16) but then was not sure how to progress from that. How do I know when a piece has landed on a specific spot on the board and once all the pieces are on the board, how do I tell whether the pattern is correct via the logic?

조나단, 좋은 글 써줘서 고마워. 질문이 있는데, 난 아직 초보자고 네 글에서 배울게 많은 사람이지만 좀 더 명확한 게 필요해. 내가 만들고 있는 게임판에는 16개의 칸이 있고 말도 16개 있어. 게임에서 이기려면 말을 게임판에 특정한 패턴으로 늘어놔야해. 이 패턴은 바뀔 수도 있지만 같은 로직으로 만들어지도록 돼 있어. 이것 때문에 1부터 시작해서 16까지 있는 배열을 만들려고 하는데 어떻게 해야할지를 모르겠어. 말이 판의 특정 지점에 놓여졌다는 것, 그리고 모든 말이 다 판에 놓여진 것을 어떻게 알 수 있을까? 그리고 말이 놓여진 패턴이 맞는 패턴인지 체크하려면 어떻게 해야 될까?


July 18th, 2011 Reply



fjal

hi,


how can i get the data which is a table inside a table, i mean like this:

테이블 속의 테이블에 들어있는 데이터를 액세스 하려면 어떻게 해야 되지? 예를 들면:


t = { {a, b, c}, {d, e, f} };


print(t[1]) ??>>> {a, b, c}


how can i print just the letter “a”?

여기서 데이터 "a"를 가져오려면, 어떻게 액세스하지?


TIA


July 24th, 2011 Reply


Jonathan Beebe

To print the letter “a” in your example, you do this:

네 예제에서 데이터 "a"를 액세스하려면, 이렇게 해봐:


print( t[1][1] )


July 25th, 2011 Reply


ZaidiSoft

Hey Jon,

안녕 조나단,


Great tutorial and helped me a lot as newby on Lua.

좋은 튜토리얼 덕분에 나같은 루아 초보자에게 많은 도움이 됐어.


Quck question here. I am trying to make a dictionary app with audio translation included. How will I accomplish that. I think using a table will be a great way to go but how can I associate a word with audio file and access it.

질문 좀 할께. 음성 번역 기능이 있는 사전 앱을 만들려고 하는데, 이걸 어떻게 구현하면 좋을까? 테이블을 쓰면 좋을 것 같은데, 오디오 파일과 단어를 어떻게 연결하고 액세스하면 좋을지를 모르겠어.


August 5th, 2011 Reply


Sean

Jon,


How might I store various image files in a table and call them at random? Any suggestions on how to code this would be greatly appreciated.

여러 개의 이미지 파일을 테이블에 저장하고 랜덤으로 불러오려면 어떻게 하면 될까? 어떤 거라도 코딩하는 방법을 알려주면 매우 고맙겠어.


Thanks,

Sean



August 8th, 2011 Reply


Jonathan Beebe

Hi sean, here’s the most basic way I could think to do that:

안녕 숀, 그걸 하려면 아마 가장 간단한 방법은 이런 걸거야:


local imgTable = {

“image1.png”,

“image2.png”,

“image3.png”

}


local randN = math.random(1,3)

local imageObj = display.newImage( imgTable[randN] )


August 8th, 2011 Reply


Sean

Thanks Jon,


Your suggestion worked like a charm!

고마워 조나단, 알려준 거 완전 잘 된다!


Sean


August 8th, 2011 Reply


luiz

hi,

i want to see a “simple shooter” demonstrating how to crate

a enemies table,a shot tabe and a ship table and how it works all together.

there is a HUGE difference between just read the “syntax” in lua docs and

and have an example demonstrating how tables works in a game.

안녕, 간단한 슈팅 게임 만드는 걸 좀 보고 싶어. 적 테이블, 총알 테이블, 우주선 테이블을 만들고 그게 다 제대로 돌아가는 게임 말야. 루아 문서에 있는 짧은 "문법"을 보는거랑, 실제로 게임에서 돌아가는 예제랑은 완전 다르니까 말야.


August 31st, 2011 Reply


Nicholas Golden

Jon you are a pimp!


I’ve been avoiding tables like the freaking plague! I’ve made a game, i’ve got my structure and then I had to think about saving data like score, level completed etc. Since I never programmed anything before lua/corona, I knew I needed to learn tables.

존 너는 정말 끝내줘! 난 전에 테이블 쓰는걸 완전 꺼렸었어. 전에 게임 만들때 점수나 클리어한 스테이지 수 같은 데이터를 보존해야 됐는데. 루아나 코로나 이전엔 프로그램 한 적이 없어서 테이블을 배워야 한다는걸 알았지.


This really helped me out, I’ve read through this several times and my guess I’ll be reading through this over and over again basically using as my reference doc for tables. It’s really good!

이거 정말 도움이 됐어. 이 글을 몇번 읽어보고 이걸 그냥 내 테이블 참고문서로 하기로 했어. 정말 좋아!


Off to go build a dresser with a dresser containing a dresser. Whoa. lol.

옷장 안의 옷장 안의 옷장이라. 와... ㅋㅋㅋ


-Nick g


September 28th, 2011 Reply


Rodrigo RSCdev

Hello Jonathan,

안녕 조나단,


Just would like to say something…”Thank You Mate!”

그냥 이 한마디만 할께. 정말 고마워 친구!


Help like this article is invaluable.

이 글은 가치를 매길 수 없을 정도로 좋은 글이야.


Regards,

Rodrigo.


October 29th, 2011 Reply


Binod Suman

Hi,


Very thanks for good tutorial and best thing is that you have explained in very basic way. One small question, if I have one table and that is not numerical index based then how to remove item from that table.

좋은 튜토리얼 고마워. 특히 아주 기본적인 방식으로 설명하고 있는게 매우 좋아. 작은 질문이 하나 있는데, 테이블을 하나 만들었고 이게 숫자 인덱스가 아니라면 테이블에서 값을 지울라면 어떻게 해야 되지?


예를 들어서:


local person = {}

person.name=”Jonathan”

person.friend=”Binod”

person.mobile=”9999999999″


Now I have to remove mobile info from person table?

이제 person 테이블에서 mobile 값을 지우려면 어떻게 해야 하지?


Thanks again from sharing very nice tutorial.


Binod Suman

Bangalore, India


December 28th, 2011 Reply


Marco Otte

Hi,

I was wondering if I can dynamically define tables.

So something like this:

안녕, 내가 동적으로 테이블을 생성할 수 있을까? 예를 들면 이렇게:


local theName = {“tableName1″, “tableName2″}

local theName[1] = {}


Then having not only the initial table called ‘theName’ but also a table called ‘tableName1′.

이러면 "theName"이라는 테이블과 "tableName1"이라는 테이블이 생기잖아?


On the Net I found some references to:

내가 검색해서 찾아본 어떤 참고문서에는 이렇게 나와있었어:


local _G['theName[1]‘] = {}


but that doesn’t seem to work with the Corona SDK.

근데 이건 코로나 SDK에서는 잘 작동하지 않는 것 같애.


Thanks!


February 3rd, 2012 Reply


daniel

hi can som one HELPPPPPPPPPP ME i try to spawn 2 monsters and i cant

here is the code i need this because i need to spawn like 30 diferent characters with same properties

누가 나 좀 도와줘. 몬스터 2마리를 불러내려고 하는데 안돼. 아래 코드가 있으니까 좀 도와줘. 30마리의 다른 캐릭터를 같은 속성으로 불러내야 한다구...


local myTable = {“monster1″,”monster2″}

for i=1,#myTable do

local ( myTable[i])= display.newImage”images/mosntruos/monstruo”..i..”.png”)

end


February 8th, 2012 Reply


Jim

Index does not start at zero? Hmmm. That could explain some problems I was having recently. Thanks for taking the time to go over this topic!

인덱스가 0에서 시작하지 않는다구? 흠. 그럼 내가 지금 겪는 문제들의 원인이 뭔지 알겠네. 시간 내서 이런 글 써줘서 고마워!


November 24th, 2012 Reply


vik

I like it very much,very helpful tutorial.

아주 도움되는 튜토리얼이야, 너무 좋아!


December 20th, 2012 Reply


mayank

Nice one dude …..

please give a tutorial on layers..

이거 멋져 친구, 부탁인데 레이어에 대해서도 튜토리얼을 써줘.


January 1st, 2013 Reply


Guillermo

hi guys, how i can get a lenght of table, for example:

안녕 여러분, 테이블의 길이를 얻으려면 어떻게 해야 되지? 예를 들면:


local imgTable = {

“image1.png”,

“image2.png”,

“image3.png”

}


January 4th, 2013 Reply


godslave

Hi guys can i put some variable within lua table like

안녕 여러분, 루아 테이블에 다음과 같이 변수 몇 개를 넣을 수 있을까?


local myTable = {}

myTable.firstVariable

myTable.secondVariable

myTable.thirdVariable


and use these variable letter in my script like

myTable.firstVariable = display.newImageRect( “assets/backgrounds/apple_ash.png”)

그리고 이 변수 이름들을 내 스크립트에 다음처럼 사용할 수 있을까?


March 19th, 2013 Reply


Rob Miracle

Yes, you can, in fact that may be one of my favorite features of Lua. Even if you did:

응 가능해. 사실 그건 루아에서 내가 가장 좋아하는 기능 중의 하나야.


myImage = display.newImageRect(“myimage.png”,width, height)


myImage is a table and you could do:

myImage는 테이블이고 넌 이렇게 하면 돼:


myImage.isActiveImage = true


or whatever creative things you can throw at it.

아니면 그냥 니가 만들고 싶은 걸 넣어버려.


March 19th, 2013 Reply


Philgin

How do you dynamically append to a table without defining a key like:

키를 정의하지 않은 테이블에 동적 참조를 하려면 어떻게 하지?


myTable = {}

myTable[] = “red”

myTable[] = “blue”


Posted by windship