Lua tableタイプ学習ノート
基本的な紹介
注意3点:第一に、すべての要素の間には、常にカンマ","で区切られています.第二に、すべてのインデックス値を[]と[]で囲む必要があります.文字列の場合は、引用符と括弧を削除することもできます.すなわち、[]で囲まれていなければ文字列インデックスが3番目であり、インデックスを書かないとインデックスは数字とみなされ、順番に自動的に1から後ろに編成される.
例:
tt = {"hello" ,33}
value = 4
tab = {[tt] = "table",key = value, ["flag" ] = nil, 11}
print(tab[tt])
print(tab.key)
print(tab[1 ])
以上の書き方はすべて正しい.
look={[www]="ok"}これは正しくありません.wwwには値が割り当てられていないので、デフォルトはnilです.そのため、table index is nilがエラーになります.
---
temp = 1
tab = {[temp] = 1, 11}
print(tab[temp])--この場合の結果は11であり、11には明示的に対応するkeyがないため、1から、先に定義した場合はvalueを上書きする
---
temp = 2
tab = {[temp] = 1, 11}
temp = 1
print(tab[temp])--結果は11であり,定義時[temp]=1であったが,その後tempの値を変更したので別のkeyを指すようになった.
以上から分かるように、
1.文字列について、{}定義の場合、key=valueでもよいし、[flag]=nilでもよいし、インデックスはstringタイプでもよいし、非nilタイプ変数(文字列を含む)については、いずれも[variable]=valueの方式でもよい.tableを使用する場合、文字列については、の方法でアクセスしたり、[]の方法でアクセスしたりすることができます.tab[a],tab[b],a=bである限りtab[a]はtab[b]の値3にアクセスできる.インデックスを定義するときに定数を使用するか変数を使用するかにかかわらず、最終tableのvalueのインデックスkeyは定数であり、変数の変化に伴ってそのvalueのkeyは変化しません.
ネスト
tb11= {tb12 = {bool = true}} -- simple, it's a table IN a table :)
-- Call magic!
print(tb11.tb12.bool ) -- works fine, since it's calling the key and value correctly.
print(tab11["tb12" ].bool ) --same as line 33
print(tab11.tb12 ["bool"]) --same as line 33
print(tab11["tb12" ]["bool"]) --same as line 33
tableのvalueを変更する
--Altering a table's content. Basically manipulating the values of the keys.
lucky= {john="chips" ,jane ="lemonade",jolene="egg salad" }
lucky.jolene = "fruit salad" --changed the value to "fruit salad" instead of "egg salad"
lucky.jerry = "fagaso food" -- adding a new key-value pair to the container lucky.
lucky.john = nil -- remove john from giving anything or from being a key.
tableの易変性
a = {}; b = a;
print(a == b) --> true
c,d = {},{};
print(c == d) -->false
tableライブラリ関数には、---------------------------------------------------------------------------------------------------------1が使用されます.table.sort (table [, comp]) Sorts table elements in a given order, in-place, from table[1] to table[n], where n is the length of the table. If comp is given, then it must be a function that receives two table elements, and returns true when the first is less than the second (so that not comp(a[i+1],a[i]) will be true after the sort). If comp is not given, then the standard Lua operator < is used instead. The sort algorithm is not stable; that is, elements considered equal by the given order may have their relative positions changed by the sort.
name = {"you" ,"me", "him","bill" }
--table.sort - only works with arrays!
table.sort(name)
for k, v in ipairs( name) do
print( k,v)
end
--table.sort uses callbacks. a function that is writtent to be called by a library function.
function cmp( a, b)
if string.sub(a,2 ,2) < string.sub(b,2 ,2) then
return true
else
return false
end
end
table.sort(name, cmp)
for k, v in ipairs( name) do
print( k,v)
end
2. table.insert (table, [pos,] value)
Inserts element value at position pos in table, shifting up other elements to open space, if necessary. The default value for pos is n+1, where n is the length of the table so that a call table.insert(t,x) inserts x at the end of table t.
--table.insert --an easy to copy a table to another table or adding elements to an array.!
foo = {"a" ,"c", "d"}
bar = {}
function printt( table)
for i=1 ,#table do
print(i,table [i ])
end
end
print("before insert:" )
printt(foo)
table.insert(foo,2 ,"b")
print("after insert" )
printt(foo)
3. table.concat (table [, sep [, i [, j]]])
Given an array where all elements are strings or numbers, returns table[i]..sep..table[i+1] ・・・ sep..table[j]. The default value for sep is the empty string, the default for i is 1, and the default for j is the length of the table. If i is greater than j, returns the empty string.
--table.concat does what it implies. Takes an array and concates to one string.
num = {1 ,2, 3,4,5 ,6}
print(table.concat (num ,"
4. table.remove (table [, pos])
Removes from table the element at position pos, shifting down other elements to close the space, if necessary. Returns the value of the removed element. The default value for pos is n, where n is the length of the table, so that a call table.remove(t) removes the last element of table t.
abc = {"a" ,"b", "c"}
print(table.remove (abc ,2))
print("abc length = " .. #abc)
5. table.maxn (table)
Returns the largest positive numerical index of the given table, or zero if the table has no positive numerical indices. (To do its job this function does a linear traversal of the whole table.) --table.maxn
apple = {"a" ,"p",[ 5]="e"}
print(table.maxn (apple )) -- 5
duck = {[-2 ]=3,[- 1]=0}
print(table.maxn (duck )) -- 0
オブジェクト向けプログラミング
--note for a object to work, it needs a closure(inner function with an upvalue(a local value from a higher scope))
--note: the more closures made, the slower the program would run.
function mg1( n)
local function get ()
return n ;
end
local function inc (m )
n = n +m ;
end
return {get = get, inc= inc}
end
object = mg1(50 )
print(object.get ())
print(object["get" ]())
object.inc(2 )
print(object.get ())
----------------------------------------
do
local function get (o )
return o.one
end
local function inc (self , two )
self.one = self.one + two
end
function mg3 (one )
return {one = one , get = get , inc = inc }
end
end
a = mg3(50 )
a:get()
a.inc(a,2 )
print(a:get())
----------------------------------------
do
local T = {};
function T:get()
return self.n ;
end
function T:inc(m)
self.n = self.n + m ;
end
function mg4 ( n )
return {n = n , get =T.get , inc =T.inc }
end
end
c = mg4(30 )
print(c:get())
c:inc(4 )
print(c:get())
(完)