nngn
Loading...
Searching...
No Matches
state.h File Reference

lua_State wrappers. More...

#include <tuple>
#include <utility>
#include <vector>
#include "math/math.h"
#include "utils/fixed_string.h"
#include "utils/pp.h"
#include "utils/utils.h"
#include "lua.h"
#include "utils.h"
Include dependency graph for state.h:
This graph shows which files directly or indirectly include this file:

Go to the source code of this file.

Classes

class  nngn::lua::state_view
 
struct  nngn::lua::state
 Owning lua_State wrapper. More...
 
struct  nngn::lua::stack_get< state_view >
 

Namespaces

namespace  nngn
 
namespace  nngn::lua
 

Functions

template<typename T >
T nngn::lua::get (nngn::lua::state_view L, int i)
 
template<typename T = value_view>
T nngn::lua::push (nngn::lua::state_view lua, auto &&v)
 

Detailed Description

lua_State wrappers.

state_view and state are the main types in this library. They each contain a lua_State and provide a generic and strongly typed interface which closely mirrors the Lua API, with methods such as state_view::top, state_view::get_type, state_view::len, etc., all with generic and uniform handling of arguments. Convenience methods are also provided, such as state_view::do_string, state_view::print_stack, etc.

A new state can be initialized with:

state lua = {};
const bool ok = lua.init();
assert(ok);
state
Definition cathedral.lua:13
assert
Definition debug.lua:3

lua will contain the lua_State, which will be closed (i.e. lua_close) when the object is itself destroyed. Multiple state_views can be created from an existing state (or directly from a lua_State): these are non-owning but provide the same interface.

state_view can also be used as an argument in C/++ functions registered in Lua. This is a convenient way to receive the current lua_State:

lua.call([](state_view l) { l.globals()["g"] = true; });
assert(lua.globals()["g"] == true);
local l
Definition light.lua:23

Examples

// Initialize
state lua = {};
lua.init();
// Push and get stack values.
const auto t = lua.push(42).get_type();
assert(lua.top() == 1);
assert(t == type::number);
lua.push("test");
assert(lua.len(-1) == 4);
// Manipulate the global table.
lua.globals()["g"] = "g";
assert(lua.globals()["g"] == "g"sv);
// Convenience methods.
lua.dostring("f = function() end");
lua.push(lua.globals()["f"]);
lua.print_stack();
// print_stack: top: 3
// 3 function (function: 0x01234567)
// 2 string (h)
// 1 number (42)
lua.create_table();
std::cout << lua.to_string(-1).second << '\n';
// table: 0x01234567