http://blog.csdn.net/cnjet/article/details/5909519
Calling Lua function from C + + is very simple. Value passing between C + + Lua goes through stack, LUA C API provides a convenience ways for the call Lua function f Rom 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 is 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:
05 |
# #include "lauxlib.h" |
11 |
lua_State *L = lua_open(); |
13 |
if (luaL_loadfile(L, "last.lua" ) || lua_pcall(L, 0, 0, 0)) { |
14 |
printf ( "error: %s" , lua_tostring(L, -1)); |
18 |
lua_getglobal(L, "f" ); |
19 |
if (!lua_isfunction(L,-1)) |
24 |
lua_pushnumber(L, 21); /* push 1st argument */ |
25 |
lua_pushnumber(L, 31); /* push 2nd argument */ |
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)); |
34 |
if (!lua_isnumber(L, -1)) { |
35 |
printf ( "function `f‘ must return a number/n" ); |
38 |
z = lua_tonumber(L, -1); |
39 |
printf ( "Result: %f/n" ,z); |
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 has 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 + +