lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


>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