English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Lua Data Types

Lua is a dynamically typed language, variables do not require type definitions, and only assignments are needed for variables. Values can be stored in variables, passed as parameters, or returned as results.

There is in Lua. 8 There are a total of 8 basic types: nil, boolean, number, string, userdata, function, thread, and table.

Data typeDescription
nilThis is the simplest, only the value nil belongs to this type, representing an invalid value (equivalent to false in conditional expressions).
booleanContains two values: false and true.
numberRepresents a double-precision real floating-point number
stringStrings are represented by a pair of double quotes or single quotes
functionFunctions written in C or Lua
userdataRepresents any C data structure stored in a variable
threadRepresents an independent execution path, used to execute coroutines
tableIn Lua, a table actually is a "associative array" (associative arrays), and the index of the array can be a number, a string, or a table type. In Lua, the creation of a table is completed through a "construction expression", the simplest construction expression is {}, which is used to create an empty table.

We can use the type function to test the type of a given variable or value:

print(type("Hello world"))      --> string
print(type(10.4*3))             --> number
print(type(print))              --> function
print(type(type))               --> function
print(type(true))               --> boolean
print(type(nil))                --> nil
print(type(type(X)))            --> string

nil (empty)

nil type represents a type with no valid value, it has only one value -- nil, for example, printing a variable that has not been assigned a value will output a nil value:

> print(type(a))
nil
>

For global variables and tables, nil also has a "deletion" effect. Assigning a nil value to a global variable or a variable in a table is equivalent to deleting them. Execute the following code to know:

tab1 = { key1 = "val1", key2 = "val2", "val3".. "}
for k, v in pairs(tab1) do
    print(k .. ") - ".. v)
end
 
tab1.key1 = nil
for k, v in pairs(tab1) do
    print(k .. ") - ".. v)
end

When comparing nil, you should add double quotes ":

> type(X)
nil
> type(X) == nil
false
> type(X) == "nil"
true
>

The result of type(X) == nil is false The reason is that type(X) actually returns the "nil" string, which is a string type:

type(type(X)) == string

boolean (boolean)

The boolean type has only two optional values: true (true) and false (false), Lua treats false and nil as false, and the rest as true, and the number 0 is also true:

print(type(true))
print(type(false))
print(type(nil))
 
if false or nil then
    print("At least one is true")
else
    print("false and nil are both false")
end
if 0 then
    print("The number 0 is true")
else
    print("The number 0 is false")
end

The execution result of the above code is as follows:

$ lua test.lua 
boolean
boolean
nil
false and nil are both false
The number 0 is true

number (number)

Lua has only one number type by default -- double (double precision) type (the default type can be modified in luaconf.h), the following formats are all considered as number types:

print(type(2))
print(type(2.2))
print(type(0.2))
print(type(2e+1))
print(type(0.2e-1))
print(type(7.8263692594256e-06))

The execution result of the above code is:

number
number
number
number
number
number

string (string)

Strings are represented by a pair of double quotes or single quotes.

string1 = "this is string"1"
string2 = 'this is string'2'

You can also use 2 Use a pair of square brackets "[[]]" to represent 'a block' of string.

Online Example

html = [[
<html>
<head></head>
<body>
    <a href="http://www.oldtoolbag.com/">Basic Tutorial Website</a>
</body>
</html>
]
print(html)
The execution result of the following code is:
<html>
<head></head>
<body>
    <a href="http://www.oldtoolbag.com/">Basic Tutorial Website</a>
</body>
</html>

When Lua performs arithmetic operations on a numeric string, it attempts to convert this numeric string into a number:

> print("2" + 6)
8.0
> print("2" + "6")
8.0
> print("2 + 6")
2 + 6
> print("-2e2" * "6")
-1200.0
> print("error" + 1)
stdin:1: attempt to perform arithmetic on a string value
stack traceback:
        stdin:1: in main chunk
        [C]: in ?
>

The 'error' in the above code + 1Execution failed, string concatenation uses .., for example:

> print("a" .. 'b')
ab
> print(157 .. 428)
157428
>

Use # to calculate the length of a string, place it in front of the string, as shown in the following example:

> len = "www.oldtoolbag.com"
> print(#len)
14
> print(#"www.oldtoolbag.com"
14
>

table(table)

In Lua, the creation of a table is done through a "construction expression", the simplest construction expression is {}, used to create an empty table. You can also add some data directly to initialize the table:

-- Create an empty table
local tbl1 = {}
 
-- Directly initialize the table
local tbl2 = {"apple", "pear", "orange", "grape"}

In Lua, a table is actually an "associative array", where the index of the array can be a number or a string.

-- table_test.lua script file
a = {}
a["key"] = "value"
key = 10
a[key] = 22
a[key] = a[key] + 11
for k, v in pairs(a) do
    print(k .. " : " .. v)
end

The script execution result is:

$ lua table_test.lua 
key : value
10 : 33

Unlike arrays in other languages that use 0 as the initial index, in Lua, the default initial index of tables is generally 1 Start.

-- table_test2.lua script file
local tbl = {"apple", "pear", "orange", "grape"}
for key, val in pairs(tbl) do
    print("Key", key)
end

The script execution result is:

$ lua table_test2.lua 
Key    1
Key    2
Key    3
Key    4

Tables in Lua do not have a fixed length size; when new data is added, the table length will automatically increase, and all initial tables are nil.

-- table_test3.lua script file
a3 = {}
for i = 1, 10 do
    a3[i] = i
end
a3["key"] = "val"
print(a3["key"])
print(a3["none"])

The script execution result is:

$ lua table_test3.lua 
val
nil

function(function)

In Lua, functions are considered as "first-class values (First-Class Value)",the function can exist in a variable:

-- function_test.lua script file
function factorial1(n)
    if  n  ==  0  then
        return 1
    else
        return  n * factorial1(n - 1)
    end
end
print(factorial1(5))
factorial2 =  factorial1
print(factorial2(5))

The script execution result is:

$ lua function_test.lua 
120
120

Functions can be passed as anonymous functions (anonymous function) through parameters:

-- function_test2.lua script file
function  testFun(tab,fun)
        for  k  ,v  in  pairs(tab)  do
                print(fun(k,v));
        end
end
tab={key1="val1",key2="val2"};
testFun(tab,
function(key,val)--Anonymous Function
        return  key.."="..val;
end
);

The script execution result is:

$ lua function_test2.lua 
key1 =  val1
key2 =  val2

thread (thread)

In Lua, the most important thread is the coroutine. It is similar to a thread, having its own independent stack, local variables, and instruction pointer, and can share global variables and most other things with other coroutines.

Difference between threads and coroutines: threads can run simultaneously, while coroutines can only run one at a time, and a coroutine in the running state will only pause when it is suspended.

userdata (custom type)

userdata is a user-defined data type used to represent a type provided by an application or C/C++ language library to create types, which can hold any C/C++ of any data type (usually struct and pointer) to Lua variables.