此 C++ 代码段的语法是什么?

what's the syntax of this c++ snippets?

本文关键字:语法 是什么 C++ 代码      更新时间:2023-10-16

经过多年的java,javascript,python,我不仅忘记了C++,而且还混淆了语法。

http://heavycoder.com/tutorials/lua_embed.php

static const luaL_reg lualibs[] =
{
        { "base",       luaopen_base },
        { NULL,         NULL }
};

lualibs 初始化 2D 数组? luaL_reg是一种类型,但显然不是数组,

const luaL_reg *lib;
for (lib = lualibs; lib->func != NULL; lib++)
{
    lib->func(l);
    lua_settop(l, 0);
}

luaL_reg可能如下所示。

typedef struct luaL_reg_t {
  char const * const name;
  void(*func)(< type_of_<l> >);
} luaL_reg;

可以使用{}设置对象的成员,如以下示例所示,它将成员name设置为指向"hello world"的位置,func具有my_function的地址。

luaL_reg obj = {"hello world", my_function};

在初始化数组成员时,也可以使用上一代码片段中显示的语法。在下面的代码片段中,const luaL_reg 实例数组设置为包含两个对象,第一个对象具有 name = "base"func设置为 luaopen_base

为了清楚起见;下面的不是 2D 数组,而是使用 {} 初始化的const luaL_reg数组,以设置每个实例的成员。

static const luaL_reg lualibs[] =
{
  { "base",       luaopen_base },
  { NULL,         NULL }
};

最后一个元素用于简化数组的迭代,将两个成员都设置为 NULL 可以很容易地看到我们何时到达最后一个元素。

即将到来的代码段中的循环利用了这一点。只要成员func不等于NULL我们就没有到达数组的末尾。

for (lib = lualibs; lib->func != NULL; lib++) {
  lib->func(l);
  lua_settop(l, 0);
} 

luaL_reg是一个包含 2 个元素的struct,这就是快速谷歌搜索的结果。

第一个代码片段是创建一个luaL_reg struct数组:

  • 第一个struct使用以下两个值进行初始化:{ "base", luaopen_base }
  • 数组中的第二个luaL_reg struct设置为:{ NULL, NULL }

最重要的是,它是一个 2D 数组,而是一个 structs 数组,其中每个struct包含两个元素。

第二个例子现在应该是相当不言自明的; lib 是指向luaL_reg struct的指针。