我正在尝试使用 Lua 文件作为配置或 ini。我成功了,但我的解决方案让我很恼火。具体来说,get_double
和get_int
函数get_string
需要以可重用的方式完成。
我在创建没有参数的函数模板时遇到了问题。另外,我不确定如何概括lua_is...
和lua_to...
. 我的想法是给我们的if(is_same<T,double>::value) return (double)lua_isnumber(L,-1);
,但它没有奏效。
这是工作代码:
主.cc:
#include <iostream>
#include <lua.hpp>
using namespace std;
class Lua_vm
{
private:
lua_State *L;
public:
double get_double(const char *var_name) {
lua_getglobal(L,var_name);
if (!lua_isnumber(L,-1)) {
cout << "error: " << var_name << " is of a wrong type\n";
}
return (double)lua_tonumber(L,-1);
lua_pop(L,1);
}
int get_int(const char *var_name) {
lua_getglobal(L,var_name);
if (!lua_isnumber(L,-1)) {
cout << "error: " << var_name << " is of a wrong type\n";
}
return (int)lua_tonumber(L,-1);
lua_pop(L,1);
}
string get_string(const char *var_name) {
lua_getglobal(L,var_name);
if (!lua_isstring(L,-1)) {
cout << "error: " << var_name << " is of a wrong type\n";
}
return string(lua_tostring(L,-1));
lua_pop(L,1);
}
Lua_vm(const char *lua_config_filename) {
L = lua_open();
if (luaL_loadfile(L, lua_config_filename) || lua_pcall(L, 0,0,0)) {
cout << "error: " << lua_tostring(L,-1) << "\n";
}
lua_pushnil(L);
}
~Lua_vm() {
lua_close(L);
}
};
int main(int argc, char** argv)
{
Lua_vm lvm("config.lua");
cout << "vol is " << lvm.get_double("vol") << "\n";
cout << "rho is " << lvm.get_int("rho") << "\n";
cout << "method is " << lvm.get_string("method") << "\n";
return 0;
}
配置.lua:
method = "cube"
len = 3.21
rho = 13
vol = len*len*len
mass = vol*rho
它编译为g++ main.C -I/usr/include/lua5.1/ -llua5.1 ; ./a.out