Skip to content

Commit

Permalink
heavily improve examples and docs
Browse files Browse the repository at this point in the history
  • Loading branch information
ThePhD committed Jul 4, 2019
1 parent 6033256 commit fd6feec
Show file tree
Hide file tree
Showing 16 changed files with 214 additions and 268 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
## sol3 (sol2 v3.0.2)
## sol3 (sol2 v3.0.3)

[![Join the chat in Discord: https://discord.gg/buxkYNT](https://img.shields.io/badge/Discord-Chat!-brightgreen.svg)](https://discord.gg/buxkYNT)

Expand Down
2 changes: 1 addition & 1 deletion docs/source/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@
# The short X.Y version.
version = '3.0'
# The full version, including alpha/beta/rc tags.
release = '3.0.2'
release = '3.0.3'

# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
Expand Down
137 changes: 20 additions & 117 deletions docs/source/tutorial/cxx-in-lua.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,131 +5,34 @@ Using user defined types ("usertype"s, or just "udt"s) is simple with sol. If yo

Take this ``player`` struct in C++ in a header file:

.. code-block:: cpp
:caption: test_player.hpp
struct player {
public:
int bullets;
int speed;
player()
: player(3, 100) {
}
player(int ammo)
: player(ammo, 100) {
}
player(int ammo, int hitpoints)
: bullets(ammo), hp(hitpoints) {
}
void boost () {
speed += 10;
}
bool shoot () {
if (bullets < 1)
return false;
--bullets;
return true;
}
void set_hp(int value) {
hp = value;
}
int get_hp() const {
return hp;
}
private:
int hp;
};
.. literalinclude:: ../../../examples/source/usertype_advanced.cpp
:caption: player.hpp
:linenos:
:lines: 1-48

It's a fairly minimal class, but we don't want to have to rewrite this with metatables in Lua. We want this to be part of Lua easily. The following is the Lua code that we'd like to have work properly:

.. code-block:: lua
.. literalinclude:: ../../../examples/source/usertype_advanced.cpp
:caption: player_script.lua
-- call single argument integer constructor
p1 = player.new(2)
-- p2 is still here from being
-- set with lua["p2"] = player(0);
-- in cpp file
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()
To do this, you bind things using the ``new_usertype`` and ``set_usertype`` methods as shown below. These methods are on both :doc:`table<../api/table>` and :doc:`state(_view)<../api/state>`, but we're going to just use it on ``state``:

.. code-block:: cpp
:caption: player_script.cpp
#include <sol/sol.hpp>
int main () {
sol::state lua;
:language: lua
:linenos:
:lines: 93-124

lua.open_libraries(sol::lib::base);
To do this, you bind things using the ``new_usertype`` and method as shown below. These methods are on both :doc:`table<../api/table>` and :doc:`state(_view)<../api/state>`, but we're going to just use it on ``state``:

// note that you can set a
// userdata before you register a usertype,
// and it will still carry
// the right metatable if you register it later
// set a variable "p2" of type "player" with 0 ammo
lua["p2"] = player(0);
.. literalinclude:: ../../../examples/source/usertype_advanced.cpp
:caption: main.cpp
:language: cpp
:linenos:
:lines: 1-3,5,7-9,53,55-86,136-137,142

// make usertype metatable
lua.new_usertype<player>( "player",
// 3 constructors
sol::constructors<player(), player(int), player(int, int)>(),
// typical member function that returns a variable
"shoot", &player::shoot,
// typical member function
"boost", &player::boost,
// gets or set the value using member variable syntax
"hp", sol::property(&player::get_hp, &player::set_hp),
// read and write variable
"speed", &player::speed,
// can only read from, not write to
"bullets", sol::readonly( &player::bullets )
);
There is one more method used in the script that is not in C++ or defined on the C++ code to bind a usertype, called ``brake``. Even if a method does not exist in C++, you can add methods to the *class table* in Lua:

lua.script_file("player_script.lua");
}
.. literalinclude:: ../../../examples/source/usertype_advanced.cpp
:caption: prelude_script.lua
:language: lua
:linenos:
:lines: 90-93

That script should run fine now, and you can observe and play around with the values. Even more stuff :doc:`you can do<../api/usertype>` is described elsewhere, like initializer functions (private constructors / destructors support), "static" functions callable with ``name.my_function( ... )``, and overloaded member functions. You can even bind global variables (even by reference with ``std::ref``) with ``sol::var``. There's a lot to try out!

Expand Down
40 changes: 7 additions & 33 deletions docs/source/tutorial/getting-started.rst
Original file line number Diff line number Diff line change
Expand Up @@ -3,61 +3,35 @@ getting started

Let's get you going with sol! To start, you'll need to use a lua distribution of some sort. sol doesn't provide that: it only wraps the API that comes with it, so you can pick whatever distribution you like for your application. There are lots, but the two popular ones are `vanilla Lua`_ and speedy `LuaJIT`_ . We recommend vanilla Lua if you're getting started, LuaJIT if you need speed and can handle some caveats: the interface for sol doesn't change no matter what Lua version you're using.

If you need help getting or building Lua, check out the `Lua page on getting started`_. Note that for Visual Studio, one can simply download the sources, include all the Lua library files in that project, and then build for debug/release, x86/x64/ARM rather easily and with minimal interference. Just make sure to adjust the Project Property page to build as a static library (or a DLL with the proper define set in the ``Preprocessor`` step).
If you need help getting or building Lua, check out the `Lua page on getting started`_. Note that for Visual Studio, one can simply download the sources, include all the Lua library files in that project, and then build for debug/release, x86/x64/ARM rather easily and with minimal interference. Just make sure to adjust the Project Property page to build as a static library (or a DLL with the proper define set in the ``Preprocessor`` page, eg. `LUA_BUILD_AS_DLL=1`).

After that, make sure you grab either the `single header file release`_, or just perform a clone of the `github repository here`_ and set your include paths up so that you can get at ``sol.hpp`` somehow. Note that we also have the latest version of the single header file with all dependencies included kept in the `repository as well`_. We recommend the single-header-file release, since it's easier to move around, manage and update if you commit it with some form of version control. You can also clone/submodule the repository and then point at the `single/sol/sol.hpp`_ on your include files path. Clone with:

>>> git clone https://github.com/ThePhD/sol2.git

When you're ready, try compiling this short snippet:

.. code-block:: cpp
.. literalinclude:: ../../../examples/source/tutorials/first_snippet.cpp
:linenos:
:caption: test.cpp: the first snippet
:name: the-first-snippet
#include <sol/sol.hpp> // or #include "sol.hpp", whichever suits your needs
int main (int argc, char* argv[]) {
sol::state lua;
lua.open_libraries( sol::lib::base );
lua.script( "print('bark bark bark!')" );
return 0;
}
:caption: hello_lua.cpp

Using this simple command line:

>>> g++ -std=c++14 test.cpp -I"path/to/lua/include" -L"path/to/lua/lib" -llua
>>> g++ -std=c++17 test.cpp -I"path/to/sol/include" -I"path/to/lua/include" -L"path/to/lua/lib" -llua

Or using your favorite IDE / tool after setting up your include paths and library paths to Lua according to the documentation of the Lua distribution you got. Remember your linked lua library (``-llua``) and include / library paths will depend on your OS, file system, Lua distribution and your installation / compilation method of your Lua distribution.

.. note::

If you get an avalanche of errors (particularly referring to ``auto``), you may not have enabled C++14 / C++17 mode for your compiler. Add one of ``std=c++14``, ``std=c++1z`` OR ``std=c++1y`` to your compiler options. By default, this is always-on for VC++ compilers in Visual Studio and friends, but g++ and clang++ require a flag (unless you're on `GCC 6.0`_ or better).
If you get an avalanche of errors (particularly referring to ``auto``), you may not have enabled C++14 / C++17 mode for your compiler. Add one of ``std=c++17``, ``std=c++1z`` OR ``std=c++1y`` to your compiler options. By default, this is always-on for VC++ compilers in Visual Studio and friends, but g++ and clang++ require a flag (unless you're on `GCC 6.0`_ or better).

If this works, you're ready to start! The first line creates the ``lua_State`` and will hold onto it for the duration of the scope its declared in (e.g., from the opening ``{`` to the closing ``}``). It will automatically close / cleanup that lua state when it gets destructed.

The second line opens a single lua-provided library, "base". There are several other libraries that come with lua that you can open by default, and those are included in the :ref:`sol::lib<lib-enum>` enumeration. You can open multiple base libraries by specifying multiple ``sol::lib`` arguments:

.. code-block:: cpp
.. literalinclude:: ../../../examples/source/tutorials/open_multiple_libraries.cpp
:linenos:
:caption: test.cpp: the first snippet
:name: the-second-snippet
#include <sol/sol.hpp>
int main (int argc, char* 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;
}
:caption: multiple_libraries.cpp

If you're interested in integrating sol with a project that already uses some other library or Lua in the codebase, check out the :doc:`existing example<existing>` to see how to work with sol when you add it to a project (the existing example covers ``require`` as well)!

Expand Down
135 changes: 33 additions & 102 deletions docs/source/tutorial/ownership.rst
Original file line number Diff line number Diff line change
@@ -1,127 +1,58 @@
ownership
=========

You can take a reference to something that exists in Lua by pulling out a :doc:`sol::reference<../api/reference>` or a :doc:`sol::object<../api/object>`:
Ownership is important when managing resources in C++. sol has many ownership semantics which are generally safe by default. Below are the rules.

.. code-block:: cpp
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);
object ownership
----------------

You can take a reference to something that exists in Lua by pulling out a :doc:`sol::reference<../api/reference>` or a :doc:`sol::object<../api/object>`:

sol will not take ownership of raw pointers: raw pointers do not own anything. sol will not delete raw pointers, because they do not (and are not supposed to) own anything:
.. literalinclude:: ../../../examples/source/tutorials/object_lifetime.cpp
:linenos:
:caption: object_lifetime.cpp

.. code-block:: cpp
All objects must be destroyed before the `sol::state` is destroyed, otherwise you will end up with dangling references to the Lua State and things will explode in horrible, terrible fashion.

struct my_type {
void stuff () {}
};
This applies to more than just `sol::object`: all types derived from `sol::reference` and `sol::object` (:doc:`sol::table<../api/table>` :doc:`sol::userdata<../api/userdata>`, etc.) must be cleaned up before the state goes out of scope.

sol::state lua;

// AAAHHH BAD
// dangling pointer!
lua["my_func"] = []() -> my_type* {
return new my_type();
};
pointer ownership
-----------------

// AAAHHH!
lua.set("something", new my_type());
sol will not take ownership of raw pointers: raw pointers do not own anything. sol will not delete raw pointers, because they do not (and are not supposed to) own anything:

// AAAAAAHHH!!!
lua["something_else"] = new my_type();
.. literalinclude:: ../../../examples/source/tutorials/pointer_lifetime.cpp
:linenos:
:caption: pointer_lifetime.cpp
:lines: 1-11,14-22, 74-

Use/return a ``unique_ptr`` or ``shared_ptr`` instead or just return a value:

.. code-block:: cpp
// :ok:
lua["my_func"] = []() -> std::unique_ptr<my_type> {
return std::make_unique<my_type>();
};
// :ok:
lua["my_func"] = []() -> std::shared_ptr<my_type> {
return std::make_shared<my_type>();
};
// :ok:
lua["my_func"] = []() -> 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);
auto my_unique = std::make_unique<my_type>();
lua["other_thing"] = std::move(my_unique);
.. literalinclude:: ../../../examples/source/tutorials/pointer_lifetime.cpp
:linenos:
:caption: (smart pointers) pointer_lifetime.cpp
:lines: 1-11,14-22, 74-

If you have something you know is going to last and you just want to give it to Lua as a reference, then it's fine too:

.. code-block:: cpp
// :ok:
lua["my_func"] = []() -> my_type* {
static my_type mt;
return &mt;
};
sol can detect ``nullptr``, so if you happen to return it there won't be any dangling because a ``sol::nil`` will be pushed.
.. literalinclude:: ../../../examples/source/tutorials/pointer_lifetime.cpp
:linenos:
:caption: (static) pointer_lifetime.cpp
:lines: 1-11,46-49,74-

.. code-block:: cpp

struct my_type {
void stuff () {}
};
sol can detect ``nullptr``, so if you happen to return it there won't be any dangling because a ``sol::lua_nil`` will be pushed. But if you know it's ``nil`` beforehand, please return ``std::nullptr_t`` or ``sol::lua_nil``:

sol::state lua;
.. literalinclude:: ../../../examples/source/tutorials/pointer_lifetime.cpp
:linenos:
:caption: (nil/nullptr) pointer_lifetime.cpp
:lines: 1-11,51-

// BUT THIS IS STILL BAD DON'T DO IT AAAHHH BAD
// return a unique_ptr still or something!
lua["my_func"] = []() -> my_type* {
return nullptr;
};

lua["my_func_2"] = [] () -> 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
}
ephermeal (proxy) objects
-------------------------

// Acceptable, it will set 'something' to nil
// (and delete it on next GC if there's no more references)
lua.set("something", nullptr);
:doc:`Proxy<../api/proxy>` and result types are ephermeal. They rely on the Lua stack and their constructors / destructors interact with the Lua stack. This means they are entirely unsafe to return from functions in C++, without very careful attention paid to how they are used that often requires relying on implementation-defined behaviors.

// Also fine
lua["something_else"] = nullptr;
Please be careful when using `(protected_)function_result`, `load_result` (especially multiple load/function results in a single C++ function!) `stack_reference`, and similar stack-based things. If you want to return these things, consider
Loading

0 comments on commit fd6feec

Please sign in to comment.