tutorial: quick ‘n’ dirty

These are all the things. Use your browser’s search to find things you want.

You’ll need to #include <sol.hpp>/#include "sol.hpp" somewhere in your code. Sol is header-only, so you don’t need to compile anything.

Note

After you learn the basics of sol, it is usually advised that if you think something can work, you should TRY IT. It will probably work!

Note

All of the code below is available at the sol2 tutorial examples.

opening a state

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>

#include <iostream>
#include <cassert>

int main(int, char*[]) {
	std::cout << "=== opening a state example ===" << std::endl;

	sol::state lua;
	// open some common libraries
	lua.open_libraries(sol::lib::base, sol::lib::package);
	lua.script("print('bark bark bark!')");

	std::cout << std::endl;

	return 0;
}

using sol2 on a lua_State*

For your system/game that already has Lua or uses an in-house or pre-rolled Lua system (LuaBridge, kaguya, Luwra, etc.), but you’d still like sol2 and nice things:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>

#include <iostream>

int use_sol2(lua_State* L) {
	sol::state_view lua(L);
	lua.script("print('bark bark bark!')");
	return 0;
}

int main(int, char*[]) {
	std::cout << "=== opening sol::state_view on raw Lua example ===" << std::endl;

	lua_State* L = luaL_newstate();
	luaL_openlibs(L);

	lua_pushcclosure(L, &use_sol2, 0);
	lua_setglobal(L, "use_sol2");

	if (luaL_dostring(L, "use_sol2()")) {
		lua_error(L);
		return -1;
	}

	std::cout << std::endl;

	return 0;
}

running lua code

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>

#include <fstream>
#include <iostream>
#include <cassert>

int main(int, char*[]) {
	std::cout << "=== running lua code example ===" << std::endl;

	sol::state lua;
	lua.open_libraries(sol::lib::base);
	
	// load and execute from string
	lua.script("a = 'test'");
	// load and execute from file
	lua.script_file("a_lua_script.lua");

	// run a script, get the result
	int value = lua.script("return 54");
	assert(value == 54);

To run Lua code but have an error handler in case things go wrong:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
	auto bad_code_result = lua.script("123 herp.derp", [](lua_State*, sol::protected_function_result pfr) {
		// pfr will contain things that went wrong, for either loading or executing the script
		// Can throw your own custom error
		// You can also just return it, and let the call-site handle the error if necessary.
		return pfr;
	});
	// it did not work
	assert(!bad_code_result.valid());
	
	// the default handler panics or throws, depending on your settings
	// uncomment for explosions:
	//auto bad_code_result_2 = lua.script("bad.code", &sol::script_default_on_error);

	std::cout << std::endl;

	{
		std::remove("a_lua_script.lua");
	}

	return 0;
}

set and get variables

You can set/get everything using table-like syntax.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>

#include <cassert>

int main(int, char*[]) {
	sol::state lua;
	lua.open_libraries(sol::lib::base);

	// integer types
	lua.set("number", 24);
	// floating point numbers
	lua["number2"] = 24.5;
	// string types
	lua["important_string"] = "woof woof";
	// is callable, therefore gets stored as a function that can be called
	lua["a_function"] = []() { return 100; };
	// make a table
	lua["some_table"] = lua.create_table_with("value", 24);

Equivalent to loading lua values like so:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
	// equivalent to this code
	std::string equivalent_code = R"(
		t = {
			number = 24,
			number2 = 24.5,
			important_string = "woof woof",
			a_function = function () return 100 end,
			some_table = { value = 24 }
		}
	)";

	// check in Lua
	lua.script(equivalent_code);

You can show they are equivalent:

1
2
3
4
5
6
7
	lua.script(R"(
		assert(t.number == number)
		assert(t.number2 == number2)
		assert(t.important_string == important_string)
		assert(t.a_function() == a_function())
		assert(t.some_table.value == some_table.value)
	)");

