2016-08-30 43 views
4

一個Lua腳本給定一個LUA文件中像通過電話由C

-- foo.lua 
return function (i) 
    return i 
end 

我怎樣才能加載該文件與C API調用和返回的函數返回的功能? 我只需要以luaL_loadfile/luaL_dostring開頭的函數調用。

回答

3

A loaded塊只是一個常規功能。加載從C模塊可以這樣認爲:

return (function() -- this is the chunk compiled by load 

    -- foo.lua 
    return function (i) 
     return i 
    end 

end)() -- executed with call/pcall 

所有你需要做的就是加載塊,並調用它,它的返回值是你的函數:

// load the chunk 
if (luaL_loadstring(L, script)) { 
    return luaL_error(L, "Error loading script: %s", lua_tostring(L, -1)); 
} 

// call the chunk (function will be on top of the stack) 
if (lua_pcall(L, 0, 1, 0)) { 
    return luaL_error(L, "Error running chunk: %s", lua_tostring(L, -1)); 
} 

// call the function 
lua_pushinteger(L, 42); // function arg (i) 
if (lua_pcall(L, 1, 1, 0)) { 
    return luaL_error(L, "Error calling function: %s", lua_tostring(L, -1)); 
} 
+0

啊,謝謝,這是一個非常有用的'塊'語義。實際上,到目前爲止,我嘗試過的其中一個版本是相似的,只不過我第一次打電話是'lua_pcall(L,0,0)',它丟棄了結果。這讓我想知道爲什麼沒有回報價值。 –