在Lua 5.1 Reference Manual 对于Lua 值和类型的介绍。Lua是一个动态语言,在Lua中变量仅仅有值而没有类型。所以在Lua中的变量不需要声明。所以的值本身包含类型。
其实Lua 包含一种运行时类型识别,通过type()函数,可以在运行时获取值的类型。
信息来自: Lua 5.1 Reference Manual Values and Types
Lua is a dynamically typed language. This means that variables do not have types; only values do. There are no type definitions in the language. All values carry their own type.
type (variables)
Returns the type of its only argument, coded as a string. The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".
在C语言特征本身,不提供运行时信息。C语言的拓展集,C++语言特征本身对运行时提供支持。在C++语言中通过typeid(),dynamic_case()等函数可以获取类型的内省信息。
在Java语言中,对内省信息支持强大,spring 等库就是通过内省信息来实现的强大库。在actionscript3.0中也提供了对类的内省信息。在游戏开发中,可以利用内省信息反射出类对象,包括游戏UI编辑器都是通过内省类信息来实现的。C# 是在C++,Java语言发展而来,同时也对运行时内省提供强大支持。对于这些语言的内省信息不详细赘述。
在Python脚本语言中,PyObject 类 实现机制与Lua lua_TValue 实现机制类型,都是通过类型值int 与值相绑定. 虽然,在python 和lua语言中,只存在值,不存在类型,但是通过语言提供的函数,可以在运行时获取到值的类型。
在Lua源代码中,节选出部分与运行时信息相关的代码:
在Lua源代码中提供了8中基本内置类型,随着Lua演化,Lua的基本内置类型变化不大。以后的文章中,就详细介绍Lua类型的演化历史。
/*
** basic types
*/
#define LUA_TNONE (-1)
#define LUA_TNIL 0
#define LUA_TBOOLEAN 1
#define LUA_TLIGHTUSERDATA 2
#define LUA_TNUMBER 3
#define LUA_TSTRING 4
#define LUA_TTABLE 5
#define LUA_TFUNCTION 6
#define LUA_TUSERDATA 7
#define LUA_TTHREAD 8
内置类型的实现,是通过值与类型相绑定来实现的。值是如何表示的,在Lua 作者的5.0实现介绍中有详细解释。
typedef struct lua_TValue
{
Value value_; //用来标示Lua的值类型,在lua作者5.0实现中有详细的介绍
int tt_; //用来标示类型,-1 -8 由上面宏定义
} TValue;
union Value
{
GCObject *gc; /* collectable objects */
void *p; /* light userdata */
int b; /* booleans */
lua_CFunction f; /* light C functions */
numfield /* numbers */
};
在Lua Code 运行时中,可以通过type()来获取值的类型:
type (v)
Returns the type of its only argument, coded as a string.
The possible results of this function are "nil" (a string, not the value nil), "number", "string", "boolean", "table", "function", "thread", and "userdata".&n