Created
April 8, 2011 13:38
-
-
Save wichert/909848 to your computer and use it in GitHub Desktop.
C++ Lua wrapper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <lua.hpp> | |
class Lua { | |
public: | |
static class Nil { Nil(); } nil; | |
Lua() { | |
L=luaL_newstate(); | |
} | |
~Lua() { | |
lua_close(L); | |
} | |
operator lua_State*() { | |
return L; | |
} | |
bool istable(int index) { | |
return lua_istable(L, index); | |
} | |
template <typename T> | |
bool is(int index); | |
template <typename T> | |
T to(int index); | |
template <typename T> | |
T getfield(int index, const char* name) { | |
lua_getfield(L, index, name); | |
T result = to<T>(-1); | |
pop(); | |
return result; | |
} | |
int gettop() { | |
return lua_gettop(L); | |
} | |
void pushnil() { | |
lua_pushnil(L); | |
} | |
void pop(int n=1) { | |
lua_pop(L, n); | |
} | |
protected: | |
lua_State *L; | |
}; | |
template<> | |
bool Lua::is<Lua::Nil>(int index) { | |
return lua_isnil(L, index); | |
} | |
template<> | |
bool Lua::is<bool>(int index) { | |
return lua_isboolean(L, index); | |
} | |
template<> | |
bool Lua::is<std::string>(int index) { | |
return lua_isstring(L, index); | |
} | |
template<> | |
bool Lua::is<const char*>(int index) { | |
return lua_isstring(L, index); | |
} | |
template<> | |
bool Lua::to<bool>(int index) { | |
return lua_toboolean(L, index); | |
} | |
template<> | |
int Lua::to<int>(int index) { | |
return lua_tointeger(L, index); | |
} | |
template<> | |
double Lua::to<double>(int index) { | |
return lua_tonumber(L, index); | |
} | |
template <> | |
const char* Lua::to<const char*>(int index) { | |
return lua_tostring(L, index); | |
} | |
template <> | |
std::string Lua::to<std::string>(int index) { | |
size_t height; | |
const char* buf; | |
if ((buf=lua_tolstring(L, index, &height))==NULL) | |
return std::string(); | |
return std::string(buf, height); | |
} | |
Lua& operator<<(Lua& lua, const Lua::Nil nil) { | |
lua_pushnil(lua); | |
return lua; | |
} | |
Lua& operator<<(Lua& lua, bool value) { | |
lua_pushboolean(lua, static_cast<int>(value)); | |
return lua; | |
} | |
Lua& operator<<(Lua& lua, int value) { | |
lua_pushinteger(lua, value); | |
return lua; | |
} | |
Lua& operator<<(Lua& lua, double value) { | |
lua_pushnumber(lua, value); | |
return lua; | |
} | |
Lua& operator<<(Lua& lua, const char* value) { | |
lua_pushlstring(lua, value, strlen(value)); | |
return lua; | |
} | |
Lua& operator<<(Lua& lua, const std::string &value) { | |
lua_pushlstring(lua, value.c_str(), value.length()); | |
return lua; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment