tutorial: quick ‘n’ dirty

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

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 sol3 tutorial examples.

Note

Make sure to add SOL_ALL_SAFETIES_ON preprocessor define to your build configuration to turn safety on.

asserts / prerequisites

You’ll need to #include <sol/sol.hpp> somewhere in your code. sol is header-only, so you don’t need to compile anything. However, Lua must be compiled and available. See the getting started tutorial for more details.

The implementation for assert.hpp with c_assert looks like so:

 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
#ifndef EXAMPLES_ASSERT_HPP
#define EXAMPLES_ASSERT_HPP

#   define m_assert(condition, message) \
    do { \
        if (! (condition)) { \
            std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
                      << " line " << __LINE__ << ": " << message << std::endl; \
            std::terminate(); \
        } \
    } while (false)

#   define c_assert(condition) \
    do { \
        if (! (condition)) { \
            std::cerr << "Assertion `" #condition "` failed in " << __FILE__ \
                      << " line " << __LINE__ << std::endl; \
            std::terminate(); \
        } \
    } while (false)
#else
#   define m_assert(condition, message) do { if (false) { (void)(condition); (void)sizeof(message); } } while (false)
#   define c_assert(condition) do { if (false) { (void)(condition); } } while (false)
#endif

#endif // EXAMPLES_ASSERT_HPP

This is the assert used in the quick code below.

opening a state

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

#include <iostream>
#include <assert.hpp>

int main(int, char*[]) {
	std::cout << "=== opening a state ===" << 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 sol3 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 sol3 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_ALL_SAFETIES_ON 1
#include <sol/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 ===" << 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_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <fstream>
#include <iostream>
#include <assert.hpp>

int main(int, char*[]) {
	std::cout << "=== running lua code ===" << 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");
	c_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
	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
	c_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);
	return 0;
}

You can see more use of safety by employing the use of .safe_script, which returns a protected result you can use to properly check for errors and similar.

Note

If you have the safety definitions on, .script will call into the .safe_script versions automatically. Otherwise, it will call into the .unsafe_script versions.

running lua code (low-level)

You can use the individual load and function call operator to load, check, and then subsequently run and check code.

Warning

This is ONLY if you need some sort of fine-grained control: for 99% of cases, running lua code is preferred and avoids pitfalls in not understanding the difference between script/load and needing to run a chunk after loading it.

 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
30
31
32
33
34
35
36
37
38
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <fstream>
#include <iostream>
#include <cstdio>
#include <assert.hpp>

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

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

	// load file without execute
	sol::load_result script1 = lua.load_file("a_lua_script.lua");
	//execute
	script1();

	// load string without execute
	sol::load_result script2 = lua.load("a = 'test'");
	//execute
	sol::protected_function_result script2result = script2();
	// optionally, check if it worked
	if (script2result.valid()) {
		// yay!
	}
	else {
		// aww
	}

	sol::load_result script3 = lua.load("return 24");
	// execute, get return value
	int value2 = script3();
	c_assert(value2 == 24);

	return 0;
}

You can also develop custom loaders that pull from things that are not strings or files.

passing arguments to scripts

Arguments to Lua scripts can be passed by first loading the file or script blob, and then calling it using sol’s abstractions. Then, in the script, access the variables with a on the left hand side of an assignment:

 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
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>
#include <assert.hpp>

int main(int, char* []) {
	std::cout << "=== passing arguments to scripts ===" << std::endl;

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

	const auto& my_script = R"(
local a,b,c = ...
print(a,b,c)
	)";

	sol::load_result fx = lua.load(my_script);
	if (!fx.valid()) {
		sol::error err = fx;
		std::cerr << "failed to load string-based script into the program" << err.what() << std::endl;
	}
	
	// prints "your arguments here"
	fx("your", "arguments", "here");

	return 0;
}

transferring functions (dumping bytecode)

You can dump the bytecode of a function, which allows you to transfer it to another state (or save it, or load it). Note that bytecode is typically specific to the Lua version!

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>
#include "assert.hpp"


