簡易 Lua Icxx 範例 |
|
/* * The lua-icxx (C++) equivalent of API example at * https://lua-users.dev.org.tw/wiki/SimpleLuaApiExample. * Oliver Schoenborn, Jul 2011 */ #include "lua_icxx/lua_icxx.h" #include "iof/fmtr.hpp" #include <iostream> int main() { LuaInterpreter L; /* Load the file containing the script we are going to run */ LuaFuncRef chunk = L.chunkFromFile("sample1.lua"); if ( chunk.isError() ) { std::cerr << "Couldn't load file: " << chunk.getErrMsg() << std::endl; exit(1); } LuaTableRef table = L.newTable(); for (int i = 1; i <= 5; i++) table[i] = i*2; /* By what name is the script going to reference our table? */ L.setGlobal("foo", table); /* Ask Lua to run our little script */ LuaTempResult res = chunk(); if ( res.isError() ) { std::cerr << "Failed to run script: " << res.getErrMsg() << std::endl; exit(1); } /* Get the returned value at the top of the stack (index -1) */ double sum = res[1]; // following line uses the iof library (ioflib.sf.net) for printf-output in c++ std::cout << iof::fmtr("Script returned: %.0fs") << sum << std::endl; return 0; }
在版本 1.x 中,lua-icxx 僅支援部分的 Lua C API,但 C API 可與 lua-icxx 搭配使用。擴充 lua-icxx 以涵蓋更多 C API 很容易,請發電子郵件給作者 (schoenborno@users.sf.net)。
如果您好奇 lua-icxx 為何不提供從 Lua 繫結至 C++ 程式碼的方式,那是因為這能透過 SWIG 和 tolua++ 等其他工具達成。lua-icxx 提供的是那些和其他繫結函式庫通常不提供的功能(從 C++ 應用程式輕鬆存取 Lua 詮譯器)。