Lua 5.2 関数を C++ から呼び出すのに問題があります。
これは Lua チャンク (名前は test.lua) です。
function testFunction ()
print "Hello World"
end
そして、これはC++です:
int iErr = 0;
//Create a lua state
lua_State *lua = luaL_newstate();
// Load io library
luaopen_io (lua);
//load the chunk we want to execute (test.lua)
iErr = luaL_loadfile(lua, "test.lua");
if (iErr == 0) {
printf("successfully loaded test.lua\n");
// Push the function name onto the stack
lua_getglobal(lua, "testFunction");
printf("called lua_getglobal. lua stack height is now %d\n", lua_gettop(lua));
//Call our function
iErr = lua_pcall(lua, 0, 0, 0);
if (iErr != 0) {
printf("Error code %i attempting to call function: '%s'\n", iErr, lua_tostring(lua, -1));
}
} else {
printf("Error loading test.lua. Error code: %s\n", lua_tostring(lua, -1));
}
lua_close (lua);
トレースすると、test.lua スクリプトが正常にロードされていることがわかります (エラーは返されません)。関数名を指定して lua_getglobal を呼び出した後、スタックの高さが 3 であることを示しています。
ただし、lua_pcall でエラー コード 2: 'attempt to call a nil value' で失敗します。
Lua 5.2 コードの例をたくさん読んだことがありますが、どこが間違っているのかわかりません。これは間違いなく機能するはずです(私が読んだことによると)。
スペルと大文字と小文字の区別を確認しましたが、すべて一致しています。
私は何かを誤解していますか?