int main() {
	std::cout << "=== dump (serialize between states) ===" << std::endl;

	// 2 states, transferring function from 1 to another
	sol::state lua;
	sol::state lua2;

	// we're not going to run the code on the first
	// state, so we only actually need
	// the base lib on the second state
	// (where we will run the serialized bytecode)
	lua2.open_libraries(sol::lib::base);

	// load this code (but do not run)
	sol::load_result lr = lua.load("a = function (v) print(v) return v end");
	// check if it's sucessfully loaded
	c_assert(lr.valid());

	// turn it into a function, then dump the bytecode
	sol::protected_function target = lr.get<sol::protected_function>();
	sol::bytecode target_bc = target.dump();

	// reload the byte code
	// in the SECOND state
	auto result2 = lua2.safe_script(target_bc.as_string_view(), sol::script_pass_on_error);
	// check if it was done properly
	c_assert(result2.valid());

	// check in the second state if it was valid
	sol::protected_function pf = lua2["a"];
	int v = pf(25557);
	c_assert(v == 25557);

	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_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>

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"];
	c_assert(number == 24);
	// explicit get
	auto number2 = lua.get<double>("number2");
	c_assert(number2 == 24.5);
	// strings too
	std::string important_string = lua["important_string"];
	c_assert(important_string == "woof woof");
	// dig into a table
	int value = lua["some_table"]["value"];
	c_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();
	c_assert(value_is_100 == 100);
	c_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();
	c_assert(t1 == sol::type::number);

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

	// will not contain data
	sol::optional<int> check_for_me = lua["a_function"];
	c_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_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>

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);
	c_assert(first_try == 250);

	lua.set("exists", sol::lua_nil);
	int second_try = lua.get_or("exists", 322);
	c_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

Tables can be manipulated using accessor-syntax. Note that sol::state is a table and all the methods shown here work with sol::state, too.

 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
30
31
32
33
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>

int main(int, char*[]) {

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

	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"];
	c_assert(bark1 == 50);
	c_assert(bark2 == 50);

	int abcval1 = abc[0];
	int abcval2 = ghi["woof"][0];
	c_assert(abcval1 == 24);
	c_assert(abcval2 == 24);

If you’re going deep, be safe:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
	sol::optional<int> will_not_error = lua["abc"]["DOESNOTEXIST"]["ghi"];
	c_assert(will_not_error == sol::nullopt);
	
	int also_will_not_error = lua["abc"]["def"]["ghi"]["jklm"].get_or(25);
	c_assert(also_will_not_error == 25);

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

	return 0;
}

make tables

There are many ways to make a table. Here’s an easy way for simple ones:

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

#include <assert.hpp>

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

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

	sol::table inner_table = lua.create_table_with("bark", 50,
		// can reference other existing stuff too
		"woof", lua["abc_sol2"]
	);
	lua.create_named_table("def_sol2",
		"ghi", inner_table
	);

Equivalent Lua code, and check that they’re equivalent:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
	std::string code = R"(
		abc = { [0] = 24 }
		def = {
			ghi = {
				bark = 50,
				woof = abc
			}
		}
	)";

	lua.script(code);
	lua.script(R"(
		assert(abc_sol2[0] == abc[0])
		assert(def_sol2.ghi.bark == def.ghi.bark)
	)");

	return 0;
}

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 easy to use, from Lua and from C++:

 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
30
31
32
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>

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

	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");
	c_assert(is_one == 1);
	int is_also_one = fx(1, "boop", 3, "bark");
	c_assert(is_also_one == 1);

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

	return 0;
}

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:

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>
#include <iostream>

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;
	}
};

int main(int, char*[]) {
	std::cout << "=== functions (all) ===" << std::endl;
	
	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:

 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
30
31
	lua.script(R"(
	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
	)");

	std::cout << std::endl;

	return 0;
}

You 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.

 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
30
31
32
33
34
35
36
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>

int main() {
	std::cout << "=== self_call ===" << std::endl;

	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"]();

	std::cout << std::endl;

	return 0;
}

multiple returns from lua

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

#include <assert.hpp>

int main(int, char* []) {
	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");
	c_assert(a == 100);
	c_assert(b == 200);
	c_assert(c == "bark");

	return 0;
}

multiple returns to lua

 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
30
31
32
33
34
35
36
37
38
39
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>

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

	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);
	const std::tuple<int, int, int> expected(100, 200, 300);
	c_assert(result == expected);

	std::tuple<int, int, std::string> result2;
	result2 = lua["f"](100, 200, "BARK BARK BARK!");
	const std::tuple<int, int, std::string> expected2(100, 200, "BARK BARK BARK!");
	c_assert(result2 == expected2);

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

	lua.script(R"(
		a, b, c = f(150, 250, "woofbark")
		assert(a == 150)
		assert(b == 250)
		assert(c == "woofbark")
	)");

	return 0;
}

