From edb8eacac7f93000853a27a8f728a4b13b9e95ab Mon Sep 17 00:00:00 2001 From: ThePhD Date: Fri, 9 Sep 2016 07:48:28 -0400 Subject: [PATCH] Add additional namespacing example and tutorial --- docs/source/tutorial/all-the-things.rst | 41 +++++++++++++++++++++++++ examples/namespacing.cpp | 33 ++++++++++++++++++++ 2 files changed, 74 insertions(+) create mode 100644 examples/namespacing.cpp diff --git a/docs/source/tutorial/all-the-things.rst b/docs/source/tutorial/all-the-things.rst index 6e7b9314..ad248a04 100644 --- a/docs/source/tutorial/all-the-things.rst +++ b/docs/source/tutorial/all-the-things.rst @@ -238,6 +238,8 @@ Equivalent Lua code: You can put anything you want in tables as values or keys, including strings, numbers, functions, other tables. +Note that this idea that things can be nested is important and will help later when you get into :ref:`namespacing`. + functions --------- @@ -501,6 +503,45 @@ C++ classes put into Lua See this :doc:`section here`. +namespacing +----------- + +You can emulate namespacing by having a table and giving it the namespace names you want before registering enums or usertypes: + +.. code-block:: cpp + + struct my_class { + int b = 24; + + int f () const { + return 24; + } + + void g () { + ++b; + } + }; + + sol::state lua; + lua.open_libraries(); + + // set up table + sol::table bark = lua.create_named_table("bark"); + + bark.new_usertype( "my_class", + "f", &my_class::f, + "g", &my_class::g + ); // the usual + + // 'bark' namespace + lua.script("obj = bark.my_class.new()" ); + lua.script("obj:g()"); + my_class& obj = lua["obj"]; + // obj.b == 25 + + +This technique can be used to register namespace-like functions and classes. It can be as deep as you want. Just make a table and name it appropriately, in either Lua script or using the equivalent Sol code. As long as the table FIRST exists (e.g., make it using a script or with one of Sol's methods or whatever you like), you can put anything you want specifically into that table using :doc:`sol::table's<../api/table>` abstractions. + advanced -------- diff --git a/examples/namespacing.cpp b/examples/namespacing.cpp new file mode 100644 index 00000000..8d32744e --- /dev/null +++ b/examples/namespacing.cpp @@ -0,0 +1,33 @@ +#define SOL_CHECK_ARGUMENTS +#include +#include + +int main() { + struct my_class { + int b = 24; + + int f() const { + return 24; + } + + void g() { + ++b; + } + }; + + sol::state lua; + lua.open_libraries(); + + sol::table bark = lua.create_named_table("bark"); + bark.new_usertype("my_class", + "f", &my_class::f, + "g", &my_class::g + ); // the usual + + lua.script("obj = bark.my_class.new()"); // this works + lua.script("obj:g()"); + my_class& obj = lua["obj"]; + assert(obj.b == 25); + + return 0; +}