Aardio-Use the direct subscript operator [[ ]] to read member values without error

Look at the code first:

import console

t={123,a=456}
console.dump(t.a) 		//表中存在该成员,无错
console.dump(t["a"])	        //表中存在该成员,无错
console.dump(t[["a"]])	//表中存在该成员,无错

t={123,456}
console.dump(t.a) 		//表中不存在该成员,返回null,无错
console.dump(t["a"])	        //表中不存在该成员,返回null,无错
console.dump(t[["a"]])	//表中不存在该成员,返回null,无错

t=null
//console.dump(t.a)		//变量为null,出错
//console.dump(t["a"])	//变量为null,出错
console.dump(t[["a"]])	//变量为null,返回null,无错

t=123
//console.dump(t.a)		//变量类型非表table,出错
//console.dump(t["a"])	//变量类型非表table,出错
console.dump(t[["a"]])	//变量类型非表table,返回null,无错

Official explanation:

1. The usage of this thing is basically the same as [], the only difference is that it will not trigger the meta method, so if there is actually this member in the array, it is there, and if it is not, it is not. This operator cannot be fooled.

2. This direct subscript operator can be applied to any type of object (including null values) without error. If the object does not contain the member specified in the direct subscript operator, it simply returns a null value. Therefore, [[]] can be used to obtain values ​​and can easily detect the object type.

3. When the ordinary subscript operator is used in a string, the [] operator takes bytecode and a numeric value, and [[]] takes out characters.

E.g:

Define string variable str = "abcd" At this time, str[1] is his ASCII code 97, and str[[1]] returns the character "a".

For Unicode/UTF16 strings, the [] operator takes a wide byte code (a 16-bit value in units of 2 bytes), and the [[ ]] operator returns a wide character (also in 2 characters Section is a single Unicode character), but when using # to get the length, the byte length is always returned.

to sum up:

  • If you want to read the value of a member in the table, feel free to use [[]], don’t worry about reading errors in various situations.
  • If it is read correctly, it will return the value you want, if it fails, it will return null instead of reporting an error.

Guess you like

Origin blog.csdn.net/sdlgq/article/details/110851270