Calling individual functions

classic Classic list List threaded Threaded
2 messages Options
Reply | Threaded
Open this post in threaded view
|

Calling individual functions

Lance Boudreaux
This may be a bit of a novice question but I only recently began using Lua.  I would like to know if anyone could provide me with some sample code showing how a function is read and called if it inside a lua file from C or C++.  I can get Lua to execute a file but I would like to make library like files that can be called from C++.  As an example, a function that calculates Miles to KM.  I would like to simply call the function from C++ and receive the answers on the stack.

thanks,
Lance
__________________________________________________________________
Get your own FREE, personal Netscape Webmail account today at http://webmail.netscape.com/

Reply | Threaded
Open this post in threaded view
|

Re: Calling individual functions

Luiz Henrique de Figueiredo
>This may be a bit of a novice question but I only recently began using Lua.  I would like to know if anyone could provide me with some sample code showing how a function is read and called if it inside a lua file from C or C++.  I can get Lua to execute a file but I would like to make library like files that can be called from C++.  As an example, a function that calculates Miles to KM.  I would like to simply call the function from C++ and receive the answers on the stack.

file f.lua:

function miles_to_km(m)
 return 1.6*m
end

file t.c:

lua_dofile(L,"f.lua");		/* this just defines miles_to_km */

lua_getglobal(L,"miles_to_km");
lua_pushnumber(L,mymiles);
lua_call(L,1,1);
printf("%g miles = %g km\n",mymiles, lua_tonumber(L,-1));

I hope this helps.
--lhf