「luafunc.lua」にコードがあるとします。
function foo(a, b)
return a + b
end
a = io.read('*n')
b = io.read('*n')
print (foo(a, b))
C++ ファイルから関数 foo を使用してみましょう:
#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;
}
したがって、問題は、この C++ コードが luafunc.lua 全体を実行することです。当然、lua ファイルから読み取り部分を削除して、C++ からは foo のみを実行します。しかし、lua-file に他のものがあっても、C++ から関数 foo を使用できますか?