This commit is contained in:
2026-04-05 02:30:23 +08:00
parent 1dc5fa6d48
commit b7f8b92fe9
526 changed files with 28920 additions and 67070 deletions
-169
View File
@@ -1,169 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <cstddef>
#include <cstdlib>
class memory_tracker {
public:
// 10 MB or something?
// idk whatever
inline static constexpr std::size_t arbitrary_default_limit
= 1024 * 1024 * 10;
memory_tracker() : memory_tracker(arbitrary_default_limit) {
}
memory_tracker(std::size_t maximum_memory)
: used(0)
, limit(maximum_memory)
, n_threads(0)
, n_tables(0)
, n_functions(0)
, n_userdata(0)
, n_strings(0) {
}
std::size_t currently_used() const {
return used;
}
std::size_t memory_limit() const {
return limit;
}
static void* allocate(void* memory_tracker_ud, void* ptr,
size_t object_code, size_t nsize) {
memory_tracker& self = (*static_cast<memory_tracker*>(
memory_tracker_ud));
return self.alloc(ptr, object_code, nsize);
}
private:
void* alloc(void* ptr, size_t original_block_size_or_code,
size_t new_block_size) {
std::size_t original_block_size
= original_block_size_or_code;
if (ptr == nullptr) {
// object code!
sol::type object_type = static_cast<sol::type>(
original_block_size_or_code);
switch (object_type) {
case sol::type::function:
++n_functions;
break;
case sol::type::string:
++n_strings;
break;
case sol::type::userdata:
++n_userdata;
break;
case sol::type::table:
++n_tables;
break;
case sol::type::thread:
++n_threads;
break;
default:
// not a clue, fam
break;
}
// because it is an object code,
// it tells us literally nothing about
// the old block size,
// so set that to 0
original_block_size = 0;
}
if (new_block_size == 0) {
// Lua expects us to act like a "free"
// when the new block size is 0
std::free(ptr);
used -= original_block_size;
return nullptr;
}
// did we hit the limit?
std::size_t memory_differntial
= new_block_size - original_block_size;
std::size_t desired_use = used + memory_differntial;
if (desired_use > limit) {
// tell the Lua Virtual Machine
// to toss off (by returning nullptr)
return nullptr;
}
// alright now we have to expand this shit
// guess we use C's realloc
ptr = std::realloc(ptr, new_block_size);
if (ptr != nullptr) {
// alright, we successfully allocated some space
// track it
used = desired_use;
}
// even if we're null, let Lua crash and burn for us
return ptr;
}
std::size_t used;
std::size_t limit;
std::size_t n_threads;
std::size_t n_tables;
std::size_t n_functions;
std::size_t n_userdata;
std::size_t n_strings;
};
struct my_type {
int a = 24;
bool b = false;
double d = 3.5;
};
#include <iostream>
int main() {
std::cout << "=== memory tracker ===" << std::endl;
#if SOL_LUAJIT_VERSION < 20100 && (UINTPTR_MAX > 0xFFFFFFFF)
std::cout << "LuaJIT in x64 mode on LuaJIT 2.0.X versions "
"does not support using a custom allocator!"
<< std::endl;
#else
memory_tracker box;
std::cout << "memory at start: " << box.currently_used()
<< " bytes / " << box.memory_limit() << " bytes"
<< std::endl;
sol::state lua(&sol::default_at_panic,
&memory_tracker::allocate,
&box);
lua.open_libraries(sol::lib::base);
std::cout << "memory after state creation: "
<< box.currently_used() << " bytes / "
<< box.memory_limit() << " bytes" << std::endl;
// trigger some allocations
lua.new_usertype<my_type>("my_type",
"a",
&my_type::a,
"b",
&my_type::b,
"d",
&my_type::d);
lua["f"] = [](std::string s) { return s + " woof!"; };
std::cout << "memory after function and usertype setup: "
<< box.currently_used() << " bytes / "
<< box.memory_limit() << " bytes" << std::endl;
lua.safe_script("print(f('bark'))");
lua.safe_script(
"local obj = my_type.new() print(obj.a, obj.b, obj.c) "
"obj.b = true print(obj.a, obj.b, obj.c)");
std::cout << "memory at end: " << box.currently_used()
<< " bytes / " << box.memory_limit() << " bytes"
<< std::endl;
#endif
return 0;
}
-53
View File
@@ -1,53 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
// Uses some of the fancier bits of sol2, including the
// "transparent argument", sol::this_state, which gets the
// current state and does not increment function arguments
sol::object fancy_func(
sol::object a, sol::object b, sol::this_state s) {
sol::state_view lua(s);
if (a.is<int>() && b.is<int>()) {
return sol::object(
lua, sol::in_place, a.as<int>() + b.as<int>());
}
else if (a.is<bool>()) {
bool do_triple = a.as<bool>();
return sol::object(lua,
sol::in_place_type<double>,
b.as<double>() * (do_triple ? 3 : 1));
}
// Can also use make_object
return sol::make_object(lua, sol::lua_nil);
}
int main() {
sol::state lua;
lua["f"] = fancy_func;
int result = lua["f"](1, 2);
// result == 3
sol_c_assert(result == 3);
double result2 = lua["f"](false, 2.5);
// result2 == 2.5
sol_c_assert(result2 == 2.5);
// call in Lua, get result
// notice we only need 2 arguments here, not 3
// (sol::this_state is transparent)
lua.script("result3 = f(true, 5.5)");
double result3 = lua["result3"];
// result3 == 16.5
sol_c_assert(result3 == 16.5);
std::cout << "=== any_return ===" << std::endl;
std::cout << "result : " << result << std::endl;
std::cout << "result2: " << result2 << std::endl;
std::cout << "result3: " << result3 << std::endl;
std::cout << std::endl;
return 0;
}
-31
View File
@@ -1,31 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <vector>
#include <set>
int main(int, const char*[]) {
std::cout << "=== args_from_container ===" << std::endl;
sol::state lua;
lua.open_libraries();
lua.script("function f (a, b, c, d) print(a, b, c, d) end");
sol::function f = lua["f"];
std::vector<int> v2 { 3, 4 };
f(1, 2, sol::as_args(v2));
std::set<int> v4 { 3, 1, 2, 4 };
f(sol::as_args(v4));
int v3[] = { 2, 3, 4 };
f(1, sol::as_args(v3));
std::cout << std::endl;
return 0;
}
-29
View File
@@ -1,29 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <set>
int main() {
sol::state lua;
lua.set_function("f", []() {
std::set<std::string> results {
"arf", "bark", "woof"
};
return sol::as_returns(std::move(results));
});
lua.script("v1, v2, v3 = f()");
std::string v1 = lua["v1"];
std::string v2 = lua["v2"];
std::string v3 = lua["v3"];
sol_c_assert(v1 == "arf");
sol_c_assert(v2 == "bark");
sol_c_assert(v3 == "woof");
return 0;
}
-79
View File
@@ -1,79 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
std::cout << "=== basic ===" << std::endl;
// create an empty lua state
sol::state lua;
// by default, libraries are not opened
// you can open libraries by using open_libraries
// the libraries reside in the sol::lib enum class
lua.open_libraries(sol::lib::base);
// you can open all libraries by passing no arguments
// lua.open_libraries();
// call lua code directly
lua.script("print('hello world')");
// call lua code, and check to make sure it has loaded and
// run properly:
auto handler = &sol::script_default_on_error;
lua.script("print('hello again, world')", handler);
// Use a custom error handler if you need it
// This gets called when the result is bad
auto simple_handler =
[](lua_State*, sol::protected_function_result result) {
// You can just pass it through to let the
// call-site handle it
return result;
};
// the above lambda is identical to sol::simple_on_error,
// but it's shown here to show you can write whatever you
// like
//
{
auto result = lua.script(
"print('hello hello again, world') \n return 24",
simple_handler);
if (result.valid()) {
std::cout << "the third script worked, and a "
"double-hello statement should "
"appear above this one!"
<< std::endl;
int value = result;
sol_c_assert(value == 24);
}
else {
std::cout << "the third script failed, check the "
"result type for more information!"
<< std::endl;
}
}
{
auto result
= lua.script("does.not.exist", simple_handler);
if (result.valid()) {
std::cout << "the fourth script worked, which it "
"wasn't supposed to! Panic!"
<< std::endl;
int value = result;
sol_c_assert(value == 24);
}
else {
sol::error err = result;
std::cout << "the fourth script failed, which "
"was intentional!\t\nError: "
<< err.what() << std::endl;
}
}
std::cout << std::endl;
return 0;
}
-55
View File
@@ -1,55 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct something {
int arr[4];
something() : arr { 5, 6, 7, 8 } {
}
};
int main() {
std::cout << "=== c arrays (works with Visual C++ too) ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<something>(
"something", "arr", sol::property([](something& s) {
return std::ref(s.arr);
}));
lua.script(R"(s = something.new()
print(s.arr[3])
s.arr[3] = 40
print(s.arr[3])
)");
something& s = lua["s"];
sol_c_assert(s.arr[0] == 5);
sol_c_assert(s.arr[1] == 6);
sol_c_assert(s.arr[2] == 40);
sol_c_assert(s.arr[3] == 8);
std::string string_array[] = {
"first string",
"second string",
"third string",
};
lua["str_arr"] = std::ref(string_array);
// or:
// lua["str_array"] = &string_array;
lua.script(R"(
print(str_arr[3])
str_arr[3] = str_arr[3] .. ': modified'
print(str_arr[3])
)");
sol_c_assert(string_array[2] == "third string: modified");
return 0;
}
-54
View File
@@ -1,54 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int f1(int) {
return 32;
}
int f2(int, int) {
return 1;
}
struct fer {
double f3(int, int) {
return 2.5;
}
};
int main() {
sol::state lua;
// overloaded function f
lua.set("f",
sol::c_call<sol::wrap<decltype(&f1), &f1>,
sol::wrap<decltype(&f2), &f2>,
sol::wrap<decltype(&fer::f3), &fer::f3>>);
// singly-wrapped function
lua.set("g", sol::c_call<sol::wrap<decltype(&f1), &f1>>);
// without the 'sol::wrap' boilerplate
lua.set("h", sol::c_call<decltype(&f2), &f2>);
// object used for the 'fer' member function call
lua.set("obj", fer());
// call them like any other bound function
lua.script("r1 = f(1)");
lua.script("r2 = f(1, 2)");
lua.script("r3 = f(obj, 1, 2)");
lua.script("r4 = g(1)");
lua.script("r5 = h(1, 2)");
// get the results and see
// if it worked out
int r1 = lua["r1"];
sol_c_assert(r1 == 32);
int r2 = lua["r2"];
sol_c_assert(r2 == 1);
double r3 = lua["r3"];
sol_c_assert(r3 == 2.5);
int r4 = lua["r4"];
sol_c_assert(r4 == 32);
int r5 = lua["r5"];
sol_c_assert(r5 == 1);
return 0;
}
-58
View File
@@ -1,58 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int func_1(int value) {
return 20 + value;
}
std::string func_2(std::string text) {
return "received: " + text;
}
sol::variadic_results fallback(
sol::this_state ts, sol::variadic_args args) {
sol::variadic_results r;
if (args.size() == 2) {
r.push_back({ ts,
sol::in_place,
args.get<int>(0) + args.get<int>(1) });
}
else {
r.push_back({ ts, sol::in_place, 52 });
}
return r;
}
int main(int, char*[]) {
std::cout << "=== calling lua functions ===" << std::endl;
sol::state lua;
lua.open_libraries();
sol::table mLuaPackets
= lua.create_named_table("mLuaPackets");
mLuaPackets[1] = lua.create_table_with("timestamp", 0LL);
mLuaPackets[2] = lua.create_table_with("timestamp", 3LL);
mLuaPackets[3] = lua.create_table_with("timestamp", 1LL);
lua.script("print('--- pre sort ---')");
lua.script(
"for i=1,#mLuaPackets do print(i, "
"mLuaPackets[i].timestamp) end");
lua["table"]["sort"](mLuaPackets,
sol::as_function([](sol::table l, sol::table r) {
std::uint64_t tl = l["timestamp"];
std::uint64_t tr = r["timestamp"];
return tl < tr;
}));
lua.script("print('--- post sort ---')");
lua.script(
"for i=1,#mLuaPackets do print(i, "
"mLuaPackets[i].timestamp) end");
return 0;
}
-41
View File
@@ -1,41 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <iostream>
// shows how to load basic data to a struct
struct config {
std::string name;
int width;
int height;
void print() {
std::cout << "Name: " << name << '\n'
<< "Width: " << width << '\n'
<< "Height: " << height << '\n';
}
};
int main() {
sol::state lua;
config screen;
// To use the file, uncomment here and make sure it is in
// local dir lua.script_file("config.lua");
lua.script(R"(
name = "Asus"
width = 1920
height = 1080
)");
screen.name = lua.get<std::string>("name");
screen.width = lua.get<int>("width");
screen.height = lua.get<int>("height");
sol_c_assert(screen.name == "Asus");
sol_c_assert(screen.width == 1920);
sol_c_assert(screen.height == 1080);
std::cout << "=== config ===" << std::endl;
screen.print();
std::cout << std::endl;
}
-3
View File
@@ -1,3 +0,0 @@
name = "Asus"
width = 1920
height = 1080
@@ -1,89 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <vector>
#include <numeric>
#include <iostream>
class number_storage {
private:
std::vector<int> data;
public:
number_storage(int i) {
data.push_back(i);
}
int accumulate() const {
return std::accumulate(data.begin(), data.end(), 0);
}
public:
using value_type = decltype(data)::value_type;
using iterator = decltype(data)::iterator;
using size_type = decltype(data)::size_type;
iterator begin() {
return iterator(data.begin());
}
iterator end() {
return iterator(data.end());
}
size_type size() const noexcept {
return data.size();
}
size_type max_size() const noexcept {
return data.max_size();
}
void push_back(int value) {
data.push_back(value);
}
bool empty() const noexcept {
return data.empty();
}
};
namespace sol {
template <>
struct is_container<number_storage> : std::false_type { };
} // namespace sol
int main(int, char*[]) {
std::cout << "=== container as container ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<number_storage>("number_storage",
sol::constructors<number_storage(int)>(),
"accumulate",
&number_storage::accumulate,
"iterable",
[](number_storage& ns) {
return sol::as_container(
ns); // treat like a container, despite
// is_container specialization
});
lua.script(R"(
ns = number_storage.new(23)
print("accumulate before:", ns:accumulate())
-- reference original usertype like a container
ns_container = ns:iterable()
ns_container:add(24)
ns_container:add(25)
-- now print to show effect
print("accumulate after :", ns:accumulate())
)");
number_storage& ns = lua["ns"];
number_storage& ns_container = lua["ns_container"];
sol_c_assert(&ns == &ns_container);
sol_c_assert(ns.size() == 3);
std::cout << std::endl;
return 0;
}
-47
View File
@@ -1,47 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <unordered_set>
#include <iostream>
int main() {
struct hasher {
typedef std::pair<std::string, std::string>
argument_type;
typedef std::size_t result_type;
result_type operator()(const argument_type& p) const {
return std::hash<std::string>()(p.first);
}
};
using my_set = std::unordered_set<
std::pair<std::string, std::string>,
hasher>;
std::cout << "=== containers with std::pair<> ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.set_function("f", []() {
return my_set { { "key1", "value1" },
{ "key2", "value2" },
{ "key3", "value3" } };
});
lua.safe_script("v = f()");
lua.safe_script("print('v:', v)");
lua.safe_script("print('#v:', #v)");
// note that using my_obj:pairs() is a
// way around pairs(my_obj) not working in Lua 5.1/LuaJIT:
// try it!
lua.safe_script(
"for k,v1,v2 in v:pairs() do print(k, v1, v2) end");
std::cout << std::endl;
return 0;
}
-64
View File
@@ -1,64 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <vector>
#include <iostream>
int main(int, char**) {
std::cout << "=== containers ===" << std::endl;
sol::state lua;
lua.open_libraries();
lua.script(R"(
function f (x)
print("container has:")
for k=1,#x do
v = x[k]
print("\t", k, v)
end
print()
end
)");
// Have the function we
// just defined in Lua
sol::function f = lua["f"];
// Set a global variable called
// "arr" to be a vector of 5 lements
lua["arr"] = std::vector<int> { 2, 4, 6, 8, 10 };
// Call it, see 5 elements
// printed out
f(lua["arr"]);
// Mess with it in C++
// Containers are stored as userdata, unless you
// use `sol::as_table()` and `sol::as_table_t`.
std::vector<int>& reference_to_arr = lua["arr"];
reference_to_arr.push_back(12);
// Call it, see *6* elements
// printed out
f(lua["arr"]);
lua.script(R"(
arr:add(28)
)");
// Call it, see *7* elements
// printed out
f(lua["arr"]);
lua.script(R"(
arr:clear()
)");
// Now it's empty
f(lua["arr"]);
std::cout << std::endl;
return 0;
}
-88
View File
@@ -1,88 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <vector>
#include <map>
#include <iostream>
// nested allows serialization of maps with vectors inside, and
// vice-versa all from a nested structure of Lua tables it has
// less control over which pieces are considered tables in Lua,
// and which ones are considered userdata, but it covers a good
// 90% of cases where someone wants to handle a nested table
void demo(
sol::nested<std::map<std::string, std::vector<std::string>>>
src) {
std::cout << "demo, sol::nested<...>" << std::endl;
const auto& listmap = src.value();
sol_c_assert(listmap.size() == 2);
for (const auto& kvp : listmap) {
const std::vector<std::string>& strings = kvp.second;
sol_c_assert(strings.size() == 3);
std::cout << "\t" << kvp.first << " = ";
for (const auto& s : strings) {
std::cout << "'" << s << "'"
<< " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
// This second demo is equivalent to the first
// Nota bene the signature here
// Every container-type that's meant to be
// a table must be wrapped in `sol::as_table_t`
// it's verbose, so feel free to use typedefs to make it easy on
// you you can mix which parts are considered tables from Lua,
// and which parts are considered other kinds of types, such as
// userdata and the like
void demo_explicit(sol::as_table_t<std::map<std::string,
sol::as_table_t<std::vector<std::string>>>>
src) {
std::cout << "demo, explicit sol::as_table_t<...>"
<< std::endl;
// Have to access the "source" member variable for
// as_table_t
const auto& listmap = src.value();
sol_c_assert(listmap.size() == 2);
for (const auto& kvp : listmap) {
// Have to access the internal "source" for the inner
// as_table_t, as well
const std::vector<std::string>& strings
= kvp.second.value();
sol_c_assert(strings.size() == 3);
std::cout << "\t" << kvp.first << " = ";
for (const auto& s : strings) {
std::cout << "'" << s << "'"
<< " ";
}
std::cout << std::endl;
}
std::cout << std::endl;
}
int main(int, char**) {
std::cout << "=== containers retrieved from lua tables ==="
<< std::endl;
sol::state lua;
// bind the function
lua.set_function("f", &demo);
lua.set_function("g", &demo_explicit);
// Call it with a table that has string sequences set to
// distinct keys
lua.script(R"(
t = {
key1 = {'hello', 'there', 'world'},
key2 = {'bark', 'borf', 'woof'}
}
f(t)
g(t)
)");
std::cout << std::endl;
return 0;
}
-68
View File
@@ -1,68 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <iostream>
int main() {
std::cout << "=== coroutine ===" << std::endl;
sol::state lua;
std::vector<sol::coroutine> tasks;
lua.open_libraries(sol::lib::base, sol::lib::coroutine);
sol::thread runner_thread = sol::thread::create(lua);
lua.set_function("start_task",
[&runner_thread, &tasks](
sol::function f, sol::variadic_args va) {
// You must ALWAYS get the current state
sol::state_view runner_thread_state
= runner_thread.state();
// Put the task in our task list to keep it alive
// and track it
std::size_t task_index = tasks.size();
tasks.emplace_back(runner_thread_state, f);
sol::coroutine& f_on_runner_thread
= tasks[task_index];
// call coroutine with arguments that came
// from main thread / other thread
// pusher for `variadic_args` and other sol types
// will transfer the arguments from the calling
// thread to the runner thread automatically for
// you using `lua_xmove` internally
int wait = f_on_runner_thread(va);
std::cout << "First return: " << wait
<< std::endl;
// When you call it again, you don't need new
// arguments (they remain the same from the first
// call)
f_on_runner_thread();
std::cout << "Second run complete: " << wait
<< std::endl;
});
lua.script(
R"(
function main(x, y, z)
-- do something
coroutine.yield(20)
-- do something else
-- do ...
print(x, y, z)
end
function main2(x, y)
coroutine.yield(10)
print(x, y)
end
start_task(main, 10, 12, 8)
start_task(main2, 1, 2)
)");
std::cout << std::endl;
return 0;
}
@@ -1,51 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <iostream>
int main() {
std::cout << "=== coroutine - multple threads ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base,
sol::lib::package,
sol::lib::coroutine);
lua["print"] = [](sol::object v) {
std::cout << v.as<std::string>() << std::endl;
};
lua["cyield"] = sol::yielding(
[]() { std::cout << "YIELDING" << std::endl; });
// notice the new threads!
sol::thread thread1 = sol::thread::create(lua);
sol::thread thread2 = sol::thread::create(lua);
// notice we load it FROM the new "execution stack"
// we need it to have thread1's stack perspective
sol::coroutine co1 = thread1.state().load(R"(
print("AA : Step 1")
cyield()
print("AA : Step 2")
)");
// call first coroutine here
co1();
// notice we load it FROM the new "execution stack"
// we need it to have thread2's stack and perspective
sol::coroutine co2 = thread2.state().load(R"(
print("BB : Step 1")
cyield()
print("BB : Step 2")
)");
// run the other coroutine
co2();
co1();
// tada! they run on
// independent stacks
return 0;
}
-53
View File
@@ -1,53 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== coroutine state transfer ==="
<< std::endl;
sol::state lua;
lua.open_libraries();
sol::function transferred_into;
lua["f"] = [&lua, &transferred_into](
sol::object t, sol::this_state this_L) {
std::cout << "state of main : "
<< (void*)lua.lua_state() << std::endl;
std::cout << "state of function : "
<< (void*)this_L.lua_state() << std::endl;
// pass original lua_State* (or
// sol::state/sol::state_view) transfers ownership from
// the state of "t", to the "lua" sol::state
transferred_into = sol::function(lua, t);
};
lua.script(R"(
i = 0
function test()
co = coroutine.create(
function()
local g = function() i = i + 1 end
f(g)
g = nil
collectgarbage()
end
)
coroutine.resume(co)
co = nil
collectgarbage()
end
)");
// give it a try
lua.safe_script("test()");
// should call 'g' from main thread, increment i by 1
transferred_into();
// check
int i = lua["i"];
sol_c_assert(i == 1);
std::cout << std::endl;
return 0;
}
-101
View File
@@ -1,101 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <exception>
#include <fstream>
struct custom_reader {
FILE* f;
// We use 2 here to demonstrate
// multiple calls to the function to
// parse whole file.
// Please don't use 2.
// PLEASE DO NOT USE A BUFFER
// OF SIZE 2!
char buffer[2];
std::size_t current_size;
std::size_t read_count;
custom_reader(FILE* f_)
: f(f_), buffer(), current_size(0), read_count(0) {
}
bool read() {
std::cout << "custom read: read #" << ++read_count
<< std::endl;
current_size = fread(buffer, 1, 2, f);
return current_size > 0 && ferror(f) == 0;
}
~custom_reader() {
std::fclose(f);
}
};
// function must match signature found in type lua_Reader:
// const char* ( lua_State*, void*, size_t* )
const char* custom_reader_function(
lua_State*, void* pointer_to_my_object, size_t* data_size) {
custom_reader& cr
= *(static_cast<custom_reader*>(pointer_to_my_object));
if (cr.read()) {
*data_size = cr.current_size;
return cr.buffer;
}
else {
*data_size = 0;
return nullptr;
}
}
int main() {
std::cout << "=== custom reader ===" << std::endl;
// make a file to use for the custom reader
{
std::ofstream bjork("bjork.lua", std::ios::binary);
bjork << "print('hello!')\n";
}
struct on_scope_exit {
~on_scope_exit() {
// remove file when done
std::remove("bjork.lua");
}
} remove_on_exit;
sol::state lua;
lua.open_libraries(sol::lib::base);
FILE* bjork_fp;
#ifdef _MSC_VER
if (fopen_s(&bjork_fp, "bjork.lua", "r") != 0) {
std::cerr << "failed to open bjork.lua -- exiting"
<< std::endl;
return -1;
}
#else
bjork_fp = fopen("bjork.lua", "r");
#endif
if (bjork_fp == nullptr) {
std::cerr << "failed to open bjork.lua -- exiting"
<< std::endl;
return -1;
}
custom_reader reader(bjork_fp);
// load the code using our custom reader, then run it
auto result = lua.safe_script(custom_reader_function,
&reader,
sol::script_pass_on_error);
// make sure we ran loaded and ran the code successfully
sol_c_assert(result.valid());
// note there are lua.load( ... ) variants that take a
// custom reader than JUST run the code, too!
std::cout << std::endl;
return 0;
}
@@ -1,214 +0,0 @@
#include <sol/sol.hpp>
#include <iostream>
// We capture the base objects
// lifetime style
// You can add more here,
// e.g. "Unique" for a unique pointer kind of lifestyle,
// but you would need to think about how to handle
// copying / moving in that case
enum class BaseObjectLifetime { Value, Pointer, Shared };
// The base object
// that we do inheritance and other work
// on
class BaseObject {
public:
BaseObject() {
objectType = 0;
}
unsigned int getObjectType() const {
return objectType;
}
bool doArmorThing() const {
return false;
}
bool doWeaponThing() const {
return false;
}
// helper function defined later after we define all the
// base classes we care about
sol::object getAsRetyped(
lua_State* L, BaseObjectLifetime Lifetime) const;
// For convenience with the customization points below
int pushAsRetyped(
lua_State* L, BaseObjectLifetime Lifetime) const {
return getAsRetyped(L, Lifetime).push(L);
}
protected:
unsigned int objectType;
};
class Armor : public BaseObject {
public:
Armor() {
objectType = 1;
}
bool doArmorThing() const {
return true;
}
};
class Weapon : public BaseObject {
public:
Weapon() {
objectType = 2;
}
bool doWeaponThing() const {
return true;
}
};
// Get the most-derived type
// that we care about from the base object,
// obeying the lifetime type
sol::object BaseObject::getAsRetyped(
lua_State* L, BaseObjectLifetime Lifetime) const {
switch (objectType) {
case 1:
std::cout << "Retyping as armor." << std::endl;
switch (Lifetime) {
case BaseObjectLifetime::Pointer:
return sol::make_object(
L, static_cast<const Armor*>(this));
case BaseObjectLifetime::Shared:
return sol::make_object(L,
std::make_shared<Armor>(
*static_cast<const Armor*>(this)));
case BaseObjectLifetime::Value:
default:
return sol::make_object(
L, *static_cast<const Armor*>(this));
}
case 2:
std::cout << "Retyping as weapon." << std::endl;
switch (Lifetime) {
case BaseObjectLifetime::Pointer:
return sol::make_object(
L, static_cast<const Weapon*>(this));
case BaseObjectLifetime::Shared:
return sol::make_object(L,
std::make_shared<Weapon>(
*static_cast<const Weapon*>(this)));
case BaseObjectLifetime::Value:
default:
return sol::make_object(
L, *static_cast<const Weapon*>(this));
}
default:
std::cout
<< "Unknown type: falling back to base object."
<< std::endl;
// we have a normal type here, so that means we
// must bypass typical customization points by using
// sol::make_object_userdata/sol::make_reference_userdata
// WARNING: IF THIS TYPE IS IN FACT NOT A BASE OBJECT,
// BUT SOME DERIVED OBJECT, THEN RUNNING THIS CODE FOR
// VALUE TYPES AND SHARED TYPES WILL "SLICE"
// THE DERIVED BITS OFF THE BASE BITS PERMANENTLY
// NEVER FORGET TO UPDATE THE SWITCH IF YOU ADD
// NEW TYPES!!
switch (Lifetime) {
case BaseObjectLifetime::Value:
return sol::make_object_userdata(L, *this);
case BaseObjectLifetime::Shared:
return sol::make_object_userdata(
L, std::make_shared<BaseObject>(*this));
case BaseObjectLifetime::Pointer:
default:
return sol::make_object_userdata(L, this);
}
}
}
//
// sol customization points
//
// Defining a customization point that lets us put the correct
// object type on the stack.
int sol_lua_push(sol::types<BaseObject>, lua_State* L,
const BaseObject& obj) {
return obj.pushAsRetyped(L, BaseObjectLifetime::Value);
}
int sol_lua_push(sol::types<BaseObject*>, lua_State* L,
const BaseObject* obj) {
return obj->pushAsRetyped(L, BaseObjectLifetime::Pointer);
}
int sol_lua_push(sol::types<std::shared_ptr<BaseObject>>,
lua_State* L, const std::shared_ptr<BaseObject>& obj) {
return obj->pushAsRetyped(L, BaseObjectLifetime::Shared);
}
int main() {
// test our customization points out
std::cout << "=== Base object customization points ==="
<< std::endl;
sol::state lua;
lua.open_libraries(
sol::lib::base, sol::lib::string, sol::lib::table);
lua["objectCache"] = lua.create_table();
// Do basic type binding.
auto luaBaseObject
= lua.new_usertype<BaseObject>("tes3baseObject");
luaBaseObject["objectType"]
= sol::readonly_property(&BaseObject::getObjectType);
luaBaseObject["doArmorThing"] = &BaseObject::doArmorThing;
luaBaseObject["doWeaponThing"] = &BaseObject::doWeaponThing;
auto luaArmorObject = lua.new_usertype<Armor>("tes3armor");
luaArmorObject[sol::base_classes]
= sol::bases<BaseObject>();
luaArmorObject["doArmorThing"] = &Armor::doArmorThing;
auto luaWeaponObject
= lua.new_usertype<Weapon>("tes3weapon");
luaWeaponObject[sol::base_classes]
= sol::bases<BaseObject>();
luaWeaponObject["doWeaponThing"] = &Weapon::doWeaponThing;
// Objects we'll play with.
BaseObject base;
Armor armor;
Weapon weapon;
// Push some objects to lua.
std::cout << "Normal pointers..." << std::endl;
lua["ptrBase"] = &base;
lua["ptrArmor"] = &armor;
lua["ptrWeapon"] = &weapon;
std::cout << std::endl;
// Same objects but as base objects to test mapping.
std::cout << "Base-cast pointers..." << std::endl;
lua["ptrBaseAsBase"] = static_cast<BaseObject*>(&base);
lua["ptrArmorAsBase"] = static_cast<BaseObject*>(&armor);
lua["ptrWeaponAsBase"] = static_cast<BaseObject*>(&weapon);
std::cout << std::endl;
std::cout << "Smart direct pointers..." << std::endl;
lua["sharedBase"] = std::make_shared<BaseObject>();
lua["sharedArmor"] = std::make_shared<Armor>();
lua["sharedArmor"] = std::make_shared<Weapon>();
std::cout << std::endl;
std::cout << "Smart pointers put as the base class..."
<< std::endl;
lua["sharedBaseAsBase"] = (std::shared_ptr<BaseObject>)
std::make_shared<BaseObject>();
lua["sharedArmorAsBase"] = (std::shared_ptr<BaseObject>)
std::make_shared<Armor>();
lua["sharedArmorAsBase"] = (std::shared_ptr<BaseObject>)
std::make_shared<Weapon>();
std::cout << std::endl;
return 0;
}
@@ -1,63 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <iomanip>
struct number_shim {
double num = 0;
};
template <typename Handler>
bool sol_lua_check(sol::types<number_shim>, lua_State* L,
int index, Handler&& handler,
sol::stack::record& tracking) {
// check_usertype is a backdoor for directly checking sol2
// usertypes
if (!sol::stack::check_usertype<number_shim>(L, index)
&& !sol::stack::check<double>(L, index)) {
handler(L,
index,
sol::type_of(L, index),
sol::type::userdata,
"expected a number_shim or a number");
return false;
}
tracking.use(1);
return true;
}
number_shim sol_lua_get(sol::types<number_shim>, lua_State* L,
int index, sol::stack::record& tracking) {
if (sol::stack::check_usertype<number_shim>(L, index)) {
number_shim& ns
= sol::stack::get_usertype<number_shim>(
L, index, tracking);
return ns;
}
number_shim ns {};
ns.num = sol::stack::get<double>(L, index, tracking);
return ns;
}
int main() {
sol::state lua;
// Create a pass-through style of function
lua.safe_script("function f ( a ) return a end");
lua.set_function("g", [](double a) {
number_shim ns;
ns.num = a;
return ns;
});
lua.script("vf = f(25) vg = g(35)");
number_shim thingsf = lua["vf"];
number_shim thingsg = lua["vg"];
sol_c_assert(thingsf.num == 25);
sol_c_assert(thingsg.num == 35);
return 0;
}
@@ -1,74 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
// Something that can't be collided with
static const auto& script_key
= "GlobalResource.MySpecialIdentifier123";
struct GlobalResource {
int value = 2;
};
template <typename Handler>
bool sol_lua_check(sol::types<GlobalResource*>, lua_State* L,
int /*index*/, Handler&& handler,
sol::stack::record& tracking) {
// not actually taking anything off the stack
tracking.use(0);
// get the field from global storage
sol::stack::get_field<true>(L, script_key);
// verify type
sol::type t = static_cast<sol::type>(lua_type(L, -1));
lua_pop(L, 1);
if (t != sol::type::lightuserdata) {
handler(L,
0,
sol::type::lightuserdata,
t,
"global resource is not present as a light "
"userdata");
return false;
}
return true;
}
GlobalResource* sol_lua_get(sol::types<GlobalResource*>,
lua_State* L, int /*index*/, sol::stack::record& tracking) {
// retrieve the (light) userdata for this type
// not actually pulling anything off the stack
tracking.use(0);
sol::stack::get_field<true>(L, script_key);
GlobalResource* ls
= static_cast<GlobalResource*>(lua_touserdata(L, -1));
// clean up stack value returned by `get_field`
lua_pop(L, 1);
return ls;
}
int sol_lua_push(sol::types<GlobalResource*>, lua_State* L,
GlobalResource* ls) {
// push light userdata
return sol::stack::push(L, static_cast<void*>(ls));
}
int main() {
sol::state lua;
lua.open_libraries(sol::lib::base);
GlobalResource instance;
// get GlobalResource
lua.set_function("f", [](GlobalResource* l, int value) {
return l->value + value;
});
lua.set(script_key, &instance);
// note only 1 argument,
// despite f having 2 arguments to recieve
lua.script("assert(f(1) == 3)");
return 0;
}
-77
View File
@@ -1,77 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct two_things {
int a;
bool b;
};
template <typename Handler>
bool sol_lua_check(sol::types<two_things>, lua_State* L,
int index, Handler&& handler,
sol::stack::record& tracking) {
// indices can be negative to count backwards from the top
// of the stack, rather than the bottom up to deal with
// this, we adjust the index to its absolute position using
// the lua_absindex function
int absolute_index = lua_absindex(L, index);
// Check first and second second index for being the proper
// types
bool success
= sol::stack::check<int>(L, absolute_index, handler)
&& sol::stack::check<bool>(
L, absolute_index + 1, handler);
tracking.use(2);
return success;
}
two_things sol_lua_get(sol::types<two_things>, lua_State* L,
int index, sol::stack::record& tracking) {
int absolute_index = lua_absindex(L, index);
// Get the first element
int a = sol::stack::get<int>(L, absolute_index);
// Get the second element,
// in the +1 position from the first
bool b = sol::stack::get<bool>(L, absolute_index + 1);
// we use 2 slots, each of the previous takes 1
tracking.use(2);
return two_things { a, b };
}
int sol_lua_push(lua_State* L, const two_things& things) {
int amount = sol::stack::push(L, things.a);
// amount will be 1: int pushes 1 item
amount += sol::stack::push(L, things.b);
// amount 2 now, since bool pushes a single item
// Return 2 things
return amount;
}
int main() {
std::cout << "=== customization ===" << std::endl;
std::cout << std::boolalpha;
sol::state lua;
lua.open_libraries(sol::lib::base);
// Create a pass-through style of function
lua.script(
"function f ( a, b ) print(a, b) return a, b end");
// get the function out of Lua
sol::function f = lua["f"];
two_things things = f(two_things { 24, false });
sol_c_assert(things.a == 24);
sol_c_assert(things.b == false);
// things.a == 24
// things.b == true
std::cout << "things.a: " << things.a << std::endl;
std::cout << "things.b: " << things.b << std::endl;
std::cout << std::endl;
return 0;
}
-21
View File
@@ -1,21 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main() {
struct callable {
int operator()(int a, bool b) {
return a + (b ? 10 : 20);
}
};
sol::state lua;
// Binds struct as userdata
// can still be callable, but beware
// caveats
lua.set("not_func", callable());
// Binds struct as function
lua.set("func", sol::as_function(callable()));
// equivalent: lua.set_function( "func", callable() );
// equivalent: lua["func"] = callable();
}
@@ -1,29 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main() {
class B {
public:
int bvar = 24;
};
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<B>("B",
// bind as variable
"b",
&B::bvar,
// bind as function
"f",
sol::as_function(&B::bvar));
B b;
lua.set("b", &b);
lua.script(R"(x = b:f()
y = b.b
assert(x == 24)
assert(y == 24)
)");
return 0;
}
-17
View File
@@ -1,17 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <vector>
int main(int, char*[]) {
sol::state lua;
lua.open_libraries();
lua.set("my_table",
sol::as_table(std::vector<int> { 1, 2, 3, 4, 5 }));
lua.script(
"for k, v in ipairs(my_table) do print(k, v) assert(k "
"== v) end");
return 0;
}
-52
View File
@@ -1,52 +0,0 @@
#define SOL_ALL_SAFTIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
const auto& co_lua_script = R"(
function loop()
while counter ~= 30
do
coroutine.yield(counter);
counter = counter + 1;
end
return counter
end
)";
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::coroutine);
/*
lua.script_file("co.lua");
we load string directly rather than use a file
*/
lua.script(co_lua_script);
sol::coroutine loop_coroutine = lua["loop"];
// set counter variable in C++
// (can set it to something else to
// have loop_coroutine() yield different values)
lua["counter"] = 20;
// example of using and re-using coroutine
// you do not have to use coroutines in a loop,
// this is just the example
// we start from 0;
// we want 10 values, and we only want to
// run if the coroutine "loop_coroutine" is valid
for (int counter = 0; counter < 10 && loop_coroutine;
++counter) {
// Alternative: counter < 10 && cr.valid()
// Call the coroutine, does the computation and then
// suspends once it returns, we get the value back from
// the return and then can use it we can either leave
// the coroutine like that can come to it later, or
// loop back around
int value = loop_coroutine();
std::cout << "In C++: " << value << std::endl;
}
return 0;
}
-39
View File
@@ -1,39 +0,0 @@
#define SOL_ALL_SAFTIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
const auto& co_lua_script = R"(
function loop()
while counter ~= 30
do
coroutine.yield(counter);
counter = counter + 1;
end
return counter
end
)";
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::coroutine);
/*
lua.script_file("co.lua");
we load string directly rather than use a file
*/
lua.script(co_lua_script);
sol::thread runner = sol::thread::create(lua.lua_state());
sol::state_view runnerstate = runner.state();
sol::coroutine loop_coroutine = runnerstate["loop"];
lua["counter"] = 20;
for (int counter = 0; counter < 10 && loop_coroutine;
++counter) {
// Call the coroutine, does the computation and then
// suspends
int value = loop_coroutine();
std::cout << "value is " << value << std::endl;
}
return 0;
}
-32
View File
@@ -1,32 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
struct A {
int a = 10;
virtual int call() {
return 0;
}
virtual ~A() {
}
};
struct B : A {
int b = 11;
virtual int call() override {
return 20;
}
};
int main(int, char*[]) {
sol::state lua;
lua.new_usertype<B>("A", "call", &A::call);
lua.new_usertype<B>("B",
"call",
&B::call,
sol::base_classes,
sol::bases<A>());
return 0;
}
-29
View File
@@ -1,29 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
inline void my_panic(sol::optional<std::string> maybe_msg) {
std::cerr << "Lua is in a panic state and will now abort() "
"the application"
<< std::endl;
if (maybe_msg) {
const std::string& msg = maybe_msg.value();
std::cerr << "\terror message: " << msg << std::endl;
}
// When this function exits, Lua will exhibit default
// behavior and abort()
}
int main(int, char*[]) {
sol::state lua(sol::c_call<decltype(&my_panic), &my_panic>);
// or, if you already have a lua_State* L
// lua_atpanic( L, sol::c_call<decltype(&my_panic),
// &my_panic> ); or, with state/state_view: sol::state_view
// lua(L); lua.set_panic( sol::c_call<decltype(&my_panic),
// &my_panic> );
// uncomment the below to see
// lua.script("boom_goes.the_dynamite");
return 0;
}
@@ -1,30 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
sol::state lua;
lua.open_libraries();
sol::environment my_env(lua, sol::create);
// set value, and we need to explicitly allow for
// access to "print", since a new environment hides
// everything that's not defined inside of it
// NOTE: hiding also hides library functions (!!)
// BE WARNED
my_env["var"] = 50;
my_env["print"] = lua["print"];
sol::environment my_other_env(
lua, sol::create, lua.globals());
// do not need to explicitly allow access to "print",
// since we used the "Set a fallback" version
// of the sol::environment constructor
my_other_env["var"] = 443;
// output: 50
lua.script("print(var)", my_env);
// output: 443
lua.script("print(var)", my_other_env);
return 0;
}
@@ -1,28 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
struct test {
int blah = 0;
};
test t;
sol::state lua;
lua.set_function("f", [&t]() { return t; });
lua.set_function("g", [&t]() -> test& { return t; });
lua.script("t1 = f()");
lua.script("t2 = g()");
test& from_lua_t1 = lua["t1"];
test& from_lua_t2 = lua["t2"];
// not the same: 'f' lambda copied
sol_c_assert(&from_lua_t1 != &t);
// the same: 'g' lambda returned reference
sol_c_assert(&from_lua_t2 == &t);
return 0;
}
-29
View File
@@ -1,29 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct object {
int value = 0;
};
int main(int, char*[]) {
std::cout << "==== runtime_extension =====" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<object>("object");
// runtime additions: through the sol API
lua["object"]["func"] = [](object& o) { return o.value; };
// runtime additions: through a lua script
lua.script(
"function object:print () print(self:func()) end");
// see it work
lua.script("local obj = object.new() \n obj:print()");
return 0;
}
-17
View File
@@ -1,17 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main() {
sol::state lua;
int x = 0;
lua.set_function("beep", [&x] { ++x; });
lua.script("beep()");
sol_c_assert(x == 1);
sol::function beep = lua["beep"];
beep();
sol_c_assert(x == 2);
return 0;
}
-31
View File
@@ -1,31 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
struct vars {
int boop = 0;
int bop() const {
return boop + 1;
}
};
int main() {
sol::state lua;
lua.new_usertype<vars>(
"vars", "boop", &vars::boop, "bop", &vars::bop);
lua.script(
"beep = vars.new()\n"
"beep.boop = 1\n"
"bopvalue = beep:bop()");
vars& beep = lua["beep"];
int bopvalue = lua["bopvalue"];
sol_c_assert(beep.boop == 1);
sol_c_assert(lua.get<vars>("beep").boop == 1);
sol_c_assert(beep.bop() == 2);
sol_c_assert(bopvalue == 2);
return 0;
}
-44
View File
@@ -1,44 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
std::cout << "=== safe_script usage ===" << std::endl;
sol::state lua;
// uses sol::script_default_on_error, which either panics or
// throws, depending on your configuration and compiler
// settings
try {
auto result1 = lua.safe_script("bad.code");
}
catch (const sol::error& e) {
std::cout << "an expected error has occurred: "
<< e.what() << std::endl;
}
// a custom handler that you write yourself
// is only called when an error happens with loading or
// running the script
auto result2 = lua.safe_script("123 bad.code",
[](lua_State*, sol::protected_function_result pfr) {
// pfr will contain things that went wrong, for
// either loading or executing the script the user
// can do whatever they like here, including
// throw. Otherwise...
sol::error err = pfr;
std::cout
<< "An error (an expected one) occurred: "
<< err.what() << std::endl;
// ... they need to return the
// protected_function_result
return pfr;
});
std::cout << std::endl;
return 0;
}
-50
View File
@@ -1,50 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
sol::state lua;
lua.open_libraries();
sol::function transferred_into;
lua["f"] = [&lua, &transferred_into](
sol::object t, sol::this_state this_L) {
std::cout << "state of main : "
<< (void*)lua.lua_state() << std::endl;
std::cout << "state of function : "
<< (void*)this_L.lua_state() << std::endl;
// pass original lua_State* (or
// sol::state/sol::state_view) transfers ownership from
// the state of "t", to the "lua" sol::state
transferred_into = sol::function(lua, t);
};
lua.script(R"(
i = 0
function test()
co = coroutine.create(
function()
local g = function() i = i + 1 end
f(g)
g = nil
collectgarbage()
end
)
coroutine.resume(co)
co = nil
collectgarbage()
end
)");
// give it a try
lua.safe_script("test()");
// should call 'g' from main thread, increment i by 1
transferred_into();
// check
int i = lua["i"];
sol_c_assert(i == 1);
return 0;
}
-157
View File
@@ -1,157 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <mutex>
#include <condition_variable>
#include <thread>
#include <variant>
#include <cstddef>
#include <iostream>
struct worker_data {
std::mutex until_ready_mutex;
std::condition_variable until_ready_condition;
bool is_ready = false;
bool is_processed = false;
sol::state worker_lua;
sol::bytecode payload;
std::variant<double, std::vector<double>> return_payload;
worker_data() {
worker_lua.open_libraries(sol::lib::base);
}
};
void worker_thread(worker_data& data) {
for (std::uint64_t loops = 0; true; ++loops) {
// Wait until main() sends data
std::unique_lock<std::mutex> data_lock(
data.until_ready_mutex);
data.until_ready_condition.wait(
data_lock, [&data] { return data.is_ready; });
if (data.payload.size() == 0) {
// signaling we are done
return;
}
// just for easier typing
sol::state& lua = data.worker_lua;
// we own the lock now, do the work
std::variant<double, std::vector<double>> result
= lua.safe_script(data.payload.as_string_view());
// store returning payload,
// clear current payload
data.return_payload = std::move(result);
data.payload.clear();
// Send result back to main
std::cout << "worker_thread data processing is "
"completed: signaling & unlocking\n";
data.is_processed = true;
data.is_ready = false;
data_lock.unlock();
data.until_ready_condition.notify_one();
}
}
int main() {
// main lua state
sol::state lua;
lua.open_libraries(sol::lib::base);
// set up functions, etc. etc.
lua.script("function f () return 4.5 end");
lua.script("function g () return { 1.1, 2.2, 3.3 } end");
// kick off worker
worker_data data;
std::thread worker(worker_thread, std::ref(data));
// main Lua state
bool done_working = false;
for (std::uint64_t loops = 0; !done_working; ++loops) {
// finished working? send nothing
// even loop? use f
// otherwise, use g
if (loops >= 3) {
data.payload.clear();
done_working = true;
}
else if ((loops % 2) == 0) {
sol::function target = lua["f"];
data.payload = target.dump();
}
else {
sol::function target = lua["g"];
data.payload = target.dump();
}
// send data to the worker thread
{
std::lock_guard<std::mutex> lk(
data.until_ready_mutex);
data.is_ready = true;
std::cout
<< "function serialized: sending to worker "
"thread to execute on Lua state...\n";
}
data.until_ready_condition.notify_one();
if (done_working) {
break;
}
// wait for the worker
{
std::unique_lock<std::mutex>
lock_waiting_for_worker(
data.until_ready_mutex);
data.until_ready_condition.wait(
lock_waiting_for_worker,
[&data] { return data.is_processed; });
data.is_processed = false;
}
auto data_processor = [](auto& returned_data) {
using option_type
= std::remove_cv_t<std::remove_reference_t<
decltype(returned_data)>>;
if constexpr (std::is_same_v<option_type,
double>) {
std::cout << "received a double: "
<< returned_data << "\n";
}
else if constexpr (std::is_same_v<option_type,
std::vector<double>>) {
std::cout
<< "received a std::vector<double>: { ";
for (std::size_t i = 0;
i < returned_data.size();
++i) {
std::cout << returned_data[i];
if (i
!= static_cast<std::size_t>(
returned_data.size() - 1)) {
std::cout << ", ";
}
}
std::cout << " }\n";
}
else {
std::cerr << "OH MY GOD YOU FORGOT TO "
"HANDLE A TYPE OF DATA FROM A "
"WORKER ABORT ABORT ABORT\n";
std::abort();
}
};
std::visit(data_processor, data.return_payload);
}
// join and wait for workers to come back
worker.join();
// workers are back, exit program
return 0;
}
-45
View File
@@ -1,45 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
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
sol_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
sol_c_assert(result2.valid());
// check in the second state if it was valid
sol::protected_function pf = lua2["a"];
int v = pf(25557);
sol_c_assert(v == 25557);
return 0;
}
-88
View File
@@ -1,88 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <unordered_map>
// use as-is,
// add as a member of your class,
// or derive from it and bind it appropriately
struct dynamic_object {
std::unordered_map<std::string, sol::object> entries;
void dynamic_set(std::string key, sol::stack_object value) {
auto it = entries.find(key);
if (it == entries.cend()) {
entries.insert(
it, { std::move(key), std::move(value) });
}
else {
std::pair<const std::string, sol::object>& kvp
= *it;
sol::object& entry = kvp.second;
entry = sol::object(std::move(value));
}
}
sol::object dynamic_get(std::string key) {
auto it = entries.find(key);
if (it == entries.cend()) {
return sol::lua_nil;
}
return it->second;
}
};
int main() {
std::cout << "=== dynamic_object ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<dynamic_object>("dynamic_object",
sol::meta_function::index,
&dynamic_object::dynamic_get,
sol::meta_function::new_index,
&dynamic_object::dynamic_set,
sol::meta_function::length,
[](dynamic_object& d) { return d.entries.size(); });
lua.safe_script(R"(
d1 = dynamic_object.new()
d2 = dynamic_object.new()
print(#d1) -- length operator
print(#d2)
function d2:run(lim)
local r = 0
for i=0,lim do
r = r + i
end
if (r % 2) == 1 then
print("odd")
end
return r
end
-- only added an entry to d2
print(#d1)
print(#d2)
-- only works on d2
local value = d2:run(5)
assert(value == 15)
)");
// does not work on d1: 'run' wasn't added to d1, only d2
auto script_result = lua.safe_script(
"local value = d1:run(5)", sol::script_pass_on_error);
sol_c_assert(!script_result.valid());
sol::error err = script_result;
std::cout << "received expected error: " << err.what()
<< std::endl;
std::cout << std::endl;
return 0;
}
-98
View File
@@ -1,98 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
// Simple sol2 version of the below
void simple(sol::this_state ts, sol::this_environment te) {
sol::state_view lua = ts;
if (te) {
sol::environment& env = te;
sol::environment freshenv = lua["freshenv"];
bool is_same_env = freshenv == env;
std::cout << "this_environment -- env == freshenv : "
<< is_same_env << std::endl;
}
std::cout << "this_environment -- no environment present"
<< std::endl;
}
// NOTE:
// THIS IS A LOW-LEVEL EXAMPLE, using pieces of sol2
// to facilitate better usage
// It is recommended you just do the simple version, as it is
// basically this code but it is sometimes useful to show the
// hoops you need to jump through to use the Lua C API
void complicated(sol::this_state ts) {
lua_State* L = ts;
lua_Debug info;
// Level 0 means current function (this C function, which is
// useless for our purposes) Level 1 means next call frame
// up the stack. This is probably the environment we're
// looking for?
int level = 1;
int pre_stack_size = lua_gettop(L);
if (lua_getstack(L, level, &info) != 1) {
// failure: call it quits
std::cout << "error: unable to traverse the stack"
<< std::endl;
lua_settop(L, pre_stack_size);
return;
}
// the "f" identifier is the most important here
// it pushes the function running at `level` onto the stack:
// we can get the environment from this
// the rest is for printing / debugging purposes
if (lua_getinfo(L, "fnluS", &info) == 0) {
// failure?
std::cout << "manually -- error: unable to get stack "
"information"
<< std::endl;
lua_settop(L, pre_stack_size);
return;
}
// Okay, so all the calls worked.
// Print out some information about this "level"
std::cout << "manually -- [" << level << "] "
<< info.short_src << ":" << info.currentline
<< " -- " << (info.name ? info.name : "<unknown>")
<< "[" << info.what << "]" << std::endl;
// Grab the function off the top of the stack
// remember: -1 means top, -2 means 1 below the top, and so
// on... 1 means the very bottom of the stack, 2 means 1
// more up, and so on to the top value...
sol::function f(L, -1);
// The environment can now be ripped out of the function
sol::environment env(sol::env_key, f);
if (!env.valid()) {
std::cout << "manually -- error: no environment to get"
<< std::endl;
lua_settop(L, pre_stack_size);
return;
}
sol::state_view lua(L);
sol::environment freshenv = lua["freshenv"];
bool is_same_env = freshenv == env;
std::cout << "manually -- env == freshenv : " << is_same_env
<< std::endl;
}
int main() {
std::cout << "=== environment snooping ===" << std::endl;
sol::state lua;
sol::environment freshenv(lua, sol::create, lua.globals());
lua["freshenv"] = freshenv;
lua.set_function("f", simple);
lua.set_function("g", complicated);
lua.script("f()", freshenv);
lua.script("g()", freshenv);
std::cout << std::endl;
return 0;
}
-37
View File
@@ -1,37 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== environment state ===" << std::endl;
sol::state lua;
lua.open_libraries();
sol::environment my_env(lua, sol::create);
// set value, and we need to explicitly allow for
// access to "print", since a new environment hides
// everything that's not defined inside of it
// NOTE: hiding also hides library functions (!!)
// BE WARNED
my_env["var"] = 50;
my_env["print"] = lua["print"];
sol::environment my_other_env(
lua, sol::create, lua.globals());
// do not need to explicitly allow access to "print",
// since we used the "Set a fallback" version
// of the sol::environment constructor
my_other_env["var"] = 443;
// output: 50
lua.script("print(var)", my_env);
// output: 443
lua.script("print(var)", my_other_env);
std::cout << std::endl;
return 0;
}
-27
View File
@@ -1,27 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== environment state 2 ===" << std::endl;
sol::state lua;
lua.open_libraries();
sol::environment env(lua, sol::create, lua.globals());
env["func"] = []() { return 42; };
sol::environment env2(lua, sol::create, lua.globals());
env2["func"] = []() { return 24; };
lua.script("function foo() print(func()) end", env);
lua.script("function foo() print(func()) end", env2);
env["foo"](); // prints 42
env2["foo"](); // prints 24
std::cout << std::endl;
return 0;
}
-63
View File
@@ -1,63 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
void test_environment(std::string key,
const sol::environment& env, const sol::state_view& lua) {
sol::optional<int> maybe_env_a = env[key];
sol::optional<int> maybe_global_a = lua[key];
if (maybe_global_a) {
std::cout << "\t'" << key << "' is "
<< maybe_global_a.value()
<< " in the global environment" << std::endl;
}
else {
std::cout
<< "\t'" << key
<< "' does not exist in the global environment"
<< std::endl;
}
if (maybe_env_a) {
std::cout << "\t'" << key << "' is "
<< maybe_env_a.value()
<< " in target environment" << std::endl;
}
else {
std::cout << "\t'" << key
<< "' does not exist in target environment"
<< std::endl;
}
}
int main(int, char**) {
std::cout << "=== environments ===" << std::endl;
sol::state lua;
// A global variable to see if we can "fallback" into it
lua["b"] = 2142;
// Create a new environment
sol::environment plain_env(lua, sol::create);
// Use it
lua.script("a = 24", plain_env);
std::cout << "-- target: plain_env" << std::endl;
test_environment("a", plain_env, lua);
test_environment("b", plain_env, lua);
std::cout << std::endl;
// Create an environment with a fallback
sol::environment env_with_fallback(
lua, sol::create, lua.globals());
// Use it
lua.script("a = 56", env_with_fallback);
std::cout << "-- target: env_with_fallback (fallback is "
"global table)"
<< std::endl;
test_environment("a", env_with_fallback, lua);
test_environment("b", env_with_fallback, lua);
std::cout << std::endl;
return 0;
}
@@ -1,85 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char**) {
sol::state lua;
lua.open_libraries(sol::lib::base);
// Environments can set on functions (scripts), userdata and
// threads let's look at functions
lua.script("f = function() return test end");
sol::function f = lua["f"];
sol::environment env_f(lua, sol::create);
env_f["test"] = 31;
bool env_f_set_success = sol::set_environment(env_f, f);
sol_c_assert(env_f_set_success);
// the function returns the value from the environment table
int result = f();
sol_c_assert(result == 31);
// You can also protect from variables
// being set without the 'local' specifier
lua.script("g = function() test = 5 end");
sol::function g = lua["g"];
sol::environment env_g(lua, sol::create);
bool env_g_set_success
= env_g.set_on(g); // same as set_environment
sol_c_assert(env_g_set_success);
g();
// the value can be retrieved from the env table
int test = env_g["test"];
sol_c_assert(test == 5);
// the global environment
// is not polluted at all, despite both functions being used
// and set
sol::object global_test = lua["test"];
sol_c_assert(!global_test.valid());
// You can retrieve environments in C++
// and check the environment of functions
// gotten from Lua
// get the environment from any sol::reference-styled type,
// including sol::object, sol::function, sol::table,
// sol::userdata ...
lua.set_function("check_f_env",
// capture necessary variable in C++ lambda
[&env_f](sol::object target) {
// pull out the environment from func using
// sol::env_key constructor
sol::environment target_env(sol::env_key, target);
int test_env_f = env_f["test"];
int test_target_env = target_env["test"];
// the environment for f the one gotten from
// `target` are the same
sol_c_assert(test_env_f == test_target_env);
sol_c_assert(test_env_f == 31);
sol_c_assert(env_f == target_env);
});
lua.set_function(
"check_g_env", [&env_g](sol::function target) {
// equivalent:
sol::environment target_env
= sol::get_environment(target);
int test_env_g = env_g["test"];
int test_target_env = target_env["test"];
sol_c_assert(test_env_g == test_target_env);
sol_c_assert(test_env_g == 5);
sol_c_assert(env_g == target_env);
});
lua.script("check_f_env(f)");
lua.script("check_g_env(g)");
return 0;
}
-83
View File
@@ -1,83 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
const auto& code = R"(
bark_power = 11;
function got_problems( error_msg )
return "got_problems handler: " .. error_msg
end
function woof ( bark_energy )
if bark_energy < 20 then
error("*whine*")
end
return (bark_energy * (bark_power / 4))
end
function woofers ( bark_energy )
if bark_energy < 10 then
error("*whine*")
end
return (bark_energy * (bark_power / 4))
end
)";
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script(code);
sol::protected_function problematic_woof = lua["woof"];
problematic_woof.set_error_handler(lua["got_problems"]);
auto firstwoof = problematic_woof(20);
if (firstwoof.valid()) {
// Can work with contents
double numwoof = firstwoof;
std::cout << "Got value: " << numwoof << std::endl;
}
else {
// An error has occured
sol::error err = firstwoof;
std::string what = err.what();
std::cout << what << std::endl;
}
// errors, calls handler and then returns a string error
// from Lua at the top of the stack
auto secondwoof = problematic_woof(19);
if (secondwoof.valid()) {
// Call succeeded
double numwoof = secondwoof;
std::cout << "Got value: " << numwoof << std::endl;
}
else {
// Call failed
// Note that if the handler was successfully called,
// this will include the additional appended error
// message information of "got_problems handler: " ...
sol::error err = secondwoof;
std::string what = err.what();
std::cout << what << std::endl;
}
// can also use optional to tell things
sol::optional<double> maybevalue = problematic_woof(19);
if (maybevalue) {
// Have a value, use it
double numwoof = maybevalue.value();
std::cout << "Got value: " << numwoof << std::endl;
}
else {
std::cout << "No value!" << std::endl;
}
std::cout << std::endl;
return 0;
}
-61
View File
@@ -1,61 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int my_exception_handler(lua_State* L,
sol::optional<const std::exception&> maybe_exception,
sol::string_view description) {
// L is the lua state, which you can wrap in a state_view if
// necessary maybe_exception will contain exception, if it
// exists description will either be the what() of the
// exception or a description saying that we hit the
// general-case catch(...)
std::cout << "An exception occurred in a function, here's "
"what it says ";
if (maybe_exception) {
std::cout << "(straight from the exception): ";
const std::exception& ex = *maybe_exception;
std::cout << ex.what() << std::endl;
}
else {
std::cout << "(from the description parameter): ";
std::cout.write(description.data(),
static_cast<std::streamsize>(description.size()));
std::cout << std::endl;
}
// you must push 1 element onto the stack to be
// transported through as the error object in Lua
// note that Lua -- and 99.5% of all Lua users and libraries
// -- expects a string so we push a single string (in our
// case, the description of the error)
return sol::stack::push(L, description);
}
void will_throw() {
throw std::runtime_error("oh no not an exception!!!");
}
int main() {
std::cout << "=== exception_handler ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.set_exception_handler(&my_exception_handler);
lua.set_function("will_throw", &will_throw);
sol::protected_function_result pfr = lua.safe_script(
"will_throw()", &sol::script_pass_on_error);
sol_c_assert(!pfr.valid());
sol::error err = pfr;
std::cout << err.what() << std::endl;
std::cout << std::endl;
return 0;
}
-82
View File
@@ -1,82 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
inline int my_add(int x, int y) {
return x + y;
}
struct multiplier {
int operator()(int x) {
return x * 10;
}
static int by_five(int x) {
return x * 5;
}
};
int main() {
std::cout << "=== functions ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
// setting a function is simple
lua.set_function("my_add", my_add);
// you could even use a lambda
lua.set_function(
"my_mul", [](double x, double y) { return x * y; });
// member function pointers and functors as well
lua.set_function("mult_by_ten", multiplier {});
lua.set_function("mult_by_five", &multiplier::by_five);
// assert that the functions work
lua.script("assert(my_add(10, 11) == 21)");
lua.script("assert(my_mul(4.5, 10) == 45)");
lua.script("assert(mult_by_ten(50) == 500)");
lua.script("assert(mult_by_five(10) == 50)");
// using lambdas, functions can have state.
int x = 0;
lua.set_function("inc", [&x]() { x += 10; });
// calling a stateful lambda modifies the value
lua.script("inc()");
sol_c_assert(x == 10);
if (x == 10) {
// Do something based on this information
std::cout << "Yahoo! x is " << x << std::endl;
}
// this can be done as many times as you want
lua.script(R"(
inc()
inc()
inc()
)");
sol_c_assert(x == 40);
if (x == 40) {
// Do something based on this information
std::cout << "Yahoo! x is " << x << std::endl;
}
// retrieval of a function is done similarly
// to other variables, using sol::function
sol::function add = lua["my_add"];
int value = add(10, 11);
// second way to call the function
int value2 = add.call<int>(10, 11);
sol_c_assert(value == 21);
sol_c_assert(value2 == 21);
if (value == 21 && value2 == 21) {
std::cout << "Woo, value is 21!" << std::endl;
}
std::cout << std::endl;
return 0;
}
@@ -1,54 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== functions empty args ===" << std::endl;
// sol::reference, sol::Stack_reference,
// sol::object (and main_* types) can all be
// used to capture "nil", or "none" when a function
// leaves it off
auto my_defaulting_function
= [](sol::object maybe_defaulted) -> int {
// if it's nil, it's "unused" or "inactive"
bool inactive = maybe_defaulted == sol::lua_nil;
if (inactive) {
return 0;
}
if (maybe_defaulted.is<int>()) {
int value = maybe_defaulted.as<int>();
return value;
}
return 1;
};
sol::state lua;
lua.open_libraries(sol::lib::base);
// copy function in (use std::ref to change this behavior)
lua.set_function(
"defaulting_function", my_defaulting_function);
sol::string_view code = R"(
result = defaulting_function(24)
result_nothing = defaulting_function()
result_nil = defaulting_function(nil)
result_string = defaulting_function('meow')
print('defaulting_function(24), returned:', result)
print('defaulting_function(), returned:', result_nothing)
print('defaulting_function(nil), returned:', result_nil)
print('defaulting_function(\'meow\'), returned:', result_string)
assert(result == 24)
assert(result_nothing == 0)
assert(result_nil == 0)
assert(result_string == 1)
)";
lua.safe_script(code);
std::cout << std::endl;
return 0;
}
@@ -1,47 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
class vector {
public:
double data[3];
vector() : data { 0, 0, 0 } {
}
double& operator[](int i) {
return data[i];
}
static double my_index(vector& v, int i) {
return v[i];
}
static void my_new_index(vector& v, int i, double x) {
v[i] = x;
}
};
int main() {
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<vector>("vector",
sol::constructors<sol::types<>>(),
sol::meta_function::index,
&vector::my_index,
sol::meta_function::new_index,
&vector::my_new_index);
lua.script(
"v = vector.new()\n"
"print(v[1])\n"
"v[2] = 3\n"
"print(v[2])\n");
vector& v = lua["v"];
sol_c_assert(v[0] == 0.0);
sol_c_assert(v[1] == 0.0);
sol_c_assert(v[2] == 3.0);
return 0;
}
-77
View File
@@ -1,77 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
sol::variadic_results call_it(sol::object function_name,
sol::variadic_args args, sol::this_environment env,
sol::this_state L) {
sol::state_view lua = L;
// default to global table as environment
sol::environment function_environment = lua.globals();
if (env) {
// if we have an environment, use that instead
function_environment = env;
}
// get and call the function
sol::protected_function pf
= function_environment[function_name];
sol::protected_function_result res = pf(args);
//
sol::variadic_results results;
if (!res.valid()) {
// something went wrong: log/crash/whatever
return results;
}
int returncount = res.return_count();
for (int i = 0; i < returncount; i++) {
// pass offset to get the object that was returned
sol::object obj = res.get<sol::object>(i);
results.push_back(obj);
}
// return the results
return results;
}
int main(int, char*[]) {
std::cout << "=== indirect function calls ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua["call_it"] = call_it;
// some functions to call
lua.script(R"(
function add (a, b)
return a + b;
end
function subtract (a, b)
return a - b;
end
function log (x)
print(x)
end
)");
// call the functions indirectly, using a name
lua.script(R"(
call_it("log", "hiyo")
call_it("log", 24)
subtract_result = call_it("subtract", 5, 1)
add_result = call_it("add", 5, 1)
)");
int subtract_result = lua["subtract_result"];
int add_result = lua["add_result"];
sol_c_assert(add_result == 6);
sol_c_assert(subtract_result == 4);
std::cout << std::endl;
return 0;
}
-23
View File
@@ -1,23 +0,0 @@
#define SOL_CHECK_ARGUMENTS 1
#include <sol/sol.hpp>
#include <cstdio>
bool is_file_std_out(sol::table data) {
sol::object maybe_file = data["file"];
if (maybe_file.is<luaL_Stream&>()) {
luaL_Stream& filestream = data["file"];
return filestream.f == stdout;
}
return false;
}
int main() {
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::io);
lua["is_std_out"] = &is_file_std_out;
lua.script("assert(is_std_out{ file = io.stdout })");
return 0;
}
-114
View File
@@ -1,114 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <string>
struct int_entry {
int value;
int_entry() : value(0) {
}
int_entry(int v) : value(v) {
}
std::string to_string() const {
return "int_entry(" + std::to_string(value) + ")";
}
bool operator==(const int_entry& e) const {
return value == e.value;
}
};
int main(int, char*[]) {
std::cout << "=== sol::lua_value/sol::array_value ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base, sol::lib::io);
sol::lua_value lv_int(lua, 56);
sol::lua_value lv_int_table(lua, { 1, 2, 3, 4, 5 });
sol::lua_value lv_map(lua,
{ { "bark bark", "meow hiss!" },
{ 3, 4 },
{ ":D", 6 } });
sol::lua_value lv_mixed_table(lua,
sol::array_value {
1, int_entry(2), 3, int_entry(4), 5 });
sol::lua_value lv_mixed_nested_table(lua,
sol::array_value { 1,
int_entry(2),
3,
int_entry(4),
sol::array_value { 5, 6, int_entry(7), "8" } });
const auto& code = R"(
function real_print_recursive (e, level)
local et = type(e)
if et == 'table' then
io.write("{ ")
local iters = 0
for k, v in pairs(e) do
if iters ~= 0 then
io.write(", ")
end
real_print_recursive(k, level + 1)
io.write(": ")
real_print_recursive(v, level + 1)
iters = iters + 1
end
io.write(" }")
elseif et == 'string' then
io.write('"')
io.write(e)
io.write('"')
else
io.write(tostring(e))
end
if level == 0 then
io.write("\n")
end
end
function print_recursive (e)
real_print_recursive(e, 0)
end
)";
sol::optional<sol::error> maybe_error
= lua.safe_script(code, sol::script_pass_on_error);
if (maybe_error) {
std::cerr << maybe_error->what() << std::endl;
return 1;
}
sol::function print_recursive = lua["print_recursive"];
// show it printed out
std::cout << "lv_int: " << std::endl;
print_recursive(lv_int);
std::cout << std::endl;
std::cout << "lv_int_table: " << std::endl;
print_recursive(lv_int_table);
std::cout << std::endl;
std::cout << "lv_map: " << std::endl;
print_recursive(lv_map);
std::cout << std::endl;
std::cout << "lv_mixed_table: " << std::endl;
print_recursive(lv_mixed_table);
std::cout << std::endl;
std::cout << "lv_mixed_nested_table: " << std::endl;
print_recursive(lv_mixed_nested_table);
std::cout << std::endl;
std::cout << std::endl;
return 0;
}
-195
View File
@@ -1,195 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <unordered_map>
struct thing {
int member_variable = 5;
double member_function() const {
return member_variable / 2.0;
}
};
#define TEMPLATE_AUTO(x) decltype(x), x
// cheap storage: in reality, you'd need to find a
// better way of handling this.
// or not! It's up to you.
static std::unordered_map<sol::string_view, sol::object>
thing_function_associations;
static std::unordered_map<sol::string_view, sol::object>
thing_variable_associations;
void register_thing_type(sol::state& lua) {
thing_variable_associations.emplace_hint(
thing_variable_associations.cend(),
"member_variable",
sol::object(lua.lua_state(),
sol::in_place,
&sol::c_call<TEMPLATE_AUTO(
&thing::member_variable)>));
thing_function_associations.emplace_hint(
thing_function_associations.cend(),
"member_function",
sol::object(lua.lua_state(),
sol::in_place,
&sol::c_call<TEMPLATE_AUTO(
&thing::member_function)>));
struct call_handler {
static int lookup_function(lua_State* L) {
sol::stack_object source(L, 1);
sol::stack_object key(L, 2);
if (!source.is<thing>()) {
return luaL_error(L,
"given an incorrect object for this "
"call");
}
sol::optional<sol::string_view> maybe_svkey
= key.as<sol::optional<sol::string_view>>();
if (maybe_svkey) {
{
// functions are different from
// variables functions, when obtain with
// the syntax obj.f, obj.f(), and
// obj:f() must return the function
// itself so we just push it realy into
// our target
auto it
= thing_function_associations.find(
*maybe_svkey);
if (it
!= thing_function_associations
.cend()) {
return it->second.push(L);
}
}
{
// variables are different than funtions
// when someone does `obj.a`, they
// expect this __index call (this lookup
// function) to return to them the value
// itself they're seeing so we call out
// lua_CFunction that we serialized
// earlier
auto it
= thing_variable_associations.find(
*maybe_svkey);
if (it
!= thing_variable_associations
.cend()) {
// note that calls generated by
// sol2 for member variables expect
// the stack ordering to be 2(, 3,
// ..., n) -- value(s) 1 -- source
// so we destroy the key on the
// stack
sol::stack::remove(L, 2, 1);
lua_CFunction cf
= it->second
.as<lua_CFunction>();
return cf(L);
}
}
}
return sol::stack::push(L, sol::lua_nil);
}
static int insertion_function(lua_State* L) {
sol::stack_object source(L, 1);
sol::stack_object key(L, 2);
sol::stack_object value(L, 3);
if (!source.is<thing>()) {
return luaL_error(L,
"given an incorrect object for this "
"call");
}
// write to member variables, etc. etc...
sol::optional<sol::string_view> maybe_svkey
= key.as<sol::optional<sol::string_view>>();
if (maybe_svkey) {
{
// variables are different than funtions
// when someone does `obj.a`, they
// expect this __index call (this lookup
// function) to return to them the value
// itself they're seeing so we call out
// lua_CFunction that we serialized
// earlier
auto it
= thing_variable_associations.find(
*maybe_svkey);
if (it
!= thing_variable_associations
.cend()) {
// note that calls generated by
// sol2 for member variables expect
// the stack ordering to be 2(, 3,
// ..., n) -- value(s) 1 -- source
// so we remove the key value
sol::stack::remove(L, 2, 1);
lua_CFunction cf
= it->second
.as<lua_CFunction>();
return cf(L);
}
else {
// write to member variable, maybe
// override function if your class
// allows for it?
(void)value;
}
}
// exercise for reader:
// how do you override functions on the
// metatable with proper syntax, but error
// when the type is an "instance" object?
}
return 0;
}
};
lua.new_usertype<thing>("thing");
sol::table metatable = lua["thing"];
metatable[sol::meta_method::index]
= &call_handler::lookup_function;
metatable[sol::meta_method::new_index]
= &call_handler::insertion_function;
}
void unregister_thing_type(sol::state&) {
thing_function_associations.clear();
thing_variable_associations.clear();
}
int main() {
std::cout << "=== metatable with custom-built (static) "
"handling ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
// register custom type + storage
register_thing_type(lua);
lua.script(R"(t = thing.new()
print(t.member_variable)
print(t:member_function())
t.member_variable = 24
print(t.member_variable)
print(t:member_function())
)");
// clear storage
unregister_thing_type(lua);
std::cout << std::endl;
return 0;
}
-34
View File
@@ -1,34 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
struct bark {
int operator()(int x) {
return x;
}
};
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<bark>("bark",
sol::meta_function::call_function,
&bark::operator());
bark b;
lua.set("b", &b);
sol::table b_as_table = lua["b"];
sol::table b_metatable = b_as_table[sol::metatable_key];
sol::function b_call = b_metatable["__call"];
sol::function b_as_function = lua["b"];
int result1 = b_as_function(1);
// pass 'self' directly to argument
int result2 = b_call(b, 1);
sol_c_assert(result1 == result2);
sol_c_assert(result1 == 1);
sol_c_assert(result2 == 1);
}
-82
View File
@@ -1,82 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <tuple>
#include <iostream>
int main() {
std::cout << "=== multi results ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
// multi-return functions are supported using
// std::tuple as the transfer type,
// sol::as_returns for containers,
// and sol::variadic_results for more special things
lua.set_function("multi_tuple",
[] { return std::make_tuple(10, "goodbye"); });
lua.script("print('calling multi_tuple')");
lua.script("print(multi_tuple())");
lua.script("x, y = multi_tuple()");
lua.script("assert(x == 10 and y == 'goodbye')");
auto multi = lua.get<sol::function>("multi_tuple");
int first;
std::string second;
// tie the values
sol::tie(first, second) = multi();
// use the values
sol_c_assert(first == 10);
sol_c_assert(second == "goodbye");
// sol::as_returns
// works with any iterable,
// but we show off std::vector here
lua.set_function("multi_containers", [](bool add_extra) {
std::vector<int> values { 55, 66 };
if (add_extra) {
values.push_back(77);
}
return sol::as_returns(std::move(values));
});
lua.script("print('calling multi_containers')");
lua.script("print(multi_containers(false))");
lua.script("a, b, c = multi_containers(true)");
int a = lua["a"];
int b = lua["b"];
int c = lua["c"];
sol_c_assert(a == 55);
sol_c_assert(b == 66);
sol_c_assert(c == 77);
// sol::variadic_results
// you can push objects of different types
// note that sol::this_state is a transparent
// argument: you don't need to pass
// that state through Lua
lua.set_function(
"multi_vars", [](int a, bool b, sol::this_state L) {
sol::variadic_results values;
values.push_back(
{ L, sol::in_place_type<int>, a });
values.push_back(
{ L, sol::in_place_type<bool>, b });
values.push_back({ L, sol::in_place, "awoo" });
return values;
});
lua.script("print('calling multi_vars')");
lua.script("print(multi_vars(2, false))");
lua.script("t, u, v = multi_vars(42, true)");
int t = lua["t"];
bool u = lua["u"];
std::string v = lua["v"];
sol_c_assert(t == 42);
sol_c_assert(u);
sol_c_assert(v == "awoo");
return 0;
}
-98
View File
@@ -1,98 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <memory>
#include <iostream>
struct thing {
int a = 20;
thing() = default;
thing(int a) : a(a) {
}
};
struct super_thing : thing {
int b = 40;
};
struct unrelated { };
int main(int, char*[]) {
std::cout << "=== optional with iteration ===" << std::endl;
sol::state lua;
// Comment out the new_usertype call
// to prevent derived class "super_thing"
// from being picked up and cast to its base
// class
lua.new_usertype<super_thing>(
"super_thing", sol::base_classes, sol::bases<thing>());
// Make a few things
lua["t1"] = thing {};
lua["t2"] = super_thing {};
lua["t3"] = unrelated {};
// And a table
lua["container"] = lua.create_table_with(
0, thing { 50 }, 1, unrelated {}, 4, super_thing {});
std::vector<std::reference_wrapper<thing>> things;
// Our recursive function
// We use some lambda techniques and pass the function
// itself itself so we can recurse, but a regular function
// would work too!
auto fx = [&things](auto& f, auto& tbl) -> void {
// You can iterate through a table: it has
// begin() and end()
// like standard containers
for (auto key_value_pair : tbl) {
// Note that iterators are extremely frail
// and should not be used outside of
// well-constructed for loops
// that use pre-increment ++,
// or C++ ranged-for loops
const sol::object& key = key_value_pair.first;
const sol::object& value = key_value_pair.second;
sol::type t = value.get_type();
switch (t) {
case sol::type::table: {
sol::table inner = value.as<sol::table>();
f(f, inner);
} break;
case sol::type::userdata: {
// This allows us to check if a userdata is
// a specific class type
sol::optional<thing&> maybe_thing
= value.as<sol::optional<thing&>>();
if (maybe_thing) {
thing& the_thing = maybe_thing.value();
if (key.is<std::string>()) {
std::cout << "key "
<< key.as<std::string>()
<< " is a thing -- ";
}
else if (key.is<int>()) {
std::cout << "key "
<< key.as<int>()
<< " is a thing -- ";
}
std::cout << "thing.a ==" << the_thing.a
<< std::endl;
things.push_back(the_thing);
}
} break;
default:
break;
}
}
};
fx(fx, lua);
std::cout << std::endl;
return 0;
}
-37
View File
@@ -1,37 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
inline int my_add(int x, int y) {
return x + y;
}
inline std::string make_string(std::string input) {
return "string: " + input;
}
int main() {
std::cout << "=== overloading ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
// you can overload functions
// just pass in the different functions
// you want to pack into a single name:
// make SURE they take different types!
lua.set_function("func", sol::overload([](int x) { return x; }, make_string, my_add));
// All these functions are now overloaded through "func"
lua.script(R"(
print(func(1))
print(func("bark"))
print(func(1,2))
)");
std::cout << std::endl;
return 0;
}
@@ -1,44 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int func_1(int value) {
return 20 + value;
}
std::string func_2(std::string text) {
return "received: " + text;
}
sol::variadic_results fallback(
sol::this_state ts, sol::variadic_args args) {
sol::variadic_results r;
if (args.size() == 2) {
r.push_back({ ts,
sol::in_place,
args.get<int>(0) + args.get<int>(1) });
}
else {
r.push_back({ ts, sol::in_place, 52 });
}
return r;
}
int main(int, char*[]) {
std::cout << "=== overloading with fallback ==="
<< std::endl;
sol::state lua;
lua.open_libraries();
lua.set_function(
"f", sol::overload(func_1, func_2, fallback));
lua.script("print(f(1))"); // func_1
lua.script("print(f('hi'))"); // func_2
lua.script("print(f(22, 11))"); // fallback
lua.script("print(f({}))"); // fallback
return 0;
}
-67
View File
@@ -1,67 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct pup {
int barks = 0;
void bark() {
++barks; // bark!
}
bool is_cute() const {
return true;
}
};
void ultra_bark(pup& p, int barks) {
for (; barks-- > 0;)
p.bark();
}
void picky_bark(pup& p, std::string s) {
if (s == "bark")
p.bark();
}
int main() {
std::cout << "=== overloading with members ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.set_function("bark", sol::overload(ultra_bark, []() {
return "the bark from nowhere";
}));
lua.new_usertype<pup>("pup",
// regular function
"is_cute",
&pup::is_cute,
// overloaded function
"bark",
sol::overload(&pup::bark, &picky_bark));
const auto& code = R"(
barker = pup.new()
print(barker:is_cute())
barker:bark() -- calls member function pup::bark
barker:bark("meow") -- picky_bark, no bark
barker:bark("bark") -- picky_bark, bark
bark(barker, 20) -- calls ultra_bark
print(bark()) -- calls lambda which returns that string
)";
lua.script(code);
pup& barker = lua["barker"];
std::cout << barker.barks << std::endl;
sol_c_assert(barker.barks == 22);
std::cout << std::endl;
return 0;
}
@@ -1,45 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
std::cout << "=== override-able member functions ==="
<< std::endl;
struct thingy {
sol::function paint;
thingy(sol::this_state L)
: paint(sol::make_reference<sol::function>(
L.lua_state(), &thingy::default_paint)) {
}
void default_paint() {
std::cout << "p" << std::endl;
}
};
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<thingy>("thingy",
sol::constructors<thingy(sol::this_state)>(),
"paint",
&thingy::paint);
sol::string_view code = R"(
obj = thingy.new()
obj:paint()
obj.paint = function (self) print("g") end
obj:paint()
function obj:paint () print("s") end
obj:paint()
)";
lua.safe_script(code);
std::cout << std::endl;
return 0;
}
-96
View File
@@ -1,96 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <map>
#include <iostream>
struct my_thing {
std::map<std::string, int> m {
{ "bark", 20 },
{ "woof", 60 },
{ "borf", 30 },
{ "awoo", 5 },
};
my_thing() {
}
};
struct lua_iterator_state {
typedef std::map<std::string, int>::iterator it_t;
it_t it;
it_t last;
lua_iterator_state(my_thing& mt)
: it(mt.m.begin()), last(mt.m.end()) {
}
};
std::tuple<sol::object, sol::object> my_next(
sol::user<lua_iterator_state&> user_it_state,
sol::this_state l) {
// this gets called
// to start the first iteration, and every
// iteration there after
// the state you passed in my_pairs is argument 1
// the key value is argument 2, but we do not
// care about the key value here
lua_iterator_state& it_state = user_it_state;
auto& it = it_state.it;
if (it == it_state.last) {
// return nil to signify that
// there's nothing more to work with.
return std::make_tuple(sol::object(sol::lua_nil),
sol::object(sol::lua_nil));
}
auto itderef = *it;
// 2 values are returned (pushed onto the stack):
// the key and the value
// the state is left alone
auto r = std::make_tuple(
sol::object(l, sol::in_place, it->first),
sol::object(l, sol::in_place, it->second));
// the iterator must be moved forward one before we return
std::advance(it, 1);
return r;
}
auto my_pairs(my_thing& mt) {
// pairs expects 3 returns:
// the "next" function on how to advance,
// the "table" itself or some state,
// and an initial key value (can be nil)
// prepare our state
lua_iterator_state it_state(mt);
// sol::user is a space/time optimization over regular
// usertypes, it's incompatible with regular usertypes and
// stores the type T directly in lua without any pretty
// setup saves space allocation and a single dereference
return std::make_tuple(&my_next,
sol::user<lua_iterator_state>(std::move(it_state)),
sol::lua_nil);
}
int main(int, char*[]) {
std::cout << "===== pairs (advanced) =====" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<my_thing>(
"my_thing", sol::meta_function::pairs, my_pairs);
#if SOL_LUA_VERSION_I_ > 501
lua.safe_script(R"(
local mt = my_thing.new()
for k, v in pairs(mt) do
print(k, v)
end
)");
#endif // Does not work on Lua 5.1
std::cout << std::endl;
return 0;
}
-91
View File
@@ -1,91 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <map>
#include <iostream>
struct my_thing {
std::map<std::string, int> m {
{ "bark", 20 },
{ "woof", 60 },
{ "borf", 30 },
{ "awoo", 5 },
};
my_thing() {
}
};
struct lua_iterator_state {
typedef std::map<std::string, int>::iterator it_t;
it_t it;
it_t last;
lua_iterator_state(my_thing& mt)
: it(mt.m.begin()), last(mt.m.end()) {
}
};
int my_next(lua_State* L) {
// this gets called
// to start the first iteration, and every
// iteration there after
// the state you passed in pairs is argument 1
// the key value is argument 2
// we do not care about the key value here
lua_iterator_state& it_state
= sol::stack::get<sol::user<lua_iterator_state>>(L, 1);
auto& it = it_state.it;
if (it == it_state.last) {
return sol::stack::push(L, sol::lua_nil);
}
auto itderef = *it;
// 2 values are returned (pushed onto the stack):
// the key and the value
// the state is left alone
int pushed = sol::stack::push(L, itderef.first);
pushed += sol::stack::push_reference(L, itderef.second);
std::advance(it, 1);
return pushed;
}
int my_pairs(lua_State* L) {
my_thing& mt = sol::stack::get<my_thing>(L, 1);
lua_iterator_state it_state(mt);
// pairs expects 3 returns:
// the "next" function on how to advance,
// the "table" itself or some state,
// and an initial key value (can be nil)
// next function controls iteration
int pushed = sol::stack::push(L, my_next);
pushed += sol::stack::push<sol::user<lua_iterator_state>>(
L, std::move(it_state));
pushed += sol::stack::push(L, sol::lua_nil);
return pushed;
}
int main(int, char*[]) {
std::cout << "===== pairs (using raw Lua C functions) "
"(advanced) ====="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<my_thing>(
"my_thing", sol::meta_function::pairs, &my_pairs);
#if SOL_LUA_VERSION_I_ > 501
lua.safe_script(R"(
local mt = my_thing.new()
for k, v in pairs(mt) do
print(k, v)
end
)");
#endif // Does not work on Lua 5.1 and below
std::cout << std::endl;
return 0;
}
-29
View File
@@ -1,29 +0,0 @@
-- call single argument integer constructor
p1 = player.new(2)
-- p2 is still here from being
-- set with lua["p2"] = player(0); below
local p2shoots = p2:shoot()
assert(not p2shoots)
-- had 0 ammo
-- set variable property setter
p1.hp = 545;
-- get variable through property getter
print(p1.hp);
local did_shoot_1 = p1:shoot()
print(did_shoot_1)
print(p1.bullets)
local did_shoot_2 = p1:shoot()
print(did_shoot_2)
print(p1.bullets)
local did_shoot_3 = p1:shoot()
print(did_shoot_3)
-- can read
print(p1.bullets)
-- would error: is a readonly variable, cannot write
-- p1.bullets = 20
p1:boost()
-59
View File
@@ -1,59 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
class Player {
public:
int get_hp() const {
return hp;
}
void set_hp(int value) {
hp = value;
}
int get_max_hp() const {
return hp;
}
void set_max_hp(int value) {
maxhp = value;
}
private:
int hp = 50;
int maxhp = 50;
};
int main(int, char*[]) {
std::cout << "=== properties from C++ functions ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.set("theplayer", Player());
// Yes, you can register after you set a value and it will
// connect up the usertype automatically
lua.new_usertype<Player>("Player",
"hp",
sol::property(&Player::get_hp, &Player::set_hp),
"maxHp",
sol::property(
&Player::get_max_hp, &Player::set_max_hp));
const auto& code = R"(
-- variable syntax, calls functions
theplayer.hp = 20
print('hp:', theplayer.hp)
print('max hp:', theplayer.maxHp)
)";
lua.script(code);
return 0;
}
-26
View File
@@ -1,26 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
struct protect_me {
int gen(int x) {
return x;
}
};
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<protect_me>(
"protect_me", "gen", sol::protect(&protect_me::gen));
lua.script(R"__(
pm = protect_me.new()
value = pcall(pm.gen,"wrong argument")
)__");
bool value = lua["value"];
sol_c_assert(!value);
return 0;
}
-49
View File
@@ -1,49 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
std::cout << "=== protected_functions ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
// A complicated function which can error out
// We define both in terms of Lua code
lua.script(R"(
function handler (message)
return "Handled this message: " .. message
end
function f (a)
if a < 0 then
error("negative number detected")
end
return a + 5
end
)");
// Get a protected function out of Lua
sol::protected_function f(lua["f"], lua["handler"]);
sol::protected_function_result result = f(-500);
if (result.valid()) {
// Call succeeded
int x = result;
std::cout << "call succeeded, result is " << x
<< std::endl;
}
else {
// Call failed
sol::error err = result;
std::string what = err.what();
std::cout << "call failed, sol::error::what() is "
<< what << std::endl;
// 'what' Should read
// "Handled this message: negative number detected"
}
std::cout << std::endl;
}
-51
View File
@@ -1,51 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct object {
void my_func() {
std::cout << "hello\n";
}
};
int deny(lua_State* L) {
return luaL_error(L, "HAH! Deniiiiied!");
}
int main(int, char*[]) {
sol::state lua;
lua.open_libraries(sol::lib::base);
object my_obj;
sol::table obj_table = lua.create_named_table("object");
sol::table obj_metatable = lua.create_table_with();
obj_metatable.set_function(
"my_func", &object::my_func, &my_obj);
// Set whatever else you need to
// on the obj_metatable,
// not on the obj_table itself!
// Properly self-index metatable to block things
obj_metatable[sol::meta_function::new_index] = deny;
obj_metatable[sol::meta_function::index] = obj_metatable;
// Set it on the actual table
obj_table[sol::metatable_key] = obj_metatable;
try {
lua.script(R"(
print(object.my_func)
object["my_func"] = 24
print(object.my_func)
)");
}
catch (const std::exception& e) {
std::cout << "an expected error occurred: " << e.what()
<< std::endl;
}
return 0;
}
-53
View File
@@ -1,53 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct some_class {
int bark = 2012;
};
sol::table open_mylib(sol::this_state s) {
sol::state_view lua(s);
sol::table module = lua.create_table();
module["func"] = []() {
/* super cool function here */
return 2;
};
// register a class too
module.new_usertype<some_class>(
"some_class", "bark", &some_class::bark);
return module;
}
int main() {
std::cout << "=== require ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::package, sol::lib::base);
// sol::c_call takes functions at the template level
// and turns it into a lua_CFunction
// alternatively, one can use
// sol::c_call<sol::wrap<callable_struct,
// callable_struct{}>> to make the call if it's a constexpr
// struct
lua.require("my_lib",
sol::c_call<decltype(&open_mylib), &open_mylib>);
// run some code against your require'd library
lua.safe_script(R"(
s = my_lib.some_class.new()
assert(my_lib.func() == 2)
s.bark = 20
)");
some_class& s = lua["s"];
sol_c_assert(s.bark == 20);
std::cout << "s.bark = " << s.bark << std::endl;
std::cout << std::endl;
return 0;
}
@@ -1,81 +0,0 @@
// Thanks to OrfeasZ for their answer to
// an issue for this example!
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <exception>
// Use raw function of form "int(lua_State*)"
// -- this is called a "raw C function",
// and matches the type for lua_CFunction
int LoadFileRequire(lua_State* L) {
// use sol2 stack API to pull
// "first argument"
std::string path = sol::stack::get<std::string>(L, 1);
if (path == "a") {
std::string script = R"(
print("Hello from module land!")
test = 123
return "bananas"
)";
// load "module", but don't run it
luaL_loadbuffer(
L, script.data(), script.size(), path.c_str());
// returning 1 object left on Lua stack:
// a function that, when called, executes the script
// (this is what lua_loadX/luaL_loadX functions return
return 1;
}
sol::stack::push(
L, "This is not the module you're looking for!");
return 1;
}
int main() {
std::cout << "=== require override behavior ==="
<< std::endl;
sol::state lua;
// need base for print,
// need package for package/searchers/require
lua.open_libraries(sol::lib::base, sol::lib::package);
lua.clear_package_loaders();
lua.add_package_loader(LoadFileRequire);
// this will call our function for
// the searcher and it will succeed
auto a_result = lua.safe_script(R"(
local a = require("a")
print(a)
print(test)
)",
sol::script_pass_on_error);
sol_c_assert(a_result.valid());
try {
// this will always fail
auto b_result = lua.safe_script(R"(
local b = require("b")
print(b)
)",
sol::script_throw_on_error);
// this will not be executed because of the throw,
// but it better be true regardless!
sol_c_assert(!b_result.valid());
}
catch (const std::exception& ex) {
// Whenever sol2 throws an exception from panic,
// catch
std::cout << "Something went wrong, as expected:\n"
<< ex.what() << std::endl;
// and CRASH / exit the application
return 0;
}
// If we get here something went wrong...!
return -1;
}
-40
View File
@@ -1,40 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct object {
int value = 0;
};
int main(int, char*[]) {
std::cout << "=== runtime_additions ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<object>("object");
// runtime additions: through the sol API
lua["object"]["func"] = [](object& o) {
++o.value;
return o.value;
};
// runtime additions: through a lua script
lua.script(R"(
function object:print ()
print(self:func())
end
)");
// see it work
lua.script(R"(
obj = object.new()
obj:print()
)");
object& obj = lua["obj"];
sol_c_assert(obj.value == 1);
return 0;
}
-103
View File
@@ -1,103 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char**) {
std::cout << "=== script error handling ===" << std::endl;
sol::state lua;
std::string code = R"(
bad&$#*$syntax
bad.code = 2
return 24
)";
/* OPTION 1 */
// Handling code like this can be robust
// If you disable exceptions, then obviously you would
// remove the try-catch branches, and then rely on the
// `lua_atpanic` function being called and trapping errors
// there before exiting the application
{
// script_default_on_error throws / panics when the
// code is bad: trap the error
try {
int value = lua.script(
code, sol::script_default_on_error);
// This will never be reached
std::cout << value << std::endl;
sol_c_assert(value == 24);
}
catch (const sol::error& err) {
std::cout << "Something went horribly wrong: "
"thrown error"
<< "\n\t" << err.what() << std::endl;
}
}
/* OPTION 2 */
// Use the script_pass_on_error handler
// this simply passes through the protected_function_result,
// rather than throwing it or calling panic
// This will check code validity and also whether or not it
// runs well
{
sol::protected_function_result result
= lua.script(code, sol::script_pass_on_error);
sol_c_assert(!result.valid());
if (!result.valid()) {
sol::error err = result;
sol::call_status status = result.status();
std::cout << "Something went horribly wrong: "
<< sol::to_string(status) << " error"
<< "\n\t" << err.what() << std::endl;
}
}
/* OPTION 3 */
// This is a lower-level, more explicit way to load code
// This explicitly loads the code, giving you access to any
// errors plus the load status then, it turns the loaded
// code into a sol::protected_function which is then called
// so that the code can run you can then check that too, for
// any errors The two previous approaches are recommended
{
sol::load_result loaded_chunk = lua.load(code);
sol_c_assert(!loaded_chunk.valid());
if (!loaded_chunk.valid()) {
sol::error err = loaded_chunk;
sol::load_status status = loaded_chunk.status();
std::cout << "Something went horribly wrong "
"loading the code: "
<< sol::to_string(status) << " error"
<< "\n\t" << err.what() << std::endl;
}
else {
// Because the syntax is bad, this will never be
// reached
sol_c_assert(false);
// If there is a runtime error (lua GC memory
// error, nil access, etc.) it will be caught here
sol::protected_function script_func
= loaded_chunk
.get<sol::protected_function>();
sol::protected_function_result result
= script_func();
if (!result.valid()) {
sol::error err = result;
sol::call_status status = result.status();
std::cout
<< "Something went horribly wrong "
"running the code: "
<< sol::to_string(status) << " error"
<< "\n\t" << err.what() << std::endl;
}
}
}
std::cout << std::endl;
return 0;
}
-53
View File
@@ -1,53 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
// NOTE:
// There are TWO ways to retrieve the "this"
// object from calls, when it comes to constructors and regular
// member functions please pay attention to both: this is a
// low-level operation!
int main() {
struct thing {
thing(sol::this_state ts) {
lua_State* L = ts;
// references the object that called this function
// in constructors:
sol::stack_object selfobj(L, 1);
// definitely the same
thing& self = selfobj.as<thing>();
sol_c_assert(&self == this);
}
void func(sol::this_state ts) const {
lua_State* L = ts;
// references the object that called this function
// in regular member functions:
sol::stack_object selfobj(L, 1);
// "1" is the bottom of the Lua stack
// 2 is one up, so on and so forth...
thing& self = selfobj.as<thing>();
// definitely the same
sol_c_assert(&self == this);
}
};
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<thing>("thing",
sol::constructors<thing(sol::this_state)>(),
"func",
&thing::func);
lua.script(R"(
obj = thing.new()
obj:func()
)");
return 0;
}
-120
View File
@@ -1,120 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct my_type {
int value = 10;
my_type() {
std::cout << "my_type at " << static_cast<void*>(this)
<< " being default constructed!"
<< std::endl;
}
my_type(const my_type& other) : value(other.value) {
std::cout << "my_type at " << static_cast<void*>(this)
<< " being copy constructed!" << std::endl;
}
my_type(my_type&& other) : value(other.value) {
std::cout << "my_type at " << static_cast<void*>(this)
<< " being move-constructed!" << std::endl;
}
my_type& operator=(const my_type& other) {
value = other.value;
std::cout << "my_type at " << static_cast<void*>(this)
<< " being copy-assigned to!" << std::endl;
return *this;
}
my_type& operator=(my_type&& other) {
value = other.value;
std::cout << "my_type at " << static_cast<void*>(this)
<< " being move-assigned to!" << std::endl;
return *this;
}
~my_type() {
std::cout << "my_type at " << static_cast<void*>(this)
<< " being destructed!" << std::endl;
}
};
int main() {
std::cout << "=== shared_ptr support ===" << std::endl;
sol::state lua;
lua.new_usertype<my_type>(
"my_type", "value", &my_type::value);
{
std::shared_ptr<my_type> shared
= std::make_shared<my_type>();
lua["shared"] = std::move(shared);
}
{
std::cout << "getting reference to shared_ptr..."
<< std::endl;
std::shared_ptr<my_type>& ref_to_shared_ptr
= lua["shared"];
std::cout << "\tshared.use_count(): "
<< ref_to_shared_ptr.use_count()
<< std::endl;
my_type& ref_to_my_type = lua["shared"];
std::cout << "\tafter getting reference to my_type: "
<< ref_to_shared_ptr.use_count()
<< std::endl;
my_type* ptr_to_my_type = lua["shared"];
std::cout << "\tafter getting pointer to my_type: "
<< ref_to_shared_ptr.use_count()
<< std::endl;
sol_c_assert(
ptr_to_my_type == ref_to_shared_ptr.get());
sol_c_assert(
&ref_to_my_type == ref_to_shared_ptr.get());
sol_c_assert(ref_to_shared_ptr->value == 10);
// script affects all of them equally
lua.script("shared.value = 20");
sol_c_assert(ptr_to_my_type->value == 20);
sol_c_assert(ref_to_my_type.value == 20);
sol_c_assert(ref_to_shared_ptr->value == 20);
}
{
std::cout << "getting copy of shared_ptr..."
<< std::endl;
std::shared_ptr<my_type> copy_of_shared_ptr
= lua["shared"];
std::cout << "\tshared.use_count(): "
<< copy_of_shared_ptr.use_count()
<< std::endl;
my_type copy_of_value = lua["shared"];
std::cout << "\tafter getting value copy of my_type: "
<< copy_of_shared_ptr.use_count()
<< std::endl;
sol_c_assert(copy_of_shared_ptr->value == 20);
sol_c_assert(copy_of_value.value == 20);
// script still affects pointer, but does not affect
// copy of `my_type`
lua.script("shared.value = 30");
sol_c_assert(copy_of_shared_ptr->value == 30);
sol_c_assert(copy_of_value.value == 20);
}
// set to nil and collect garbage to destroy it
lua.script("shared = nil");
lua.collect_garbage();
lua.collect_garbage();
std::cout << "garbage has been collected" << std::endl;
std::cout << std::endl;
return 0;
}
-61
View File
@@ -1,61 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <memory>
#include <iostream>
struct Shape {
virtual ~Shape() = default;
};
struct Box : Shape { };
SOL_BASE_CLASSES(Box, Shape);
SOL_DERIVED_CLASSES(Shape, Box);
int main() {
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<Shape>("Shape", sol::no_constructor);
lua.new_usertype<Box>("Box", sol::factories([&]() {
auto b = std::make_shared<Box>();
std::cout << "create Box@" << std::hex << b.get()
<< '\n';
return b;
}));
lua.set_function(
"inspect_shape_table", [](const sol::table& args) {
std::shared_ptr<Shape> defbox = nullptr;
// check if there's a field with the name "shape"
auto s = args.get<
sol::optional<std::shared_ptr<Shape>>>(
"shape");
std::cout << "has : " << std::boolalpha
<< s.has_value() << '\n';
// get the field named "shape" or use the default
// value
std::cout << "get_or: " << std::hex
<< args.get_or<std::shared_ptr<Shape>>(
"shape", defbox)
.get()
<< '\n';
// this works but I can't test for existence
// beforehand...
std::cout
<< "get : " << std::hex
<< args.get<std::shared_ptr<Shape>>("shape")
.get()
<< '\n';
});
sol::protected_function_result result = lua.safe_script(
"inspect_shape_table({shape=Box.new()})");
sol_c_assert(result.valid());
return 0;
}
@@ -1,58 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct ree {
int value = 1;
ree() {
}
ree(int v) : value(v) {
}
};
int main() {
std::cout << "=== special pointers -- modify in place ==="
<< std::endl;
sol::state lua;
auto new_shared_ptr = [](sol::stack_reference obj) {
// works just fine
sol::stack::modify_unique_usertype(
obj, [](std::shared_ptr<ree>& sptr) {
sptr = std::make_shared<ree>(
sptr->value + 1);
});
};
auto reset_shared_ptr = [](sol::stack_reference obj) {
sol::stack::modify_unique_usertype(
obj, [](std::shared_ptr<ree>& sptr) {
// THIS IS SUCH A BAD IDEA AAAGH
sptr.reset();
// DO NOT reset to nullptr:
// change it to an actual NEW value...
// otherwise you will inject a nullptr into
// the userdata representation... which will
// NOT compare == to Lua's nil
});
};
lua.set_function("f", new_shared_ptr);
lua.set_function("f2", reset_shared_ptr);
lua.set_function("g",
[](ree* r) { std::cout << r->value << std::endl; });
lua["p"] = std::make_shared<ree>();
lua.script("g(p) -- okay");
lua.script("f(p)");
lua.script("g(p) -- okay");
// uncomment the below for
// segfault/read-access violation
lua.script("f2(p)");
// lua.script("g(p) -- kaboom");
return 0;
}
-74
View File
@@ -1,74 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
#include <memory>
#include <mutex>
struct SomeLib {
private:
SomeLib() {
}
public:
static std::shared_ptr<SomeLib> getInstance();
int doSomething() const {
return 20;
}
// destructor must be public to work with
// std::shared_ptr and friends
// if you need it to be private, you must implement
// a custom deleter with access to the private members
// (e.g., a deleter struct defined in this class)
~SomeLib() {
}
};
std::shared_ptr<SomeLib> SomeLib::getInstance() {
static std::weak_ptr<SomeLib> instance;
static std::mutex m;
m.lock();
auto ret = instance.lock();
if (!ret) {
ret.reset(new SomeLib());
instance = ret;
}
m.unlock();
return ret;
}
int main(int, char*[]) {
std::cout << "=== singleton ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<SomeLib>("SomeLib",
"new",
sol::no_constructor,
"getInstance",
&SomeLib::getInstance,
"doSomething",
&SomeLib::doSomething);
lua.script(R"(
-- note we use the `.` here, not `:` (there's no self to access)
local sli = SomeLib.getInstance()
-- we use the `:` here because there is something to access
local value = sli:doSomething()
-- check
print('sli:doSomething() returned:', value)
assert(value == 20)
)");
std::cout << std::endl;
return 0;
}
-34
View File
@@ -1,34 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
sol::state lua;
lua.script("function func (a, b) return (a + b) * 2 end");
sol::reference func_ref = lua["func"];
// for some reason, you need to use the low-level API
func_ref.push(); // function on stack now
// maybe this is in a lua_CFunction you bind,
// or maybe you're trying to work with a pre-existing system
// maybe you've used a custom lua_load call, or you're
// working with state_view's load(lua_Reader, ...) call...
// here's a little bit of how you can work with the stack
lua_State* L = lua.lua_state();
sol::stack_aligned_unsafe_function func(L, -1);
lua_pushinteger(L, 5); // argument 1, using plain API
lua_pushinteger(L, 6); // argument 2
// take 2 arguments from the top,
// and use "stack_aligned_function" to call
int result = func(sol::stack_count(2));
// make sure everything is clean
sol_c_assert(result == 22);
sol_c_assert(
lua.stack_top() == 0); // stack is empty/balanced
return 0;
}
@@ -1,48 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
sol::state lua;
lua.script("function func (a, b) return (a + b) * 2 end");
sol::reference func_ref = lua["func"];
// maybe this is in a lua_CFunction you bind,
// or maybe you're trying to work with a pre-existing system
// maybe you've used a custom lua_load call, or you're
// working with state_view's load(lua_Reader, ...) call...
// here's a little bit of how you can work with the stack
lua_State* L = lua.lua_state();
// this is a handler:
// stack_aligned_stack_handler,
// as its type name explains so verbosely,
// expects the handler on the stack
sol::stack_reference traceback_handler(L,
-sol::stack::push(
L, sol::default_traceback_error_handler));
// then, you need the function
// to be on the stack
func_ref.push();
sol::stack_aligned_stack_handler_function func(
L, -1, traceback_handler);
lua_pushinteger(L, 5); // argument 1, using plain API
lua_pushinteger(L, 6); // argument 2
// take 2 arguments from the top,
// and use "stack_aligned_function" to call
int result = func(sol::stack_count(2));
// function call pops function and arguments,
// leaves result on the stack for us
// but we must manually clean the traceback handler
// manually pop traceback handler
traceback_handler.pop();
// make sure everything is clean
sol_c_assert(result == 22);
sol_c_assert(
lua.stack_top() == 0); // stack is empty/balanced
return 0;
}
-63
View File
@@ -1,63 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
struct test {
static int muh_variable;
};
int test::muh_variable = 25;
int main() {
std::cout << "=== static_variables ===" << std::endl;
sol::state lua;
lua.open_libraries();
lua.new_usertype<test>("test",
"direct",
sol::var(2),
"global",
sol::var(test::muh_variable),
"ref_global",
sol::var(std::ref(test::muh_variable)));
int direct_value = lua["test"]["direct"];
// direct_value == 2
sol_c_assert(direct_value == 2);
std::cout << "direct_value: " << direct_value << std::endl;
int global = lua["test"]["global"];
int global2 = lua["test"]["ref_global"];
// global == 25
// global2 == 25
sol_c_assert(global == 25);
sol_c_assert(global2 == 25);
std::cout << "First round of values --" << std::endl;
std::cout << global << std::endl;
std::cout << global2 << std::endl;
test::muh_variable = 542;
global = lua["test"]["global"];
// global == 25
// global is its own memory: was passed by value
global2 = lua["test"]["ref_global"];
// global2 == 542
// global2 was passed through std::ref
// global2 holds a reference to muh_variable
// if muh_variable goes out of scope or is deleted
// problems could arise, so be careful!
sol_c_assert(global == 25);
sol_c_assert(global2 == 542);
std::cout << "Second round of values --" << std::endl;
std::cout << "global : " << global << std::endl;
std::cout << "global2: " << global2 << std::endl;
std::cout << std::endl;
return 0;
}
-37
View File
@@ -1,37 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
struct Vector {
int x;
int y;
Vector() = default;
Vector(int _x, int _y) : x { _x }, y { _y } {
}
};
int main() {
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.new_usertype<Vector>("Vector",
sol::constructors<Vector(), Vector(int, int)>(),
"x",
sol::property(&Vector::x, &Vector::x),
"y",
sol::property(&Vector::y, &Vector::y));
lua.script(
"vectors = { Vector.new(3, 6), Vector.new(6, 3) }");
auto vectors = lua["vectors"].get<std::vector<Vector>>();
sol_c_assert(vectors[0].x == 3);
sol_c_assert(vectors[0].y == 6);
sol_c_assert(vectors[1].x == 6);
sol_c_assert(vectors[1].y == 3);
return 0;
}
-42
View File
@@ -1,42 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
void create_namespace_sf(sol::state& lua) {
// this would explode
// lua["sf"]["value"] = 256;
lua[sol::create_if_nil]["sf"]["value"] = 256;
}
int main(int, char*[]) {
std::cout << "=== sol::lua_value/sol::array_value ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
const auto& code = R"(
print(sf)
print(sf.value)
assert(sf.value == 256)
)";
auto result
= lua.safe_script(code, sol::script_pass_on_error);
// did not work
sol_c_assert(!result.valid());
// create values
create_namespace_sf(lua);
auto result2
= lua.safe_script(code, sol::script_pass_on_error);
// it worked properly
sol_c_assert(result2.valid());
std::cout << std::endl;
return 0;
}
-53
View File
@@ -1,53 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main() {
const auto& code = R"(
bark = {
woof = {
[2] = "arf!"
}
}
)";
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script(code);
// produces table_proxy, implicitly converts to std::string,
// quietly destroys table_proxy
std::string arf_string = lua["bark"]["woof"][2];
// lazy-evaluation of tables
auto x = lua["bark"];
auto y = x["woof"];
auto z = y[2];
// retrivies value inside of lua table above
std::string value = z;
sol_c_assert(value == "arf!");
// Can change the value later...
z = 20;
// Yay, lazy-evaluation!
int changed_value = z; // now it's 20!
sol_c_assert(changed_value == 20);
lua.script("assert(bark.woof[2] == 20)");
lua["a_new_value"] = 24;
lua["chase_tail"] = [](int chasing) {
int r = 2;
for (int i = 0; i < chasing; ++i) {
r *= r;
}
return r;
};
lua.script("assert(a_new_value == 24)");
lua.script("assert(chase_tail(2) == 16)");
return 0;
}
-74
View File
@@ -1,74 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <iostream>
// this example shows how to read data in from a lua table
int main() {
std::cout << "=== tables ===" << std::endl;
sol::state lua;
// table used as an array
lua.script(R"(table1 = {"hello", "table"})");
// table with a nested table and the key value syntax
lua.script(R"(
table2 = {
["nestedTable"] = {
["key1"] = "value1",
["key2"]= "value2",
},
["name"] = "table2",
}
)");
/* Shorter Syntax: */
// using the values stored in table1
/*std::cout << (std::string)lua["table1"][1] << " "
<< (std::string)lua["table1"][2] << '\n';
*/
// some retrieval of values from the nested table
// the cleaner way of doing things
// chain off the the get<>() / [] results
auto t2 = lua.get<sol::table>("table2");
auto nestedTable = t2.get<sol::table>("nestedTable");
// Alternatively:
// sol::table t2 = lua["table2"];
// sol::table nestedTable = t2["nestedTable"];
std::string x = lua["table2"]["nestedTable"]["key2"];
std::cout << "nested table: key1 : "
<< nestedTable.get<std::string>("key1")
<< ", key2: " << x << '\n';
std::cout << "name of t2: " << t2.get<std::string>("name")
<< '\n';
std::string t2name = t2["name"];
std::cout << "name of t2: " << t2name << '\n';
/* Longer Syntax: */
// using the values stored in table1
std::cout << lua.get<sol::table>("table1").get<std::string>(
1) << " "
<< lua.get<sol::table>("table1").get<std::string>(
2)
<< '\n';
// some retrieval of values from the nested table
// the cleaner way of doing things
std::cout << "nested table: key1 : "
<< nestedTable.get<std::string>("key1")
<< ", key2: "
// yes you can chain the get<>() results
<< lua.get<sol::table>("table2")
.get<sol::table>("nestedTable")
.get<std::string>("key2")
<< '\n';
std::cout << "name of t2: " << t2.get<std::string>("name")
<< '\n';
std::cout << std::endl;
return 0;
}
-31
View File
@@ -1,31 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main() {
sol::state lua;
lua.set_function(
"bark", [](sol::this_state s, int a, int b) {
lua_State* L = s; // current state
return a + b + lua_gettop(L);
});
lua.script(
"first = bark(2, 2)"); // only takes 2 arguments, NOT 3
// Can be at the end, too, or in the middle: doesn't matter
lua.set_function(
"bark", [](int a, int b, sol::this_state s) {
lua_State* L = s; // current state
return a + b + lua_gettop(L);
});
lua.script("second = bark(2, 2)"); // only takes 2 arguments
int first = lua["first"];
sol_c_assert(first == 6);
int second = lua["second"];
sol_c_assert(second == 6);
return 0;
}
-38
View File
@@ -1,38 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int, char*[]) {
const auto& code = R"(
bark_power = 11;
function woof ( bark_energy )
return (bark_energy * (bark_power / 4))
end
)";
sol::state lua;
lua.script(code);
sol::function woof = lua["woof"];
double numwoof = woof(20);
sol_c_assert(numwoof == 55.0);
lua.script("function f () return 10, 11, 12 end");
sol::function f = lua["f"];
std::tuple<int, int, int> abc = f();
sol_c_assert(std::get<0>(abc) == 10);
sol_c_assert(std::get<1>(abc) == 11);
sol_c_assert(std::get<2>(abc) == 12);
// or
int a, b, c;
sol::tie(a, b, c) = f();
sol_c_assert(a == 10);
sol_c_assert(b == 11);
sol_c_assert(c == 12);
return 0;
}
-32
View File
@@ -1,32 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
sol::state lua;
lua["bark"] = 50;
sol::optional<int> x = lua["bark"];
// x will have a value
if (x) {
std::cout << "x has no value, as expected"
<< std::endl;
}
else {
return -1;
}
lua["bark"] = sol::lua_nil;
sol::optional<int> y = lua["bark"];
// y will not have a value
if (y) {
return -1;
}
else {
std::cout << "y has no value, as expected"
<< std::endl;
}
return 0;
}
-15
View File
@@ -1,15 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp> // or #include "sol.hpp", whichever suits your needs
int main(int argc, char* argv[]) {
// silence unused warnings
(void)argc;
(void)argv;
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script("print('bark bark bark!')");
return 0;
}
-24
View File
@@ -1,24 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main() {
sol::state lua;
auto barkkey = lua["bark"];
if (barkkey.valid()) {
// Branch not taken: doesn't exist yet
std::cout << "How did you get in here, arf?!"
<< std::endl;
}
barkkey = 50;
if (barkkey.valid()) {
// Branch taken: value exists!
std::cout << "Bark Bjork Wan Wan Wan" << std::endl;
}
return 0;
}
@@ -1,22 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main() {
sol::state lua;
lua.script("function f (a, b, c) return a, b, c end");
std::tuple<int, int, int> result;
result = lua["f"](1, 2, 3);
sol_c_assert(result == std::make_tuple(1, 2, 3));
int a, b;
std::string c;
// NOTE: sol::tie, NOT std::tie
// (ESS OH ELL prefix, not ESS TEE DEE prefix)
sol::tie(a, b, c) = lua["f"](1, 2, "bark");
sol_c_assert(a == 1);
sol_c_assert(b == 2);
sol_c_assert(c == "bark");
return 0;
}
@@ -1,37 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <string>
#include <iostream>
int main() {
sol::state lua;
lua.open_libraries(sol::lib::base);
lua.script(R"(
obj = "please don't let me die";
)");
sol::object keep_alive = lua["obj"];
lua.script(R"(
obj = nil;
function say(msg)
print(msg)
end
)");
lua.collect_garbage();
lua["say"](lua["obj"]);
// still accessible here and still alive in Lua
// even though the name was cleared
std::string message = keep_alive.as<std::string>();
std::cout << message << std::endl;
// Can be pushed back into Lua as an argument
// or set to a new name,
// whatever you like!
lua["say"](keep_alive);
return 0;
}
@@ -1,17 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
int main(int argc, char* argv[]) {
// silence unused warnings
(void)argc;
(void)argv;
sol::state lua;
lua.open_libraries(sol::lib::base,
sol::lib::coroutine,
sol::lib::string,
sol::lib::io);
lua.script("print('bark bark bark!')");
return 0;
}
@@ -1,82 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
struct my_type {
void stuff() {
}
};
int main() {
sol::state lua;
/*
// AAAHHH BAD
// dangling pointer!
lua["my_func"] = []() -> my_type* { return new my_type(); };
// AAAHHH!
lua.set("something", new my_type());
// AAAAAAHHH!!!
lua["something_else"] = new my_type();
*/
// :ok:
lua["my_func0"] = []() -> std::unique_ptr<my_type> {
return std::make_unique<my_type>();
};
// :ok:
lua["my_func1"] = []() -> std::shared_ptr<my_type> {
return std::make_shared<my_type>();
};
// :ok:
lua["my_func2"] = []() -> my_type { return my_type(); };
// :ok:
lua.set(
"something", std::unique_ptr<my_type>(new my_type()));
std::shared_ptr<my_type> my_shared
= std::make_shared<my_type>();
// :ok:
lua.set("something_else", my_shared);
// :ok:
auto my_unique = std::make_unique<my_type>();
lua["other_thing"] = std::move(my_unique);
// :ok:
lua["my_func5"] = []() -> my_type* {
static my_type mt;
return &mt;
};
// THIS IS STILL BAD DON'T DO IT AAAHHH BAD
// return a unique_ptr that's empty instead
// or be explicit!
lua["my_func6"] = []() -> my_type* { return nullptr; };
// :ok:
lua["my_func7"]
= []() -> std::nullptr_t { return nullptr; };
// :ok:
lua["my_func8"] = []() -> std::unique_ptr<my_type> {
// default-constructs as a nullptr,
// gets pushed as nil to Lua
return std::unique_ptr<my_type>();
// same happens for std::shared_ptr
};
// Acceptable, it will set 'something' to nil
// (and delete it on next GC if there's no more references)
lua.set("something", nullptr);
// Also fine
lua["something_else"] = nullptr;
return 0;
}
@@ -1,30 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
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;
}
@@ -1,82 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.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 {});
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;
}
@@ -1,32 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.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");
sol_c_assert(is_one == 1);
int is_also_one = fx(1, "boop", 3, "bark");
sol_c_assert(is_also_one == 1);
// call through operator[]
int is_three = lua["g"](1, 2);
sol_c_assert(is_three == 3);
double is_4_8 = lua["g"](2.4, 2.4);
sol_c_assert(is_4_8 == 4.8);
return 0;
}
@@ -1,35 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.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);
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;
}
@@ -1,22 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.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");
sol_c_assert(a == 100);
sol_c_assert(b == 200);
sol_c_assert(c == "bark");
return 0;
}
@@ -1,40 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.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);
sol_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!");
sol_c_assert(result2 == expected2);
int a, b;
std::string c;
sol::tie(a, b, c) = lua["f"](100, 200, "bark");
sol_c_assert(a == 100);
sol_c_assert(b == 200);
sol_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;
}
@@ -1,59 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
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"];
sol_c_assert(obj.b == 25);
std::cout << std::endl;
return 0;
}
@@ -1,17 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
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;
}

Some files were not shown because too many files have changed in this diff Show More