Retrieve these variables using this syntax:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
	// implicit conversion
	int number = lua["number"];
	assert(number == 24);
	// explicit get
	auto number2 = lua.get<double>("number2");
	assert(number2 == 24.5);
	// strings too
	std::string important_string = lua["important_string"];
	assert(important_string == "woof woof");
	// dig into a table
	int value = lua["some_table"]["value"];
	assert(value == 24);
	// get a function
	sol::function a_function = lua["a_function"];
	int value_is_100 = a_function();
	// convertible to std::function
	std::function<int()> a_std_function = a_function;
	int value_is_still_100 = a_std_function();
	assert(value_is_100 == 100);
	assert(value_is_still_100 == 100);

Retrieve Lua types using object and other sol:: types.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
	sol::object number_obj = lua.get<sol::object>("number");
	// sol::type::number
	sol::type t1 = number_obj.get_type();
	assert(t1 == sol::type::number);

	sol::object function_obj = lua["a_function"];
	// sol::type::function
	sol::type t2 = function_obj.get_type();
	assert(t2 == sol::type::function);
	bool is_it_really = function_obj.is<std::function<int()>>();
	assert(is_it_really);

	// will not contain data
	sol::optional<int> check_for_me = lua["a_function"];
	assert(check_for_me == sol::nullopt);

	return 0;
}

You can erase things by setting it to nullptr or sol::lua_nil.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#define SOL_CHECK_ARGUMENTS 1
#include <sol.hpp>

#include <cassert>

int main(int, char*[]) {
	sol::state lua;
	lua.open_libraries(sol::lib::base);

	lua.script("exists = 250");

	int first_try = lua.get_or("exists", 322);
	assert(first_try == 250);

	lua.set("exists", sol::lua_nil);
	int second_try = lua.get_or("exists", 322);
	assert(second_try == 322);

	return 0;
}

Note that if its a userdata/usertype for a C++ type, the destructor will run only when the garbage collector deems it appropriate to destroy the memory. If you are relying on the destructor being run when its set to sol::lua_nil, you’re probably committing a mistake.

tables

sol::state is a table too.

sol::state lua;

// Raw string literal for easy multiline
lua.script( R"(
        abc = { [0] = 24 }
        def = {
                ghi = {
                        bark = 50,
                        woof = abc
                }
        }
)"
);

sol::table abc = lua["abc"];
sol::table def = lua["def"];
sol::table ghi = lua["def"]["ghi"];

int bark1 = def["ghi"]["bark"];
int bark2 = lua["def"]["ghi"]["bark"];
// bark1 == bark2 == 50

int abcval1 = abc[0];
int abcval2 = ghi["woof"][0];
// abcval1 == abcval2 == 24

If you’re going deep, be safe:

sol::state lua;

sol::optional<int> will_not_error = lua["abc"]["DOESNOTEXIST"]["ghi"];
// will_not_error == sol::nullopt
int also_will_not_error = lua["abc"]["def"]["ghi"]["jklm"].get_or(25);
// is 25

// if you don't go safe,
// will throw (or do at_panic if no exceptions)
int aaaahhh = lua["boom"]["the_dynamite"];

make tables

Make some:

sol::state lua;

lua["abc"] = lua.create_table_with(
        0, 24
);

lua.create_named_table("def",
        "ghi", lua.create_table_with(
                "bark", 50,
                // can reference other existing stuff too
                "woof", lua["abc"]
        )
);

Equivalent Lua code:

abc = { [0] = 24 }
def = {
        ghi = {
                bark = 50,
                woof = abc
        }
}

You can put anything you want in tables as values or keys, including strings, numbers, functions, other tables.

Note that this idea that things can be nested is important and will help later when you get into namespacing.

functions

They’re great. Use them:

sol::state lua;

lua.script("function f (a, b, c, d) return 1 end");
lua.script("function g (a, b) return a + b end");

// sol::function is often easier:
// takes a variable number/types of arguments...
sol::function fx = lua["f"];
// fixed signature std::function<...>
// can be used to tie a sol::function down
std::function<int(int, double, int, std::string)> stdfx = fx;

int is_one = stdfx(1, 34.5, 3, "bark");
int is_also_one = fx(1, "boop", 3, "bark");

// call through operator[]
int is_three = lua["g"](1, 2);
// is_three == 3
double is_4_8 = lua["g"](2.4, 2.4);
// is_4_8 == 4.8