C++ classes from C++

Everything that is not a:

Is set as a userdata + usertype.

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>
#include <iostream>

struct Doge {
	int tailwag = 50;

	Doge() {
	}

	Doge(int wags)
	: tailwag(wags) {
	}

	~Doge() {
		std::cout << "Dog at " << this << " is being destroyed..." << std::endl;
	}
};

int main(int, char* []) {
	std::cout << "=== userdata ===" << std::endl;

	sol::state lua;

	Doge dog{ 30 };

	// fresh one put into Lua
	lua["dog"] = Doge{};
	// Copy into lua: destroyed by Lua VM during garbage collection
	lua["dog_copy"] = dog;
	// OR: move semantics - will call move constructor if present instead
	// Again, owned by Lua
	lua["dog_move"] = std::move(dog);
	lua["dog_unique_ptr"] = std::make_unique<Doge>(25);
	lua["dog_shared_ptr"] = std::make_shared<Doge>(31);

	// Identical to above
	Doge dog2{ 30 };
	lua.set("dog2", Doge{});
	lua.set("dog2_copy", dog2);
	lua.set("dog2_move", std::move(dog2));
	lua.set("dog2_unique_ptr", std::unique_ptr<Doge>(new Doge(25)));
	lua.set("dog2_shared_ptr", std::shared_ptr<Doge>(new Doge(31)));

	// Note all of them can be retrieved the same way:
	Doge& lua_dog = lua["dog"];
	Doge& lua_dog_copy = lua["dog_copy"];
	Doge& lua_dog_move = lua["dog_move"];
	Doge& lua_dog_unique_ptr = lua["dog_unique_ptr"];
	Doge& lua_dog_shared_ptr = lua["dog_shared_ptr"];
	c_assert(lua_dog.tailwag == 50);
	c_assert(lua_dog_copy.tailwag == 30);
	c_assert(lua_dog_move.tailwag == 30);
	c_assert(lua_dog_unique_ptr.tailwag == 25);
	c_assert(lua_dog_shared_ptr.tailwag == 31);
	std::cout << std::endl;

	return 0;
}

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++ while it is used/exists in Lua, do the following:

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <assert.hpp>
#include <iostream>

struct Doge {
	int tailwag = 50;

	Doge() {
	}

	Doge(int wags)
		: tailwag(wags) {
	}

	~Doge() {
		std::cout << "Dog at " << this << " is being destroyed..." << std::endl;
	}
};

int main(int, char* []) {
	std::cout << "=== userdata memory reference ===" << std::endl;

	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 ) );


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

You can retrieve the userdata in the same way as everything else. Importantly, 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:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
	lua.new_usertype<Doge>("Doge",
		"tailwag", &Doge::tailwag
	);

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

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

	dog_pointer->tailwag = 345;
	// Now 345
	lua.script("assert(dog.tailwag == 345)");

	std::cout << std::endl;

	return 0;
}

C++ classes put into Lua

See this section here. Also check out a basic example, special functions example and initializers example! There are many more examples that show off the usage of classes in C++, so please peruse them all carefully as it can be as simple or as complex as your needs are.

namespacing

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

 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
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>

#include <iostream>
#include <assert.hpp>

int main() {
	std::cout << "=== namespacing ===" << std::endl;

	struct my_class {
		int b = 24;

		int f() const {
			return 24;
		}

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

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

	// "bark" namespacing in Lua
	// namespacing is just putting things in a table
	// forces creation if it does not exist
	auto bark = lua["bark"].get_or_create<sol::table>();
	// equivalent-ish:
	//sol::table bark = lua["bark"].force(); // forces table creation
	// equivalent, and more flexible:
	//sol::table bark = lua["bark"].get_or_create<sol::table>(sol::new_table());
	// equivalent, but less efficient/ugly:
	//sol::table bark = lua["bark"] = lua.get_or("bark", lua.create_table());
	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; });

	// this works
	lua.script("obj = bark.my_class.new()");
	lua.script("obj:g()");

	// calling this function also works
	lua.script("bark.print_my_class(obj)");
	my_class& obj = lua["obj"];
	c_assert(obj.b == 25);

	std::cout << std::endl;

	return 0;
}

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.