返回介绍

lua_call

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

void lua_call (lua_State *L, int nargs, int nresults);

Calls a function.

To call a function you must use the following protocol: first, the function to be called is pushed onto the stack; then, the arguments to the function are pushed in direct order; that is, the first argument is pushed first. Finally you call lua_call; nargs is the number of arguments that you pushed onto the stack. All arguments and the function value are popped from the stack when the function is called. The function results are pushed onto the stack when the function returns. The number of results is adjusted to nresults, unless nresults is LUA_MULTRET. In this case, all results from the function are pushed. Lua takes care that the returned values fit into the stack space. The function results are pushed onto the stack in direct order (the first result is pushed first), so that after the call the last result is on the top of the stack.

Any error inside the called function is propagated upwards (with a longjmp).

The following example shows how the host program may do the equivalent to this Lua code:

 a = f("how", t.x, 14)

Here it is in C:

 lua_getfield(L, LUA_GLOBALSINDEX, "f"); /* function to be called */
 lua_pushstring(L, "how"); /* 1st argument */
 lua_getfield(L, LUA_GLOBALSINDEX, "t"); /* table to be indexed */
 lua_getfield(L, -1, "x"); /* push result of t.x (2nd arg) */
 lua_remove(L, -2); /* remove 't' from the stack */
 lua_pushinteger(L, 14); /* 3rd argument */
 lua_call(L, 3, 1); /* call function with 3 arguments and 1 result */
 lua_setfield(L, LUA_GLOBALSINDEX, "a"); /* set global variable 'a' */

Note that the code above is "balanced": at its end, the stack is back to its original configuration. This is considered good programming practice.

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

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

发布评论

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