mirror of
https://github.com/ThePhD/sol2.git
synced 2024-03-22 13:10:44 +08:00
Add basic examples directory
This commit is contained in:
parent
ac975872ad
commit
afe435910f
35
README.md
35
README.md
|
@ -15,40 +15,9 @@ It should be noted that the library itself depends on `lua.hpp` to be found by y
|
||||||
|
|
||||||
If you want to contribute, please check CONTRIBUTING.md for details. Thank you!
|
If you want to contribute, please check CONTRIBUTING.md for details. Thank you!
|
||||||
|
|
||||||
## Example
|
## Examples
|
||||||
|
|
||||||
Here's an example on how to load a basic configuration struct with a Lua script.
|
Examples are provided in the examples directory.
|
||||||
|
|
||||||
```cpp
|
|
||||||
#include <sol.hpp>
|
|
||||||
#include <iostream>
|
|
||||||
#include <string>
|
|
||||||
|
|
||||||
struct test {
|
|
||||||
int foo;
|
|
||||||
std::string bar;
|
|
||||||
double baz;
|
|
||||||
};
|
|
||||||
|
|
||||||
test load(const sol::table& t) {
|
|
||||||
return { t.get<int>("foo"), t.get<std::string>("bar"), t.get<double>("baz") };
|
|
||||||
}
|
|
||||||
|
|
||||||
int main() {
|
|
||||||
try {
|
|
||||||
sol::state lua;
|
|
||||||
lua.script("foo = 1234;\n"
|
|
||||||
"bar = \"hello world\";\n"
|
|
||||||
"baz = 1.4;");
|
|
||||||
|
|
||||||
test c = load(lua.global_table());
|
|
||||||
std::cout << '(' << c.foo << ", " << c.bar << ", " << c.baz << ")\n";
|
|
||||||
}
|
|
||||||
catch(const std::exception& e) {
|
|
||||||
std::cerr << e.what() << '\n';
|
|
||||||
}
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
|
27
examples/config.cpp
Normal file
27
examples/config.cpp
Normal file
|
@ -0,0 +1,27 @@
|
||||||
|
// shows how to load basic data to a struct
|
||||||
|
|
||||||
|
#include <sol.hpp>
|
||||||
|
#include <string>
|
||||||
|
#include <iostream>
|
||||||
|
|
||||||
|
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;
|
||||||
|
lua.open_file("config.lua");
|
||||||
|
screen.name = lua.get<std::string>("name");
|
||||||
|
screen.width = lua.get<int>("width");
|
||||||
|
screen.height = lua.get<int>("height");
|
||||||
|
screen.print();
|
||||||
|
}
|
3
examples/config.lua
Normal file
3
examples/config.lua
Normal file
|
@ -0,0 +1,3 @@
|
||||||
|
name = "Asus"
|
||||||
|
width = 1920
|
||||||
|
height = 1080
|
Loading…
Reference in New Issue
Block a user