2017-04-13 4 views
1

とPCALL私はLuaのスクリプトをロードしています:ルア - "エントリーポイント"

lua_State * L = lua_open(); 
luaL_openlibs(L); 

const char lua_script[] = "function sum(a, b) return a+b; end print(\"_lua_\")"; 
int load_stat = luaL_loadbuffer(L,lua_script,strlen(lua_script),lua_script); 
lua_pcall(L, 0, 0, 0); 

今、私は

lua_getglobal(L,"sum"); 

を呼び出すことができますし、C-側

上でそれに起因しますがlua_pcallを呼び出すと、スクリプトが実行され、コンソールには "_lua_"という出力が表示されます。 lua_pcallがなければ、後でlua_getglobalにアクセスできません。これを回避する方法はありますか? lua_getglobalで「エントリポイント」機能を設定する前にlua_pcallに電話したいとは思わない。

+2

'lua_pcall'を実行中にメッセージを隠すために' print'を一時的に再定義します –

答えて

2

スクリプトを変更することができた場合は、これに異なるアプローチがそうのように、別の関数にあなたの初期化コード(printおよび任意の他があるかもしれない)をパックすることである:、今

lua_State * L = lua_open(); 
luaL_openlibs(L); 

const char lua_script[] = "function sum(a,b) return a+b end return function() print'_lua_' end"; 
int load_stat = luaL_loadbuffer(L,lua_script,strlen(lua_script),lua_script); 
lua_pcall(L, 0, 1, 0); // run the string, defining the function(s)… 
// also puts the returned init function onto the stack, which you could just leave 
// there, save somewhere else for later use, … then do whatever you need, e.g. 
    /* begin other stuff */ 
    lua_getglobal(L, "sum"); 
    lua_pushinteger(L, 2); 
    lua_pushinteger(L, 3); 
    lua_pcall(L, 2, 1, 0); 
    printf("2+3=%d\n", lua_tointeger(L,-1)); 
    lua_pop(L, 1); 
    /* end other stuff (keep stack balanced!) */ 
// and then run the init code: 
lua_pcall(L, 0, 0, 0); // prints "_lua_" 

しばらくあなたはまだ関数を定義するためにチャンクを実行しなければなりません。他の初期化コードは、あなたが後で実行することができる関数/ /変更された環境で返されます。 case。)

+1

類似のアイデア:inser 'function sum()... end'の後ろに' coroutine.yield() 'を置き、このチャンクをコルーチンとして使用します。 –

1

関数sumは、関数定義がLuaの代入関数であり、実行する必要があるため、スクリプトを実行するまで定義されていません。

したがって、sumを定義するスクリプトの実行を避ける方法はありません。それはlua_pcallのことです。 lua_callを使用できますが、エラーを処理することはできません。