For other languages, we will need to use some key word, such as int,String and boolean to define the variables.
Once they are declared, we cannot change their types.
For Lua, the types of variables are defined automatically and dynamically.
It will assign the type according to the parameter you provide.
For example:
t = 1 --assign t as number type
t = "hello" --assign t as string type
Can we set t = 1 and then set t = "hello"?
That is, can we change its type for the same variable?
Yes, it is allowed.
There have few basic types:
nil: When you declare the variable without assign any value to it, it will be nil type. It is similar with null in other languages.
For example, local t or local t = nil both are nil.
If we access the variable in nil type, we will get the error message "got nil".
local t display.newText( t, display.contentCenterX, display.contentWidth / 4, native.systemFont, 40 )boolean: It is false or true. We will use it in conditional expression.
If the parameter is false or nil, the result is false.
Otherwise, the result will be true.
if(true) then --will display display.newText( "hello true", display.contentCenterX, 20, native.systemFont, 20 ) end if(false) then --will NOT display display.newText( "hello false", display.contentCenterX, 40, native.systemFont, 20 ) end if(nil) then --will NOT display display.newText( "hello nil", display.contentCenterX, 60, native.systemFont, 20 ) end if(1) then --will display display.newText( "hello 1", display.contentCenterX, 80, native.systemFont, 20 ) end if(0) then --will display display.newText( "hello 0", display.contentCenterX, 100, native.systemFont, 20 ) endIn the above example, if(0) will be taken as true.
number: To express real numbers (double-precision floating-point) ,
The example shown below are all allowed:
12 12.0 12.1895 12189.5e-3 0.121895E2 0xA3 0Xb22f
e or E is for decimal exponent,0x or 0X is for hexadecimal.
string: To present characters array, embedded with zero at the end.
function:
table: It is Lua fundamental data structure, check [Corona SDK] How to use Table?
Another special usage is that number and string can converse mutually.
If we do string operation on a number variable, then it will become string type first.
For example, display.newText() will accept string.
However, we can feed it with number variable.
t = 123 display.newText( t, display.contentCenterX, 100, native.systemFont, 20 )On other hand, if we do arithmetic operations on a string variable, then it will become number type first, as example shown below:
t = "456.2" t = t + 1 display.newText( t, display.contentCenterX, 100, native.systemFont, 20 )We will get "457.2" for above example.
For the variable t, we can use other number expression as along as it can be converted to number type.
For example t = "0x3a" or t = "1E3" are all acceptable.
沒有留言:
張貼留言