简单 Lua Icxx 示例 |
|
/*
* The lua-icxx (C++) equivalent of API example at
* https://lua-users.lua.ac.cn/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 解释器)。