Calling Lua function from C++

來源:互聯網
上載者:User

標籤:

http://blog.csdn.net/cnjet/article/details/5909519

 

Calling Lua function from c++ is very simple. Value passing between c++ and Lua goes through stack, Lua C API provides a convenience ways for you to call Lua function from C. To call Lua function, you need to specify:

1. Function Name.
2. Parameters of function call.
3. Return values expected ( Lua function support multiple results reture)

Let say my lua function name call f in last.lua, takes 2 parameters.

-- last.luafunction f (x, y)    return (x^2 * math.sin(y))/(1 - x)end

I perform function call from c++ like this:

01 //last.cc
02 # extern "C" {
03 # #include "lua.h"
04 # #include "lualib.h"
05 # #include "lauxlib.h"
06 # } 
07  
08 int main()
09 {
10     double z;
11     lua_State *L = lua_open();
12     luaL_openlibs(L);
13     if (luaL_loadfile(L, "last.lua") || lua_pcall(L, 0, 0, 0)) {
14         printf("error: %s", lua_tostring(L, -1));
15         return -1;
16     }
17  
18     lua_getglobal(L, "f");
19     if(!lua_isfunction(L,-1))
20     {
21         lua_pop(L,1);
22         return -1;
23     }
24     lua_pushnumber(L, 21);   /* push 1st argument */
25     lua_pushnumber(L, 31);   /* push 2nd argument */
26  
27     /* do the call (2 arguments, 1 result) */
28     if (lua_pcall(L, 2, 1, 0) != 0) {
29         printf("error running function `f‘: %s/n",lua_tostring(L, -1));
30         return -1;
31     }
32  
33     /* retrieve result */
34     if (!lua_isnumber(L, -1)) {
35         printf("function `f‘ must return a number/n");
36         return -1;
37     }
38     z = lua_tonumber(L, -1);
39     printf("Result: %f/n",z);
40     lua_pop(L, 1);
41     lua_close(L);
42  
43     return 0;
44 }

Compile it with g++ like this:

g++ -o last{,.cc} -llua -ldl

The results:

Result: -12.158958

Brief explanation of the C++ codes above:
First, I trigger lua_getglobal to get the function name, then I push 2 parameters to stack. I make lua_pcall by telling Lua I have 2 params and expect 1 value return. Upon success, I retrieve the return value from the top of the stack.

Calling Lua function from C++

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.