Lua 中值的最小大小是多少

What is the minimum size of a value in Lua

值在 Lua 中的最小大小是多少?例如一个数字。

此知识在计算值数组的大小时特别有用。

这是 Lua 5.3 中定义 Value 的方式:

#define TValuefields    Value value_; int tt_

/*
** Tagged Values. This is the basic representation of values in Lua,
** an actual value plus a tag with its type.
*/

/*
** Union of all Lua values
*/
typedef union Value {
  GCObject *gc;    /* collectable objects */
  void *p;         /* light userdata */
  int b;           /* booleans */
  lua_CFunction f; /* light C functions */
  lua_Integer i;   /* integer numbers */
  lua_Number n;    /* float numbers */
} Value;


#define TValuefields    Value value_; int tt_


typedef struct lua_TValue {
  TValuefields;
} TValue;

GCObject 定义如下:

/*
** Common type for all collectable objects
*/
typedef struct GCObject GCObject;


/*
** Common Header for all collectable objects (in macro form, to be
** included in other objects)
*/
#define CommonHeader    GCObject *next; lu_byte tt; lu_byte marked


/*
** Common type has only the common header
*/
struct GCObject {
  CommonHeader;
};

lu_byte:

/* chars used as small naturals (so that 'char' is reserved for characters) */
typedef unsigned char lu_byte;

lua_CFunction:

/*
** Type for C functions registered with Lua
*/
typedef int (*lua_CFunction) (lua_State *L);

lua_Integer:

/* type for integer functions */
typedef LUA_INTEGER lua_Integer;

定义LUA_INTEGER depends on the platform and build settings但通常是64位有符号整数。

lua_Number:

/* type of numbers in Lua */
typedef LUA_NUMBER lua_Number;

LUA_NUMBER 也取决于配置和平台,但通常是 double.

因此要获得最小大小,您必须计算以下内容(假设所有指针类型具有相同的长度):

max(sizeof(pointer), sizeof(int), sizeof(LUA_INTEGER), sizeof(LUA_NUMBER)) + sizeof(int) + padding

在 x86_64 这通常是:

sizeof(pointer) + sizeof(int) + padding  = 8 + 4 + 4 = 16

32 位 x86:

sizeof(double) + sizeof(int) + padding = 8 + 4 + 4 = 16