如何从 C 语言调用 Lua 函数?


从 C 语言调用 Lua 函数需要一系列步骤,并且需要掌握 Lua 库函数。无论何时我们想要从 C 语言调用 Lua 函数或反之,Lua 都提供了几个库函数供我们使用。

以下是一些从 C 语言调用 Lua 函数最常用的 Lua 库函数:

  • luaL_dofile(L, "myFile.lua");
  • lua_getglobal(L, "add");
  • lua_pushnumber(L, a);

等等。

当我们从 C 语言调用 Lua 函数时,我们将使用这些函数。

第一步是关闭 Lua 解释器,为此我们需要在 C 语言中编写代码。

示例

请考虑以下示例:

extern "C" {
   #include "lua.h"
   #include "lualib.h"
   #include "lauxlib.h"
}
int main(int argc, char *argv[]) {
   lua_State* L;
   L = luaL_newstate();
   luaL_openlibs(L);
   lua_close(L);
   printf( "Press enter to exit..." );
   getchar();
   return 0;
}

现在,我们只需要为包含我们将从 C 代码中调用的 Lua 代码的文件调用 luaL_dofile(L, "myFile.lua"); 函数。

请考虑以下代码,它写在 myFile.lua 中:

add = function(a,b)
return a + b
end

现在,将调用上述 Lua 函数的 C 文件将如下所示:

int luaAdd(lua_State* L, int a, int b) {
   // Push the add function on the top of the lua stack
   lua_getglobal(L, "add");
   // Push the first argument on the top of the lua stack
   lua_pushnumber(L, a);
   // Push the second argument on the top of the lua stack
   lua_pushnumber(L, b);
   // Call the function with 2 arguments, returning 1 result
   lua_call(L, 2, 1);
   // Get the result
   int sum = (int)lua_tointeger(L, -1);
   lua_pop(L, 1);
   return sum;
}

当我们在 C 语言中调用此 luaAdd() 函数时,输出将为:(对于 a = 2,b = 3)

5

更新于:2021 年 7 月 20 日

3K+ 浏览量

启动你的 职业生涯

通过完成课程获得认证

开始学习
广告

© . All rights reserved.