2017-04-13 21 views
1

我加載的Lua腳本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_" 

現在,雖然你仍然需要運行塊來定義函數,另一個初始化代碼作爲一個函數返回,你可以稍後運行/使用修改後的環境/ ...(或者根本不需要,如果你的代碼中沒有必要)

+1

類似思路:inser在'函數sum()... end'後加上''coroutine.yield()',並將這個塊用作協程。 –

1

函數sum在運行腳本之前未定義,因爲函數定義是Lua中的一個賦值,需要執行它。

因此,無法避免運行定義sum的腳本。這就是lua_pcall所做的。您可以使用lua_call,但那樣您將無法處理錯誤。