What is the type() function in LUA?
Overview
The LUA programming language has a number of data types. They include the following:
- nil
- boolean
- number
- string
- function
- table
The purpose of knowing these data types is to learn about the type function that returns a value of any of these data types.
The type() function will accept a value of any type, check for what data type it is, and return its name as a string. The type() function returns the type of its only argument set as a string.
Syntax
Let’s view the syntax of the function:
type(value)
Parameter
value: This is the only parameter of this function. It is the value whose data type is being checked.
Return value
The type() function returns the data type of its only argument, set as a string. These values can be any of the following:
"nil"(as a string, not the actual value)numberstringbooleantablefunctionthreaduserdata
Code
In the code snippet below, we check for the data types of each variable:
--declare variablesboolVal = true;int_value = 1024;stringVal = "hello world";floatVal = 12.90;--display the data type returned for each declared value.print(type(boolVal));print(type(int_value));print(type(stringVal));print(type(floatVal));print(type(nilVal));
Explanation
- Line 3: We declare a boolean value.
- Line 4: We declare an integer number value.
- Line 5: We declare a string value.
- Line 6: We declare a float number variable.
- Lines 9–13: We use the
type()built-in routine to get the type of the earlier declared variables and print the outcome to display.