2015年4月1日 星期三

[Corona SDK] How to use Table?

The table in Lua is very special and important.
It can accept any types of data, except for nil.
We can also put different types of data in the same table.

We can use "{}" to create a new table.
Its index can be number or other types, except for nil.

display.setStatusBar( display.HiddenStatusBar )
t = {} --create a table
t = {he = "today"} --create a table with single property "he"
t[1] = 123
t[5] = "this is 5"
t[true] = 789
t["my"] = 456
t["you"] = "this is you"
display.newText( t[1], display.contentCenterX, 80, native.systemFont, 20 )
display.newText( t[5], display.contentCenterX, 100, native.systemFont, 20 )
display.newText( t["my"], display.contentCenterX, 120, native.systemFont, 20 )
display.newText( t["he"], display.contentCenterX, 140, native.systemFont, 20 )
display.newText( t.you, display.contentCenterX, 160, native.systemFont, 20 )
if(t[true] == 789) then
 display.newText( "this is 789", display.contentCenterX, 180, native.systemFont, 20 )
else
 display.newText( "this is NOT 789", display.contentCenterX, 180, native.systemFont, 20 )
end

To access the table, we can use t[].
There has a special usage when the index is in string type.
That is, t["name"] or t.name are all allowed, like line 13 t.you in above codes.
However, if the "name" of t["name"] has number prefix, we cannot access by t.name then.
For example, t["5r"] cannot be accessed by t.5r.
Below is the result of above demo codes:

沒有留言:

張貼留言