If you need to protect against errors and parser problems and you’re not ready to deal with Lua’s longjmp problems (if you compiled with C), use sol::protected_function.

You can bind member variables as functions too, as well as all KINDS of function-like things:

void some_function () {
        std::cout << "some function!" << std::endl;
}

void some_other_function () {
        std::cout << "some other function!" << std::endl;
}

struct some_class {
        int variable = 30;

        double member_function () {
                return 24.5;
        }
};

sol::state lua;
lua.open_libraries(sol::lib::base);

// put an instance of "some_class" into lua
// (we'll go into more detail about this later
// just know here that it works and is
// put into lua as a userdata
lua.set("sc", some_class());

// binds a plain function
lua["f1"] = some_function;
lua.set_function("f2", &some_other_function);

// binds just the member function
lua["m1"] = &some_class::member_function;

// binds the class to the type
lua.set_function("m2", &some_class::member_function, some_class{});

// binds just the member variable as a function
lua["v1"] = &some_class::variable;

// binds class with member variable as function
lua.set_function("v2", &some_class::variable, some_class{});

The lua code to call these things is:

f1() -- some function!
f2() -- some other function!

-- need class instance if you don't bind it with the function
print(m1(sc)) -- 24.5
-- does not need class instance: was bound to lua with one
print(m2()) -- 24.5

-- need class instance if you
-- don't bind it with the function
print(v1(sc)) -- 30
-- does not need class instance:
-- it was bound with one
print(v2()) -- 30

-- can set, still
-- requires instance
v1(sc, 212)
-- can set, does not need
-- class instance: was bound with one
v2(254)

print(v1(sc)) -- 212
print(v2()) -- 254

Can use sol::readonly( &some_class::variable ) to make a variable readonly and error if someone tries to write to it.

self call

You can pass the ‘self’ argument through C++ to emulate ‘member function’ calls in Lua.

sol::state lua;

lua.open_libraries(sol::lib::base, sol::lib::package, sol::lib::table);

// a small script using 'self' syntax
lua.script(R"(
some_table = { some_val = 100 }

function some_table:add_to_some_val(value)
    self.some_val = self.some_val + value
end

function print_some_val()
    print("some_table.some_val = " .. some_table.some_val)
end
)");

// do some printing
lua["print_some_val"]();
// 100

sol::table self = lua["some_table"];
self["add_to_some_val"](self, 10);
lua["print_some_val"]();

multiple returns from lua

sol::state lua;

lua.script("function f (a, b, c) return a, b, c end");

std::tuple<int, int, int> result;
result = lua["f"](100, 200, 300);
// result == { 100, 200, 300 }
int a;
int b;
std::string c;
sol::tie( a, b, c ) = lua["f"](100, 200, "bark");
// a == 100
// b == 200
// c == "bark"

multiple returns to lua

sol::state lua;

lua["f"] = [](int a, int b, sol::object c) {
        // sol::object can be anything here: just pass it through
        return std::make_tuple( a, b, c );
};

std::tuple<int, int, int> result = lua["f"](100, 200, 300);
// result == { 100, 200, 300 }

std::tuple<int, int, std::string> result2;
result2 = lua["f"](100, 200, "BARK BARK BARK!");
// result2 == { 100, 200, "BARK BARK BARK!" }

int a, b;
std::string c;
sol::tie( a, b, c ) = lua["f"](100, 200, "bark");
// a == 100
// b == 200
// c == "bark"

C++ classes from C++

Everything that is not a:

Is set as a userdata + usertype.

struct Doge {
        int tailwag = 50;
};

Doge dog{};

// Copy into lua: destroyed by Lua VM during garbage collection
lua["dog"] = dog;
// OR: move semantics - will call move constructor if present instead
// Again, owned by Lua
lua["dog"] = std::move( dog );
lua["dog"] = Doge{};
lua["dog"] = std::make_unique<Doge>();
lua["dog"] = std::make_shared<Doge>();
// Identical to above

Doge dog2{};

lua.set("dog", dog2);
lua.set("dog", std::move(dog2));
lua.set("dog", Doge{});
lua.set("dog", std::unique_ptr<Doge>(new Doge()));
lua.set("dog", std::shared_ptr<Doge>(new Doge()));

