Lua Table Type Learning notes _lua

Source: Internet
Author: User
Tags constant lua

Relational table type, which is a very powerful type. We can think of this type as an array. Just a C-language array, which can only be indexed by positive integers; in Lua, you can count the index of a group with any type of value, but this value cannot be nil. Similarly, in C, the contents of an array allow only one type; in Lua, you can also use any type of value to count the contents of the group, nil.

Basic introduction

Note Three points:
First, all elements are always separated by commas ",";
Second, all index values need to be enclosed in "[" and "]", and if it is a string, you can also remove the quotation marks and brackets; that is, if there is no [] enclosed, the string index is considered
Third, if the index is not written, the index is considered to be a number and automatically compiled from 1 in order;

For example:

Copy Code code as follows:

tt = {"Hello", 33}
Value = 4
tab = {[TT] = ' table ', key = value, [' flag '] = nil, 11}

Print (Tab[tt])
Print (Tab.key)
Print (tab[1])


The above wording is right.

look = {[www] = ' OK} ' this is not true, www is not assigned, so the default is nil so error table index is nil

Copy Code code as follows:

---
temp = 1
tab = {[Temp] = 1, 11}

Print (Tab[temp])--At this point the result is 11, since 11 does not have an explicit key, so starting from 1, overwriting its value if previously defined
Copy Code code as follows:

---
temp = 2
tab = {[Temp] = 1, 11}
temp = 1

Print (Tab[temp])--the result is 11, although [temp] = 1 is defined, but then we change the temp value, so we point to another key.


The above know:

1. For strings, when {} is defined, you can key = value, or ["flag"] = Nil, indexes are string types, and for non nil type variables (including strings), you can [Variable]=value
2. When using table, for strings, you can access them through the. TAB[A],TAB[B], as long as a==b so tab[a] can access the value of Tab[b]
3. Regardless of whether the index is defined with a constant or a variable, the index key of value in the final table is a constant and does not change the key of the value as the variable changes

Nesting

Copy Code code as follows:

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

Modify the value of a table
Copy Code code as follows:

--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.john = nil-remove John from giving anything or from being a key.

Variability of Table

Copy Code code as follows:

A = {}; b = A;
Print (A = = b)--> true

C,d = {},{};

Print (c = = d)-->false

The table library function uses the
-----------------------------------------------------------
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 being a function that receives two table elements, and returns True when the This is less tha n the second (so, not comp (a[i+1],a[i)) is true after the sort. If comp is isn't given, then the standard Lua operator < is used instead.
The sort algorithm is not stable; That's, elements considered equal by the given of the order may have their relative-positions by the sort.

Copy Code code as follows:

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 being 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 spaces, if necessary. The default value for POS is n+1, where n is the length of the "table so" a call Table.insert (T,X) inserts x on the end of table T.

Copy Code code as follows:

--table.insert--an easy to copy a table to another table or adding elements to a 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 are the empty string, the default for I are 1, and the default for j is the length of the table. If I is greater than J, returns the empty string.

Copy Code code as follows:

--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])

The removes from table is the element at position POS, and shifting down is elements to close the spaces, if necessary. Returns the value of the removed element. The default value for POS was n, where n is the length of the table, so this a call Table.remove (t) removes the last Elemen T of table T.

Copy Code code as follows:

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. (To do it job this function does a linear traversal of the whole table.)
--table.maxn

Copy Code code as follows:

Apple = {"A", "P", [5]= "E"}
Print (TABLE.MAXN (apple))--5

Duck = {[-2]=3,[-1]=0}
Print (TABLE.MAXN (duck))--0

Object Oriented Programming

Copy Code code as follows:

--note for a of object to work, it needs a closure (inner function with a upvalue (a local value from a higher scope)
--note:the more closures made, the slower of 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
  & nbsp function MG3 (one)
         return {one = one, get = GET, Inc = Inc}
& nbsp;   End
End
A = MG3
A:get ()
A.inc (a,2)
Print (A:get ())

----------------------------------------
Todo
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 ())

Finish

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.