返回介绍

lua_CFunction

发布于 2019-08-25 13:16:47 字数 1461 浏览 1095 评论 0 收藏 0

typedef int (*lua_CFunction) (lua_State *L);

Type for C functions.

In order to communicate properly with Lua, a C function must use the following protocol, which defines the way parameters and results are passed: a C function receives its arguments from Lua in its stack in direct order (the first argument is pushed first). So, when the function starts, lua_gettop(L) returns the number of arguments received by the function. The first argument (if any) is at index 1 and its last argument is at index lua_gettop(L). To return values to Lua, a C function just pushes them onto the stack, in direct order (the first result is pushed first), and returns the number of results. Any other value in the stack below the results will be properly discarded by Lua. Like a Lua function, a C function called by Lua can also return many results.

As an example, the following function receives a variable number of numerical arguments and returns their average and sum:

 static int foo (lua_State *L) {
 int n = lua_gettop(L); /* number of arguments */
 lua_Number sum = 0;
 int i;
 for (i = 1; i <= n; i++) {
 if (!lua_isnumber(L, i)) {
 lua_pushstring(L, "incorrect argument to function 'average'");
 lua_error(L);
 }
 sum += lua_tonumber(L, i);
 }
 lua_pushnumber(L, sum/n); /* first result */
 lua_pushnumber(L, sum); /* second result */
 return 2; /* number of results */
 }

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文