Give an example to explain the table data structure in Lua


In the text — single line comments starting with two horizontal lines, – [[add two [and] to indicate multi line comments –]].


Copy codeThe code is as follows:
–Table = Lua’s unique data structure;
—          They are associative arrays.
–Similar to PHP arrays or JS objects,
–They are hash lookup tables (dicts) and can also be used by list.



Copy codeThe code is as follows:

–Use table as dictionary / map:


–The iteration of dict uses string type key by default:
t = {key1 = ‘value1’, key2 = false}



Copy codeThe code is as follows:
–The key of string can be referenced with a dot like JS:
print(t.key1)   — Print ‘value1’
t.newKey = {}   — Add a new key / value pair.
t.key2 = nil    — Delete key2 from table.



Copy codeThe code is as follows:
–Use any non nil value as the key:
u = {[‘@!#’] = ‘qbert’, [{}] = 1729, [6.28] = ‘tau’}
print(u[6.28])   — Print “tau”



Copy codeThe code is as follows:
–For numbers and strings, keys are matched by value, but for tables, they are matched by ID.
a = u[‘@!#’]   — Now a =’qbert ‘
b = u[{}]      — What we expect is 1729,   But the result is nil:
–B = nil because it was not found.
–The reason why we didn’t find it is that the key we used is not the same object as the one we used to save the data.
–Therefore, strings and numbers are keys with better usability.



Copy codeThe code is as follows:
–Function calls that require only one table parameter do not need parentheses:
function h(x) print(x.key1) end
h{key1 = ‘Sonmi~451’}   — Print ‘sonmi ~ 451’



Copy codeThe code is as follows:
for key, val in pairs(u) do   — Table traversal
  print(key, val)



Copy codeThe code is as follows:
— _ G is a special table used to store all global variables
print(_G[‘_G’] == _G)   — Print ‘true’



Copy codeThe code is as follows:

–Use as list / array:


–The iteration method of list implicitly adds the key of int:
v = {‘value1’, ‘value2’, 1.21, ‘gigawatts’}
for i = 1, #v do   — # V is the size of the list
  print(v[i])   — Index starts from 1!! That’s crazy!
–‘list’ is not a real type, V but a table,
–But it has consecutive integers as keys, which can be used like a list.

Recommended Today

On the mutation mechanism of Clickhouse (with source code analysis)

Recently studied a bit of CH code.I found an interesting word, mutation.The word Google has the meaning of mutation, but more relevant articles translate this as “revision”. The previous article analyzed background_ pool_ Size parameter.This parameter is related to the background asynchronous worker pool merge.The asynchronous merge and mutation work in Clickhouse kernel is completed […]