Let we have a code in "luafunc.lua":
function foo(a, b)
return a + b
end
a = io.read('*n')
b = io.read('*n')
print (foo(a, b))
Let's try to use function foo from C++ file:
#include <iostream>
using namespace std;
extern "C"{
#include <lua.h>
#include <lualib.h>
#include <lauxlib.h>
};
int main()
{
lua_State *lvm = lua_open();
luaL_openlibs(lvm);
luaL_loadfile(lvm, "luafunc.lua");
int a, b;
cin >> a >> b;
lua_pcall(lvm, 0, LUA_MULTRET, 0);
lua_getglobal(lvm, "foo");
lua_pushnumber(lvm, a);
lua_pushnumber(lvm, b);
if (lua_pcall(lvm, 2, 1, 0))
{
cout << "Error: " << lua_tostring(lvm, -1) << endl;
return 0;
}
cout << "The result is: " << lua_tonumber(lvm, -1) << endl;
lua_close(lvm);
return 0;
}
So, the problem is that this C++ code executes the whole luafunc.lua. Naturally I can remove reading part from lua-file and then from C++ only foo is executed. But can I use function foo from C++ even if there's other stuff in lua-file?