title: Generic solution to get simple values from lua file into c++
body: <p>I'm trying to use a Lua file as a config or an ini. I have succeeded but my solution irritates me. Specifically, <code>get_double</code>, <code>get_int</code> and <code>get_string</code> functions needs to be done in a reusable way.</p>
  
  <p>I ran into problems creating function templates that don't have arguments.
  Also, I'm not sure how to generalize <code>lua_is...</code> and <code>lua_to...</code>. My idea was to us <code>if(is_same&lt;T,double&gt;::value) return (double)lua_isnumber(L,-1);</code> but it didn't work.</p>
  
  <p>Here is the working code:</p>
  
  <p>main.cc:</p>
  
  <pre><code>#include &lt;iostream&gt;
  #include &lt;lua.hpp&gt;
  
  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 &lt;&lt; "error: " &lt;&lt; var_name &lt;&lt; " 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 &lt;&lt; "error: " &lt;&lt; var_name &lt;&lt; " 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 &lt;&lt; "error: " &lt;&lt; var_name &lt;&lt; " 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 &lt;&lt; "error: " &lt;&lt; lua_tostring(L,-1) &lt;&lt; "\n";
      }
      lua_pushnil(L);
    }
    ~Lua_vm() {
      lua_close(L);
    }
  };
  int main(int argc, char** argv)
  {
    Lua_vm lvm("config.lua");
  
    cout &lt;&lt; "vol is " &lt;&lt; lvm.get_double("vol") &lt;&lt; "\n";
    cout &lt;&lt; "rho is " &lt;&lt; lvm.get_int("rho") &lt;&lt; "\n";
    cout &lt;&lt; "method is " &lt;&lt; lvm.get_string("method") &lt;&lt; "\n";
  
    return 0;
  }
  </code></pre>
  
  <p>config.lua:</p>
  
  <pre><code>method = "cube"
  len = 3.21
  rho = 13
  vol = len*len*len
  mass = vol*rho
  </code></pre>
  
  <p>It compiles with <code>g++ main.C -I/usr/include/lua5.1/ -llua5.1 ; ./a.out</code></p>