std::unique_ptr/std::shared_ptr‘s reference counts / deleters will be respected. If you want it to refer to something, whose memory you know won’t die in C++, do the following:

struct Doge {
        int tailwag = 50;
};

sol::state lua;
lua.open_libraries(sol::lib::base);

Doge dog{}; // Kept alive somehow

// Later...
// The following stores a reference, and does not copy/move
// lifetime is same as dog in C++
// (access after it is destroyed is bad)
lua["dog"] = &dog;
// Same as above: respects std::reference_wrapper
lua["dog"] = std::ref(dog);
// These two are identical to above
lua.set( "dog", &dog );
lua.set( "dog", std::ref( dog ) );

Get userdata in the same way as everything else:

struct Doge {
        int tailwag = 50;
};

sol::state lua;
lua.open_libraries(sol::lib::base);

Doge& dog = lua["dog"]; // References Lua memory
Doge* dog_pointer = lua["dog"]; // References Lua memory
Doge dog_copy = lua["dog"]; // Copies, will not affect lua

Note that you can change the data of usertype variables and it will affect things in lua if you get a pointer or a reference from Sol:

struct Doge {
        int tailwag = 50;
};

sol::state lua;
lua.open_libraries(sol::lib::base);

Doge& dog = lua["dog"]; // References Lua memory
Doge* dog_pointer = lua["dog"]; // References Lua memory
Doge dog_copy = lua["dog"]; // Copies, will not affect lua

dog_copy.tailwag = 525;
// Still 50
lua.script("assert(dog.tailwag == 50)");

dog.tailwag = 100;
// Now 100
lua.script("assert(dog.tailwag == 100)");

C++ classes put into Lua

See this section here and after perhaps see if simple usertypes suit your needs. Also check out some a basic example, special functions and initializers,

namespacing

You can emulate namespacing by having a table and giving it the namespace names you want before registering enums or usertypes:

struct my_class {
        int b = 24;

        int f () const {
                return 24;
        }

        void g () {
                ++b;
        }
};

sol::state lua;
lua.open_libraries();

// set up table
sol::table bark = lua.create_named_table("bark");

bark.new_usertype<my_class>( "my_class",
        "f", &my_class::f,
        "g", &my_class::g
); // the usual

// can add functions, as well (just like the global table)
bark.set_function("print_my_class", [](my_class& self) { std::cout << "my_class { b: " << self.b << " }" << std::endl; });

// 'bark' namespace
lua.script("obj = bark.my_class.new()" );
lua.script("obj:g()");
// access the function on the 'namespace'
lua.script("bark.print_my_class(obj)");

my_class& obj = lua["obj"];
// obj.b == 25

This technique can be used to register namespace-like functions and classes. It can be as deep as you want. Just make a table and name it appropriately, in either Lua script or using the equivalent Sol code. As long as the table FIRST exists (e.g., make it using a script or with one of Sol’s methods or whatever you like), you can put anything you want specifically into that table using sol::table’s abstractions.

there is a LOT more

Some more things you can do/read about:
  • the usertypes page lists the huge amount of features for functions
    • unique usertype traits allows you to specialize handle/RAII types from other libraries frameworks, like boost and Unreal, to work with Sol. Allows custom smart pointers, custom handles and others
  • the containers page gives full information about handling everything about container-like usertypes
  • the functions page lists a myriad of features for functions
    • variadic arguments in functions with sol::variadic_args.
    • also comes with variadic_results for returning multiple differently-typed arguments
    • this_state to get the current lua_State*, alongside other transparent argument types
  • metatable manipulations allow a user to change how indexing, function calls, and other things work on a single type.
  • ownership semantics are described for how Lua deals with its own internal references and (raw) pointers.
  • stack manipulation to safely play with the stack. You can also define customization points for stack::get/stack::check/stack::push for your type.
  • make_reference/make_object convenience function to get the same benefits and conveniences as the low-level stack API but put into objects you can specify.
  • stack references to have zero-overhead Sol abstractions while not copying to the Lua registry.
  • resolve overloads in case you have overloaded functions; a cleaner casting utility. You must use this to emulate default parameters.