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
-110
View File
@@ -1,110 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
BasedOnStyle: WebKit
IndentWidth: 5
TabWidth: 5
ContinuationIndentWidth: 5
UseTab: ForIndentation
# Namespaces
NamespaceIndentation: All
CompactNamespaces: true
FixNamespaceComments: true
# Overall Alignment
ColumnLimit: 160
AlignAfterOpenBracket: DontAlign # uses ContinuationIndentWidth for this instead
AccessModifierOffset: -5 # do not push public: or private: around
#AlignConsecutiveAssignments: true # affects more than what's expected: do not use
#AlignConsecutiveDeclarations: true # affects more than what's expected: do not use
# Type Alignment
DerivePointerAlignment: false
PointerAlignment: Left
AlwaysBreakTemplateDeclarations: true
AlwaysBreakBeforeMultilineStrings: true
# Comments
AlignTrailingComments: true
ReflowComments: true
# Macros
AlignEscapedNewlines: Left
#IndentPPDirectives: None
# Functions
AllowShortFunctionsOnASingleLine: None
AlwaysBreakAfterReturnType: None
BreakConstructorInitializers: BeforeComma
ConstructorInitializerIndentWidth: 0
ConstructorInitializerAllOnOneLineOrOnePerLine: true
BinPackArguments: false
BinPackParameters: true
# Classes
BreakBeforeInheritanceComma: false
# Braces
Cpp11BracedListStyle: false
BreakBeforeBraces: Custom
BraceWrapping:
AfterEnum: false
AfterStruct: false
AfterControlStatement: false
AfterClass: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
BeforeElse: true
BeforeCatch: true
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: true
# Control Statements
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
IndentCaseLabels: false
# Spaces
SpaceAfterCStyleCast: false
SpacesInCStyleCastParentheses: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
MaxEmptyLinesToKeep: 3
# OCD
SortUsingDeclarations: true
SortIncludes: false
---
Language: Cpp
Standard: Cpp11
-27
View File
@@ -1,27 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Ignore literally everything
**
# Except the script directory
!scripts/preparation*
-16
View File
@@ -1,16 +0,0 @@
Read these guidelines. They are relatively simple and will allow me to help you better!
For Error Reports:
1. Produce a simple, short, compilable test case that reproduces your problem.
2. Make a descriptive title that summarises the bug as a whole.
3. Explain the bug in as much detail as you can in the body of the issue.
4. Include Compiler/IDE (Visual Studio, XCode...), Build and Deployment System, Language (C++, Objective-C++), and any special defines you have set.
If you want to request a feature:
1. Produce any relevant imaginary code that illustrates what you would like or desired behavior.
2. Include a description and title of what you would like.
3. Annotate and describe the behavior through comments, asserts or just a small write up.
Thanks for helping sol2 grow!
-33
View File
@@ -1,33 +0,0 @@
name: Mac OS
on: [push]
env:
CTEST_OUTPUT_ON_FAILURE: 1
jobs:
build:
runs-on: macos-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: configure
run: |
cmake -B build/debug -D CMAKE_BUILD_TYPE:STRING=Debug "-DSOL2_LUA_VERSION:STRING=5.4" -DSOL2_PLATFORM:STRING=x64 -DSOL2_CI=ON -DSOL2_BUILD_LUA:BOOL=ON -DBUILD_LUA_AS_DLL:BOOL=OFF -DSOL2_TESTS:BOOL=ON -DSOL2_EXAMPLES:BOOL=ON -DSOL2_TESTS_EXAMPLES:BOOL=ON
cmake -B build/release -D CMAKE_BUILD_TYPE:STRING=Release "-DSOL2_LUA_VERSION:STRING=5.4" -DSOL2_PLATFORM:STRING=x64 -DSOL2_CI=ON -DSOL2_BUILD_LUA:BOOL=ON -DBUILD_LUA_AS_DLL:BOOL=OFF -DSOL2_TESTS:BOOL=ON -DSOL2_EXAMPLES:BOOL=ON -DSOL2_TESTS_EXAMPLES:BOOL=ON
- name: build
run: |
cmake --build build/debug --config Debug
cmake --build build/release --config Release
- name: test
run: |
cd build/debug
ctest --build-config Debug
cd ../..
cd build/release
ctest --build-config Release
cd ../..
-33
View File
@@ -1,33 +0,0 @@
name: Ubuntu
on: [push]
env:
CTEST_OUTPUT_ON_FAILURE: 1
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: configure
run: |
cmake -B build/debug -D CMAKE_BUILD_TYPE:STRING=Debug "-DSOL2_LUA_VERSION:STRING=5.4" -DSOL2_PLATFORM:STRING=x64 -DSOL2_CI=ON -DSOL2_BUILD_LUA:BOOL=ON -DBUILD_LUA_AS_DLL:BOOL=OFF -DSOL2_TESTS:BOOL=ON -DSOL2_EXAMPLES:BOOL=ON -DSOL2_TESTS_EXAMPLES:BOOL=ON
cmake -B build/release -D CMAKE_BUILD_TYPE:STRING=Release "-DSOL2_LUA_VERSION:STRING=5.4" -DSOL2_PLATFORM:STRING=x64 -DSOL2_CI=ON -DSOL2_BUILD_LUA:BOOL=ON -DBUILD_LUA_AS_DLL:BOOL=OFF -DSOL2_TESTS:BOOL=ON -DSOL2_EXAMPLES:BOOL=ON -DSOL2_TESTS_EXAMPLES:BOOL=ON
- name: build
run: |
cmake --build build/debug --config Debug
cmake --build build/release --config Release
- name: test
run: |
cd build/debug
ctest --build-config Debug
cd ../..
cd build/release
ctest --build-config Release
cd ../..
-38
View File
@@ -1,38 +0,0 @@
name: Windows
on: [push]
env:
CTEST_OUTPUT_ON_FAILURE: true
UseMultiToolTask: true
EnforceProcessCountAcrossBuilds: true
jobs:
build:
runs-on: windows-latest
steps:
- uses: actions/checkout@v2
with:
submodules: recursive
- name: configure
run: |
$env:MultiProcMaxCount = ((Get-CimInstance -ClassName Win32_Processor | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum + 1)
cmake -B build/debug -D CMAKE_BUILD_TYPE:STRING=Debug "-DSOL2_LUA_VERSION:STRING=5.4" -DSOL2_PLATFORM:STRING=x64 -DSOL2_CI=ON -DSOL2_BUILD_LUA:BOOL=ON -DBUILD_LUA_AS_DLL:BOOL=ON -DSOL2_TESTS:BOOL=ON -DSOL2_EXAMPLES:BOOL=ON -DSOL2_TESTS_EXAMPLES:BOOL=ON
cmake -B build/release -D CMAKE_BUILD_TYPE:STRING=Release "-DSOL2_LUA_VERSION:STRING=5.4" -DSOL2_PLATFORM:STRING=x64 -DSOL2_CI=ON -DSOL2_BUILD_LUA:BOOL=ON -DBUILD_LUA_AS_DLL:BOOL=ON -DSOL2_TESTS:BOOL=ON -DSOL2_EXAMPLES:BOOL=ON -DSOL2_TESTS_EXAMPLES:BOOL=ON
- name: build
run: |
$env:MultiProcMaxCount = ((Get-CimInstance -ClassName Win32_Processor | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum + 1)
cmake --build build/debug --config Debug
cmake --build build/release --config Release
- name: test
run: |
cd build/debug
ctest --build-config Debug
cd ../..
cd build/release
ctest --build-config Release
cd ../..
-131
View File
@@ -1,131 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Python (Bytecode)
*.pyc
# ninja files
*.ninja
# Visual Studio
*.props
*.user
.vs/
Debug/
Release/
x64/
x86/
*.pyproj
*.vcxproj
*.vcxproj.filters
*.tlog
*.lastbuildstate
*.idb
*.sln
*.gitattributes
# VSCode
.vscode/
# scratch space
/main.cpp
scratch/
# CMake
build/
build-sol2/
CMakeCache.txt
CMakeFiles/
# Compiler outputs
obj/*
bin/*
main.exe
main.o
lua53.dll
lua-5.3.4.dll
main.ilk
main.pdb
# Dropbox interference
.dropbox*
# QtCreator
*.creator.user.*
*.config
*.creator
*.files
*.includes
# Local Lua Testbeds
lua-5.4.0-cxx/
lua-5.4.0/
lua-5.4.0-work1-cxx/
lua-5.4.0-work1/
lua-5.3.4-cxx/
lua-5.3.4/
lua-5.3.2/
lua-5.3.1/
lua-5.3.0/
lua-5.2.4/
lua-5.2.2/
lua-5.2.3/
lua-5.1.5/
LuaJIT-2.1.0/
luajit-2.0.5/
luajit-2.0.3/
liblua.a
lib/liblua5.2.a
# Docs Artefacts
docs/build/
# Sublime Text
*.sublime-workspace
*.sublime-project
# MacOS Garbage
.DS_Store
# Windows Crap
desktop.ini
*.db
# Miscellaneous
external/
vendor/
.idea/
cmake-build-debug/
cmake-build-relwithdebinfo/
cmake-build-release/
/subprojects/*
!/subprojects/*.wrap
lua-5.3/
lua-5.3-cxx/
lua-5.4/
LuaJIT-2.0/
LuaJIT-2.1/
lua-5.1/
lua-5.2/
~syncthing*
.tmp
-15
View File
@@ -1,15 +0,0 @@
[style]
based_on_style = pep8
use_tabs = true
indent_width = 5
spaces_before_comment = 1
spaces_around_power_operator = true
space_between_ending_comma_and_closing_bracket = true
continuation_align_style = SPACE
split_before_first_argument = false
split_complex_comprehension = true
dedent_closing_brackets = false
coalesce_brackets = true
align_closing_bracket_with_visual_indent = false
-311
View File
@@ -1,311 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # # sol2
# # # Required minimum version statement
cmake_minimum_required(VERSION 3.16.0)
# # # Project Include - file that is included after project declaration is finished
set(CMAKE_PROJECT_INCLUDE "${CMAKE_CURRENT_SOURCE_DIR}/cmake/Includes/Project.cmake")
# # # project declaration
project(sol2 VERSION 4.0.0 LANGUAGES CXX C)
if (sol2-is-top-level-project)
message(STATUS "sol2 is the top-level directory...")
endif()
# Include standard modules
include(CMakePackageConfigHelpers)
include(CheckCXXCompilerFlag)
include(CMakeDependentOption)
include(GNUInstallDirs)
include(FetchContent)
# # # Configuration
# # Cached defines, strings, paths and options
set(SOL2_LUA_VERSION "5.4.4" CACHE STRING "The version of Lua needed. Can be 5.1, 5.2, 5.3, 5.4, LuaJIT, or a more specific 3-part version number for a specifc Lua (e.g., 5.4.4 or luajit-2.0.5)")
set(SOL2_BUILD_LUA TRUE CACHE BOOL "Always build Lua, do not search for it in the system")
set(SOL2_PLATFORM "x64" CACHE STRING "Target platform to compile for when building binaries (x86, x64)")
option(SOL2_CI "Whether or not we are in continguous integration mode" OFF)
option(SOL2_SYSTEM_INCLUDE "Whether or not sol2 should be considered a system include. This helps suppress errors for when the sol2 author is a big derp and doesn't fix every single warning, ever." ON)
option(SOL2_TESTS "Enable build of tests" OFF)
option(SOL2_EXAMPLES "Enable build of examples" OFF)
option(SOL2_INTEROP_EXAMPLES "Enable build of interop examples" OFF)
option(SOL2_DYNAMIC_LOADING_EXAMPLES "Enable build of interop examples" OFF)
option(SOL2_SINGLE "Enable generation and build of single header files" OFF)
option(SOL2_DOCS "Enable build of documentation" OFF)
option(SOL2_ENABLE_INSTALL "Enable installation of Sol2" ON)
# Single tests and examples tests will only be turned on if both SINGLE and TESTS are defined
CMAKE_DEPENDENT_OPTION(SOL2_TESTS_SINGLE "Enable build of tests using the premade single headers" ON
"SOL2_SINGLE;SOL2_TESTS" OFF)
CMAKE_DEPENDENT_OPTION(SOL2_EXAMPLES_SINGLE "Enable build of examples using the generated single headers" OFF
"SOL2_SINGLE;SOL2_EXAMPLES" OFF)
CMAKE_DEPENDENT_OPTION(SOL2_INTEROP_EXAMPLES_SINGLE "Enable build of interop examples using the generated single headers" OFF
"SOL2_SINGLE;SOL2_INTEROP_EXAMPLES" OFF)
CMAKE_DEPENDENT_OPTION(SOL2_DYNAMIC_LOADING_EXAMPLES_SINGLE "Enable build of dynamic loading examples using the generated single headers" OFF
"SOL2_SINGLE;SOL2_DYNAMIC_LOADING_EXAMPLES" OFF)
CMAKE_DEPENDENT_OPTION(SOL2_TESTS_EXAMPLES "Enable build of examples as tests" ON
"SOL2_EXAMPLES" OFF)
CMAKE_DEPENDENT_OPTION(SOL2_TESTS_INTEROP_EXAMPLES "Enable build of interop examples as tests" ON
"SOL2_INTEROP_EXAMPLES" OFF)
CMAKE_DEPENDENT_OPTION(SOL2_TESTS_DYNAMIC_LOADING_EXAMPLES "Enable build of dynamic loading examples as tests" ON
"SOL2_DYNAMIC_LOADING_EXAMPLES" OFF)
CMAKE_DEPENDENT_OPTION(BUILD_LUA_AS_DLL "Build Lua as a DLL" ON
"SOL2_BUILD_LUA" OFF)
if (SOL2_SYSTEM_INCLUDE)
set(sol2-system-include SYSTEM)
endif()
# # # sol2 Source Groups
# # Sources everyone is going to need
# Header files
file(GLOB_RECURSE sol2-headers
LIST_DIRECTORIES FALSE
CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/include/sol*.hpp
)
file(GLOB_RECURSE sol2-sources
LIST_DIRECTORIES FALSE
CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/source/**
)
# # # sol2 Library
# # Add a target for sol2's library to be included by external users
add_library(sol2 INTERFACE)
add_library(sol2::sol2 ALIAS sol2)
target_include_directories(sol2 ${sol2-system-include}
INTERFACE
$<BUILD_INTERFACE:${CMAKE_CURRENT_SOURCE_DIR}/include>
$<INSTALL_INTERFACE:include>)
# # Version configurations
configure_package_config_file(
cmake/sol2-config.cmake.in
"${CMAKE_CURRENT_BINARY_DIR}/cmake/sol2-config.cmake"
INSTALL_DESTINATION lib/cmake/sol2
NO_CHECK_REQUIRED_COMPONENTS_MACRO)
write_basic_package_version_file(
"${CMAKE_CURRENT_BINARY_DIR}/cmake/sol2-config-version.cmake"
COMPATIBILITY AnyNewerVersion)
export(TARGETS sol2
FILE "${CMAKE_CURRENT_BINARY_DIR}/cmake/sol2-targets.cmake")
if(SOL2_ENABLE_INSTALL)
install(TARGETS sol2
EXPORT sol2)
install(EXPORT sol2
FILE sol2-targets.cmake
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/sol2")
install(DIRECTORY include/sol
DESTINATION "${CMAKE_INSTALL_INCLUDEDIR}")
install(FILES
"${CMAKE_CURRENT_BINARY_DIR}/cmake/sol2-config.cmake"
"${CMAKE_CURRENT_BINARY_DIR}/cmake/sol2-config-version.cmake"
DESTINATION "${CMAKE_INSTALL_LIBDIR}/cmake/sol2")
endif()
# # # sol2 Library - Single header target
if (SOL2_SINGLE)
message(STATUS "sol2 adding single...")
add_subdirectory(single)
endif()
# # # documentation
# Generates the docs
if (SOL2_DOCS)
message(STATUS "sol2 adding docs...")
add_subdirectory(documentation)
endif()
if(SOL2_ENABLE_INSTALL)
# pkg-config support, except on Windows
if(NOT WIN32 OR NOT CMAKE_HOST_SYSTEM_NAME MATCHES Windows)
set(PKGCONFIG_INSTALL_DIR
"${CMAKE_INSTALL_DATAROOTDIR}/pkgconfig"
CACHE PATH "Path where sol2.pc is installed")
configure_file("${CMAKE_CURRENT_SOURCE_DIR}/sol2.pc.in" "${CMAKE_CURRENT_BINARY_DIR}/sol2.pc" @ONLY)
install(FILES "${CMAKE_CURRENT_BINARY_DIR}/sol2.pc" DESTINATION "${PKGCONFIG_INSTALL_DIR}")
endif()
endif()
if (SOL2_CI)
message(STATUS "sol2 Contiguous Integration is on")
endif()
if (SOL2_EXAMPLES OR SOL2_TESTS_EXAMPLES OR SOL2_EXAMPLES_SINGLE OR SOL2_INTEROP_EXAMPLES OR SOL2_TESTS_INTEROP_EXAMPLES OR SOL2_INTEROP_EXAMPLES_SINGLE OR SOL2_DYNAMIC_LOADING_EXAMPLES OR SOL2_TESTS_DYNAMIC_LOADING_EXAMPLES OR SOL2_DYNAMIC_LOADING_EXAMPLES_SINGLE)
set(SOL2_DO_EXAMPLES TRUE)
else()
set(SOL2_DO_EXAMPLES FALSE)
endif()
if (SOL2_TESTS OR SOL2_TESTS_SINGLE)
set(SOL2_DO_TESTS TRUE)
else()
set(SOL2_DO_TESTS FALSE)
endif()
# # # Tests, Examples and other CI suites that come with sol2
if (sol2-is-top-level-project)
# # # General project output locations
if (CMAKE_SIZEOF_VOID_P EQUAL 4)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/x86/lib")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/x86/bin")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/x86/bin")
else()
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/x64/lib")
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/x64/bin")
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}/x64/bin")
endif()
if (NOT CMAKE_CXX_STANDARD GREATER_EQUAL 17)
set(CMAKE_CXX_STANDARD 17)
endif()
if (NOT CMAKE_C_STANDARD GREATER_EQUAL 11)
set(CMAKE_C_STANDARD 11)
endif()
# Build Flag Settings
# Basic/Normal flags
check_compiler_flag(disable-permissive MSVC /permissive- GCC -pedantic)
check_compiler_flag(utf8-literal-encoding MSVC /execution-charset:utf-8 GCC -fexec-charset=utf-8)
check_compiler_flag(utf8-source-encoding MSVC /source-charset:utf-8 GCC -finput-charset=utf-8)
check_compiler_flag(extra-constexpr-depth MSVC /constexpr:depth2147483647 GCC -fconstexpr-depth=2147483647 CLANG -fconstexpr-depth=2147483647)
check_compiler_flag(extra-constexpr-steps MSVC /constexpr:steps2147483647 GCC -fconstexpr-ops-limit=2147483647 CLANG -fconstexpr-steps=2147483647)
check_compiler_flag(template-debugging-mode GCC -ftemplate-backtrace-limit=0)
check_compiler_flag(big-obj MSVC /bigobj)
# Overall warning flags
check_compiler_flag(pedantic GCC -pedantic)
check_compiler_flag(warn-pedantic GCC -Wpedantic)
check_compiler_flag(warn-all MSVC /W4 GCC -Wall)
check_compiler_flag(warn-extra GCC -Wextra)
check_compiler_flag(warn-errors MSVC /WX GCC -Werror)
# Individual warnings/errors
check_compiler_diagnostic(unknown-warning)
check_compiler_diagnostic(unknown-warning-option)
check_compiler_diagnostic(microsoft-cast)
check_compiler_diagnostic(noexcept-type)
check_compiler_diagnostic(unreachable-code MSVC 4702)
check_compiler_diagnostic(padding-from-alignment MSVC 4324)
# # # Libraries
# Here, we pull in all the necessary libraries for building examples and tests
# Find threading library
find_package(Threads REQUIRED)
string(TOLOWER ${SOL2_LUA_VERSION} NORMALIZED_LUA_VERSION)
# Find way to get Lua: build if requested, or attempt to build if no matching version is found
if (SOL2_BUILD_LUA)
find_package(LuaBuild REQUIRED COMPONENTS ${SOL2_LUA_VERSION})
elseif (NOT SOL2_LUA_VERSION)
find_package(LuaBuild REQUIRED)
else ()
if (NORMALIZED_LUA_VERSION MATCHES "5.1")
set(CREATE_LUALIB_TARGET TRUE)
find_package(Lua 5.1 EXACT REQUIRED)
elseif(NORMALIZED_LUA_VERSION MATCHES "5.2")
set(CREATE_LUALIB_TARGET TRUE)
find_package(Lua 5.2 EXACT REQUIRED)
elseif(NORMALIZED_LUA_VERSION MATCHES "5.3")
set(CREATE_LUALIB_TARGET TRUE)
find_package(Lua 5.3 EXACT REQUIRED)
elseif(NORMALIZED_LUA_VERSION MATCHES "5.4")
set(CREATE_LUALIB_TARGET TRUE)
find_package(Lua 5.4 EXACT REQUIRED)
elseif(NORMALIZED_LUA_VERSION MATCHES "luajit")
set(CREATE_LUALIB_TARGET TRUE)
find_package(LuaJIT REQUIRED)
else()
find_package(LuaBuild ${SOL2_LUA_VERSION} REQUIRED)
endif()
endif()
if (CREATE_LUALIB_TARGET AND LUA_FOUND)
set(lualib lua_imported_lib_${SOL2_LUA_VERSION})
foreach(lua_search_lib ${LUA_LIBRARIES})
get_filename_component(lsl_fname ${lua_search_lib} NAME)
if (lsl_fname MATCHES "lua" OR lsl_fname MATCHES "Lua" OR lsl_fname MATCHES "LUA")
if (lsl_fname MATCHES "\.so|\.dylib|\.dll")
set(lualibtype SHARED)
set(lualiblocation ${lua_search_lib})
else()
set(lualibtype STATIC)
set(lualiblocation ${lua_search_lib})
endif()
else()
set(LUA_SEARCH_DEPENDENCY_LIBS ${LUA_SEARCH_DEPENDENCY_LIBS} "${lua_search_lib}")
endif()
endforeach()
add_library(${lualib} ${lualibtype} IMPORTED)
set_target_properties(${lualib}
PROPERTIES
INTERFACE_INCLUDE_DIRECTORIES ${LUA_INCLUDE_DIR}
INTERFACE_LINK_LIBRARIES "${LUA_SEARCH_DEPENDENCY_LIBS} ${CMAKE_DL_LIBS}"
IMPORTED_LINK_INTERFACE_LANGUAGES C
IMPORTED_LOCATION ${lualiblocation})
set(LUA_LIBRARIES ${lualib})
endif()
if (NOT LUA_FOUND AND NOT LUABUILD_FOUND)
message(FATAL_ERROR "sol2 Lua \"${SOL2_LUA_VERSION}\" not found and could not be targeted for building")
endif()
# # Enable test harness for regular, example or single tests
if (SOL2_DO_TESTS OR (SOL2_TESTS_EXAMPLES AND SOL2_DO_EXAMPLES))
# enable ctest
message(STATUS "sol2 testing enabled...")
enable_testing()
endif()
# # # Examples
# # Enable examples to be built against the library
if (SOL2_DO_EXAMPLES)
# NOTE: will also add to tests if TESTS is defined
message(STATUS "sol2 adding examples...")
add_subdirectory(examples)
endif()
# # # Tests
# # Add tests here
if (SOL2_DO_TESTS)
# add subdir to get going
message(STATUS "sol2 adding tests...")
add_subdirectory(tests)
endif()
# # # Scratch Space
# # Scratch space for diagnosing bugs and other shenanigans
if (SOL2_SCRATCH)
message(STATUS "sol2 adding scratch space...")
add_subdirectory(scratch)
endif()
endif()
-27
View File
@@ -1,27 +0,0 @@
## Contributing to sol
Looking to contribute to sol? Well, first thing I want to mention is thank you!
Second of all, this is probably where you should look :)
## Reporting Issues
If you found a bug, please make sure to make an issue in the issue tracker.
The guidelines for reporting a bug are relatively simple and are as follows:
1. Produce a simple, short, compilable test case that reproduces your problem.
2. Make a descriptive title that summarises the bug as a whole.
3. Explain the bug in as much detail as you can in the body of the issue.
If you have all of those requirements set, then your issue reporting is golden.
## Submitting a pull request
Submitting a pull request is fairly simple, just make sure it focuses on a single aspect and doesn't
manage to have scope creep and it's probably good to go. It would be incredibly lovely if the style is
consistent to those found in the repository.
To help with this, a `.clang-format` is included. Please run it on your code before you push anything.
If you don't meet all of these style guidelines, don't fret. I'll probably fix it. But please
do make an effort to actually meet them. Otherwise I'm more likely to reject the pull request.
-27
View File
@@ -1,27 +0,0 @@
# 🎉 Donators! ♥ 🎉
Thank you to all patrons, donators and contributors who help keep sol2 amazing.
- Robert Salvet
- Ορφέας Ζαφείρης - 2x Donations!
- Michael Wallar
- Johannes Schultz
- Elias Daler
- BECKMANN & EGLE Industrieelektronik GmbH [bue.de](https://www.bue.de/)
# 🎉 Patrons! ♥ 🎉
Beyond just a one-time donation, patrons make a continued commitment to help keep sol2 supported and bug-free. Thank you for your patronage! Here are the supporters that wanted to be featured as sol2 contributors.
- Joel Falcou
- Michael Caisse
- Joshua Fisher
- Ορφέας Ζαφείρης
# Company Patrons / Supporters #
Companies who sign up for a long-term support contract or patronage are listed here! They really push forward what's possible with sol2 (and the newer v3)! Please reach out to phdofthehouse@gmail.com if you are interested in a custom solution or a long-term support contract that goes beyond the current release's needs!
- Intrepid Control Systems [intrepidcs.com](https://www.intrepidcs.com/)
-71
View File
@@ -1,71 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2017 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Start from the ubuntu:bionic image
FROM ubuntu:bionic
# owner
LABEL author="ThePhD <phdofthehouse@gmail.com>"
LABEL maintainer="ThePhD <phdofthehouse@gmail.com>"
# We want our working directory to be the home directory
WORKDIR /root
# RUN is how you write to the image you've pulled down
# RUN actions are "committed" to the image, and everything will
# start from the base after all run commands are executed
RUN apt-get update && apt-get install -y \
zsh
# Scripts should be added directly to the docker image to get us started
# We can mount the whole sol2 directory later as a volume
ADD scripts/ /root/sol2-scripts
RUN mkdir -p /root/build-sol2/Debug /root/build-sol2/Release
RUN chmod +x /root/sol2-scripts/preparation.linux.sh
VOLUME /root/sol2
#ADD . /root/sol2
# # Above this is more or less static parts: the rest is non-static
# # This is ordered like this so making multiple of these
# # containers is more or less identical up to this point
# Command line arguments, with default values
ARG SOL2_PLATFORM=x64
ARG SOL2_LUA_VERSION=x64
ARG SOL2_LUA_VERSION=5.4.4
ARG SOL2_TEST_SINGLE=false
ARG SOL2_TEST_INTEROP=false
ARG SOL2_CI=true
ARG GCC_VERSION
ARG LLVM_VERSION
# Potential environment variables
ENV SOL2_LUA_VERSION=${SOL2_LUA_VERSION} SOL2_TEST_SINGLE=${SOL2_TEST_SINGLE} SOL2_TEST_INTEROP=${SOL2_TEST_INTEROP} SOL2_CI=${SOL2_CI} SOL2_PLATFORM=${SOL2_PLATFORM} GCC_VERSION=${GCC_VERSION} LLVM_VERSION=${LLVM_VERSION} SOL2_DIR=/root/sol2
RUN ["/usr/bin/env", "zsh", "-e", "/root/sol2-scripts/preparation.linux.sh"]
# CMD/ENTRYPOINT is different from RUN
# these are done on a per-instantiation and essentially describe
# the DEFAULT behavior of this container when its started, not what state it
# gets "saved" in...
# it only runs the last CMD/ENTRYPOINT as the default behavior:
# multiple CMDs will not be respected
ENTRYPOINT ["/usr/bin/env", "zsh", "-e", "/root/sol2/scripts/run.linux.sh"]
-20
View File
@@ -1,20 +0,0 @@
The MIT License (MIT)
Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-161
View File
@@ -1,161 +0,0 @@
# sol2
[![Documentation Status](https://readthedocs.org/projects/sol2/badge/?version=latest)](http://sol2.readthedocs.io/en/latest/?badge=latest)
sol2 is a C++ library binding to Lua. It currently supports all Lua versions 5.1+ (LuaJIT 2.0+ and MoonJIT included). sol2 aims to be easy to use and easy to add to a project. The library is header-only for easy integration with projects, and a single header can be used for drag-and-drop start up.
## Sneak Peek
```cpp
#include <sol/sol.hpp>
#include <cassert>
int main() {
sol::state lua;
int x = 0;
lua.set_function("beep", [&x]{ ++x; });
lua.script("beep()");
assert(x == 1);
}
```
```cpp
#include <sol/sol.hpp>
#include <cassert>
struct vars {
int boop = 0;
};
int main() {
sol::state lua;
lua.new_usertype<vars>("vars", "boop", &vars::boop);
lua.script("beep = vars.new()\n"
"beep.boop = 1");
assert(lua.get<vars>("beep").boop == 1);
}
```
More examples are given in the examples directory [here](https://github.com/ThePhD/sol2/tree/develop/examples).
## Documentation
Find it [here](http://sol2.rtfd.io/). A run-through kind of tutorial is [here](http://sol2.readthedocs.io/en/latest/tutorial/all-the-things.html)! The API documentation goes over most cases (particularly, the "api/usertype" and "api/table_proxy" and "api/function" sections) that should still get you off your feet and going, and there's an examples directory [here](https://github.com/ThePhD/sol2/tree/develop/examples) as well.
# "I need X Feature or Fix, Right Now™"
Find the support option that's right for you, [here](https://github.com/ThePhD/.github/blob/main/SUPPORT.md)! If you're happy to wait, you can just file a boring issue and we'll get to it Whenever There Is Time™.
## I want to donate to help!
You can find [donation and sponorship options here](https://github.com/ThePhD/.github/blob/main/SUPPORT.md#support-in-general) and from the little heart button near the top of this repository that will take you to a bevy of links in which you can donate and show support for this project and others!
# Features
- [Fastest in the land](http://sol2.readthedocs.io/en/latest/benchmarks.html) (see: sol2 bar in graph).
- Supports retrieval and setting of multiple types including:
* `std::string`, `std::wstring`, `std::u16string` and `std::u32string` support (and for views).
* understands and works with containers such as `std::map/unordered_map`, c-style arrays, vectors, non-standard custom containers and more.
* user-defined types, with or **without** registering that type
* `std::unique_ptr`, `std::shared_ptr`, and optional support of other pointer types like `boost::shared_ptr`.
* custom `optional<T>` that works with references, and support for the inferior `std::optional`.
* C++17 support for variants and similar new types.
- Lambda, function, and member function bindings are supported.
- Intermediate type for checking if a variable exists.
- Simple API that completely abstracts away the C stack API, including `protected_function` with the ability to use an error-handling function.
- `operator[]`-style manipulation of tables
- C++ type representations in Lua userdata as `usertype`s with guaranteed cleanup.
- Customization points to allow your C++ objects to be pushed and retrieved from Lua as multiple consecutive objects, or anything else you desire!
- Overloaded function calls: `my_function(1); my_function("Hello")` in the same Lua script route to different function calls based on parameters
- Support for tables, nested tables, table iteration with `table.for_each` / `begin()` and `end()` iterators.
- Zero string overhead for usertype function lookup.
## Supported Compilers
sol2 makes use of C++17 features. GCC 7.x.x and Clang 3.9.x (with `-std=c++1z` and appropriate standard library) or higher should be able to compile without problems. However, the officially supported and CI-tested compilers are:
- GCC 7.x.x+ (MinGW 7.x.x+)
- Clang 3.9.x+
- Visual Studio 2017 Community (Visual C++ 15.0)+
Please make sure you use the `-std=c++2a`, `-std=c++1z`, `-std=c++17` or better standard flags
(some of these flags are the defaults in later versions of GCC, such as 7+ and better).
If you would like support for an older compiler (at the cost of some features), use the latest tagged sol2 branch. If you would like support for an even older compiler, feel free to contact me for a Custom Solution.
sol2 is checked by-hand for other platforms as well, including Android-based builds with GCC and iOS-based builds out of XCode with Apple-clang. It should work on both of these platforms, so long as you have the proper standards flags. If something doesn't work or you need special options, you may need to look into the different ways to support the project to have it done for you!
## Creating a single header
You can grab a single header (and the single forward header) out of the library [here](https://github.com/ThePhD/sol2/tree/develop/single). For stable version, check the releases tab on GitHub for a provided single header file for maximum ease of use. A script called [`single.py`](https://github.com/ThePhD/sol2/blob/develop/single/single.py) is provided in the repository if there's some bleeding edge change that hasn't been published on the releases page. You can run this script to create a single file version of the library so you can only include that part of it. Check `single.py --help` for more info.
If you use CMake, you can also configure and generate a project that will generate the `sol2_single_header` for you. You can also include the project using CMake. Run CMake for more details. Thanks @Nava2, @alkino, @mrgreywater and others for help with making the CMake build a reality.
# Testing
Testing turns on certain CI-only variables in the CMake to test a myriad of configuration options. You can generate the tests by running CMake and configuring `SOL2_TESTS`, `SOL2_TESTS_SINGLE`, `SOL2_TESTS_EXAMPLES`, and `SOL2_EXAMPLES` to be on. Make sure `SOL2_SINGLE` is also on.
You will need any flavor of python3 and an available compiler. The testing suite will build its own version of Lua and LuaJIT, so you do not have to provide one (you may provide one with the `LUA_LOCAL_DIR` variable).
# Presentations
"A Sun For the Moon - A Zero-Overhead Lua Abstraction using C++"
ThePhD
Lua Workshop 2016 - Mashape, San Francisco, CA
[Deck](https://github.com/ThePhD/sol2/blob/develop/docs/presentations/2016.10.14%20-%20ThePhD%20-%20No%20Overhead%20C%20Abstraction.pdf)
"Wrapping Lua C in C++ - Efficiently, Nicely, and with a Touch of Magic"
ThePhD
Boston C++ Meetup November 2017 - CiC (Milk Street), Boston, MA
[Deck](https://github.com/ThePhD/sol2/blob/develop/docs/presentations/2017.11.08%20-%20ThePhD%20-%20Wrapping%20Lua%20C%20in%20C%2B%2B.pdf)
"Biting the CMake Bullet"
ThePhD
Boston C++ Meetup February 2018 - CiC (Main Street), Cambridge, MA
[Deck](https://github.com/ThePhD/sol2/blob/develop/docs/presentations/2018.02.06%20-%20ThePhD%20-%20Biting%20the%20CMake%20Bullet.pdf)
"Compile Fast, Run Faster, Scale Forever: A look into the sol2 Library"
ThePhD
C++Now 2018 - Hudson Commons, Aspen Physics Center, Aspen, Colorado
[Deck](https://github.com/ThePhD/sol2/blob/develop/docs/presentations/2018.05.10%20-%20ThePhD%20-%20Compile%20Fast%2C%20Run%20Faster%2C%20Scale%20Forever.pdf)
"Scripting at the Speed of Thought: Using Lua in C++ with sol2"
ThePhD
CppCon 2018 - 404 Keystone, Meydenbauer Center, Aspen, Colorado
[Deck](https://github.com/ThePhD/sol2/blob/develop/docs/presentations/2018.09.28%20-%20ThePhD%20-%20Scripting%20at%20the%20Speed%20of%20Thought.pdf)
"The Plan for Tomorrow: Compile-Time Extension Points in C++"
ThePhD
C++Now 2019 - Flug Auditorium, Aspen Physics Center, Aspen, Colorado
[Deck](https://github.com/ThePhD/sol2/blob/develop/docs/presentations/2019.05.10%20-%20ThePhD%20-%20The%20Plan%20for%20Tomorrow%20-%20Compile-Time%20Extension%20Points%20in%20C%2b%2b.pdf)
# License
sol2 is distributed with an MIT License. You can see LICENSE.txt for more info.
If you need a custom solution, [feel free to reach out](https://soasis.org/contact/opensource/).
-52
View File
@@ -1,52 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # # sol2 - cmake - basic project configuration
include_guard(DIRECTORY)
list(PREPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/Packages")
list(PREPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake/Modules")
list(APPEND CMAKE_MODULE_PATH "${PROJECT_SOURCE_DIR}/cmake")
list(APPEND CMAKE_MESSAGE_CONTEXT "${PROJECT_NAME}")
if (PROJECT_SOURCE_DIR STREQUAL CMAKE_SOURCE_DIR)
set(sol2-is-top-level-project TRUE)
else()
set(sol2-is-top-level-project FALSE)
endif()
# # CMake and sol2 Includes
# CMake
include(CheckCXXCompilerFlag)
include(CheckCCompilerFlag)
include(CheckIPOSupported)
include(CMakeDependentOption)
include(CMakePrintHelpers)
include(GNUInstallDirs)
include(FeatureSummary)
include(FetchContent)
include(CTest)
# sol2
include(CheckCompilerDiagnostic)
include(CheckCompilerFlag)
include(FindVersion)
-92
View File
@@ -1,92 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # # sol2 - cmake - compiler diagnostic checking
include_guard(GLOBAL)
include(CheckCXXCompilerFlag)
include(CheckCCompilerFlag)
#[[
Given a diagnostic name and flag, like
check_cxx_compiler_diagnostic(pig MSVC 1312)
or
check_cxx_compiler_diagnostic(pig GCC acab)
we check if the given flag works C++ compiler. If it does, we then generate
a --warn, --allow, --deny, and --forbid prefixed set of variables. Users are
then free to simply apply them to targets at will.
]]
function (check_compiler_diagnostic diagnostic)
cmake_parse_arguments(diagnostic "" "GCC;MSVC;CLANG" "" ${ARGN})
if (NOT diagnostic_GCC)
set(diagnostic_GCC ${diagnostic})
endif()
if (NOT diagnostic_MSVC)
set(diagnostic_MSVC ${diagnostic})
endif()
if (NOT diagnostic_CLANG)
set(diagnostic_CLANG ${diagnostic_GCC})
endif()
string(MAKE_C_IDENTIFIER "${diagnostic}" suffix)
string(TOUPPER "${suffix}" suffix)
get_property(enabled-languages GLOBAL PROPERTY ENABLED_LANGUAGES)
if (CXX IN_LIST enabled-languages)
if (MSVC)
check_cxx_compiler_flag(-wo${diagnostic_MSVC} CXX_DIAGNOSTIC_${suffix})
elseif (CMAKE_CXX_COMPILER_ID MATCHES Clang)
check_cxx_compiler_flag(-W${diagnostic_CLANG} CXX_DIAGNOSTIC_${suffix})
else()
check_cxx_compiler_flag(-W${diagnostic_GCC} CXX_DIAGNOSTIC_${suffix})
endif()
endif()
if (C IN_LIST enabled-languages)
if (MSVC)
check_c_compiler_flag(-wo${diagnostic_MSVC} C_DIAGNOSTIC_${suffix})
elseif (CMAKE_CXX_COMPILER_ID MATCHES Clang)
check_c_compiler_flag(-W${diagnostic_CLANG} C_DIAGNOSTIC_${suffix})
else()
check_c_compiler_flag(-W${diagnostic_GCC} C_DIAGNOSTIC_${suffix})
endif()
endif()
string(CONCAT when $<OR:
$<AND:$<BOOL:${CXX_DIAGNOSTIC_${suffix}}>,$<COMPILE_LANGUAGE:CXX>>,
$<AND:$<BOOL:${C_DIAGNOSTIC_${suffix}}>,$<COMPILE_LANGUAGE:C>>
>)
string(CONCAT diagnostic_flag
$<$<COMPILE_LANG_AND_ID:CXX,MSVC>:${diagnostic_MSVC}>
$<$<COMPILE_LANG_AND_ID:C,MSVC>:${diagnostic_MSVC}>
$<$<COMPILE_LANG_AND_ID:CXX,GNU>:${diagnostic_GCC}>
$<$<COMPILE_LANG_AND_ID:C,GNU>:${diagnostic_GCC}>
$<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:${diagnostic_CLANG}>
$<$<COMPILE_LANG_AND_ID:C,Clang,AppleClang>:${diagnostic_CLANG}>
)
set(forbid_prefix $<IF:$<BOOL:${MSVC}>,-we,-Werror=>)
set(allow_prefix $<IF:$<BOOL:${MSVC}>,-wd,-Wno->)
set(warn_prefix $<IF:$<BOOL:${MSVC}>,-w1,-W>)
set(--forbid-${diagnostic} $<${when}:${forbid_prefix}${diagnostic_flag}> PARENT_SCOPE)
set(--deny-${diagnostic} ${--forbid-${diagnostic}} PARENT_SCOPE)
set(--allow-${diagnostic} $<${when}:${allow_prefix}${diagnostic_flag}> PARENT_SCOPE)
set(--warn-${diagnostic} $<${when}:${warn_prefix}${diagnostic_flag}> PARENT_SCOPE)
endfunction()
-83
View File
@@ -1,83 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # # sol2 - cmake - compiler flag checking
include_guard(GLOBAL)
include(CheckCXXCompilerFlag)
include(CheckCCompilerFlag)
#[[
Given a flag name and the actual flag, like
check_cxx_compiler_flag(strict-conformance MSVC /permissive- GCC -pedantic)
we check if the given flag works C++ compiler. If it is, then
--strict-conformance will be the provided flag. MSVC and GCC are the 2 different
"style" of flags to be tested for.
]]
function (check_compiler_flag flag_name)
cmake_parse_arguments(PARSE_ARGV 1 flag "" "" "GCC;MSVC;CLANG")
if (NOT flag_MSVC)
set(flag_MSVC /${flag_name})
endif()
if (NOT flag_GCC)
set(flag_GCC ${flag_name})
endif()
if (NOT flag_CLANG)
set(flag_CLANG ${flag_GCC})
endif()
string(MAKE_C_IDENTIFIER "${flag_name}" suffix)
string(TOUPPER "${suffix}" suffix)
get_property(enabled-languages GLOBAL PROPERTY ENABLED_LANGUAGES)
if (CXX IN_LIST enabled-languages)
if (MSVC)
check_cxx_compiler_flag(${flag_MSVC} CXX_CHECK_FLAG_${suffix})
elseif (CMAKE_CXX_COMPILER_ID MATCHES Clang)
check_cxx_compiler_flag(${flag_CLANG} CXX_CHECK_FLAG_${suffix})
else()
check_cxx_compiler_flag(${flag_GCC} CXX_CHECK_FLAG_${suffix})
endif()
endif()
if (C IN_LIST enabled-languages)
if (MSVC)
check_c_compiler_flag(${flag_MSVC} C_CHECK_FLAG_${suffix})
elseif (CMAKE_C_COMPILER_ID MATCHES Clang)
check_c_compiler_flag(${flag_CLANG} C_CHECK_FLAG_${suffix})
else()
check_c_compiler_flag(${flag_GCC} C_CHECK_FLAG_${suffix})
endif()
endif()
string(CONCAT when $<OR:
$<AND:$<BOOL:${CXX_CHECK_FLAG_${suffix}}>,$<COMPILE_LANGUAGE:CXX>>,
$<AND:$<BOOL:${C_CHECK_FLAG_${suffix}}>,$<COMPILE_LANGUAGE:C>>
>)
string(CONCAT compiler_flag
$<$<COMPILE_LANG_AND_ID:CXX,MSVC>:${flag_MSVC}>
$<$<COMPILE_LANG_AND_ID:C,MSVC>:${flag_MSVC}>
$<$<COMPILE_LANG_AND_ID:CXX,GNU>:${flag_GCC}>
$<$<COMPILE_LANG_AND_ID:C,GNU>:${flag_GCC}>
$<$<COMPILE_LANG_AND_ID:CXX,Clang,AppleClang>:${flag_CLANG}>
$<$<COMPILE_LANG_AND_ID:C,Clang,AppleClang>:${flag_CLANG}>
)
set(--${flag_name} $<${when}:${compiler_flag}> PARENT_SCOPE)
endfunction()
-35
View File
@@ -1,35 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
if(_common_core_included)
return()
endif(_common_core_included)
set(_common_core_included true)
# # Prepend function (is there an equivalent in CMake somewhere...?)
function(prepend var prefix)
set(l "")
foreach(f ${ARGN})
list(APPEND l "${prefix}${f}")
endforeach(f)
SET(${var} "${l}" PARENT_SCOPE)
ENDFUNCTION(prepend)
-61
View File
@@ -1,61 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # # sol2 - cmake - version matching
include_guard(GLOBAL)
#[[
This is used to create a version variable. How these are used or set is up
to the user.
TODO: Support find_version(<VAR> SOURCE <FILE>) for parsing a version name from a header file
TODO: Support find_version(<VAR> LIBRARY <FILE>) for .dll/.lib/.so/.dylib parsing
]]
function (find_version output)
cmake_parse_arguments(ARG "" "OPTION;REGEX;COMMAND;DOC" "" ${ARGN})
unset(version-output)
unset(version-check)
if (NOT ARG_OPTION)
set(ARG_OPTION "--version")
endif()
if (NOT ARG_REGEX)
set(ARG_REGEX "[^0-9]*([0-9]+)[.]([0-9]+)?[.]?([0-9]+)?[.]?([0-9]+)?.*")
endif()
if (ARG_COMMAND AND NOT DEFINED ${output})
execute_process(
COMMAND ${ARG_COMMAND} ${ARG_OPTION}
OUTPUT_VARIABLE version-output
OUTPUT_STRIP_TRAILING_WHITESPACE
ENCODING UTF-8)
if (version-output)
string(REGEX MATCH "${ARG_REGEX}" version-check ${version-output})
endif()
if (version-check)
string(JOIN "." ${output}
${CMAKE_MATCH_1}
${CMAKE_MATCH_2}
${CMAKE_MATCH_3}
${CMAKE_MATCH_4})
set(${output} "${${output}}" CACHE STRING "${ARG_DOC}" FORCE)
endif()
endif()
endfunction()
-76
View File
@@ -1,76 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
include(ExternalProject)
include(FindPackageHandleStandardArgs)
include(Common/Core)
# # Base variables
set(kaguya_version 1.3.2)
set(kaguya_lib kaguya_lib_${kaguya_version})
# # Useful locations
set(kaguya_build_toplevel "${CMAKE_BINARY_DIR}/vendor/kaguya_${kaguya_version}")
set(kaguya_include_dirs "${kaguya_build_toplevel}/include")
# # kaguya library sources
set(kaguya_sources kaguya/kaguya.hpp)
prepend(kaguya_sources "${kaguya_build_toplevel}/include/" ${kaguya_sources})
# # External project to get sources
ExternalProject_Add(KAGUYA_BUILD_SOURCE
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS FALSE
# # Use Git to get what we need
GIT_SHALLOW TRUE
GIT_SUBMODULES ""
GIT_REPOSITORY https://github.com/satoren/kaguya.git
PREFIX ${kaguya_build_toplevel}
SOURCE_DIR ${kaguya_build_toplevel}
DOWNLOAD_DIR ${kaguya_build_toplevel}
TMP_DIR "${kaguya_build_toplevel}-tmp"
STAMP_DIR "${kaguya_build_toplevel}-stamp"
INSTALL_DIR "${kaguya_build_toplevel}/local"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS "${kaguya_sources}")
add_library(${kaguya_lib} INTERFACE)
add_dependencies(${kaguya_lib} KAGUYA_BUILD_SOURCE)
target_include_directories(${kaguya_lib} INTERFACE ${kaguya_include_dirs})
target_link_libraries(${kaguya_lib} INTERFACE ${LUA_LIBRARIES})
if (NOT MSVC)
target_compile_options(${kaguya_lib} INTERFACE
-Wno-noexcept-type -Wno-ignored-qualifiers -Wno-unused-parameter)
endif()
set(KAGUYABUILD_FOUND TRUE)
set(KAGUYA_LIBRARIES ${kaguya_lib})
set(KAGUYA_INCLUDE_DIRS ${kaguya_include_dirs})
FIND_PACKAGE_HANDLE_STANDARD_ARGS(KaguyaBuild
FOUND_VAR KAGUYABUILD_FOUND
REQUIRED_VARS KAGUYA_LIBRARIES KAGUYA_INCLUDE_DIRS
VERSION_VAR kaguya_version)
@@ -1,77 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Uses the Lua version and calculates the names of the include directories and library
# name accordingly.
#
# ::
# _prefix - Prefix added to all variables exposed, e.g. "lua" or "luajit"
# _lua_suffix - Name suffix, typically only used for specifiying luajit, which is "jit"
function(_lua_set_version_vars _prefix _lua_suffix)
set(LUA_VERSIONS5 5.3 5.2 5.1 5.0)
if (${_prefix}_FIND_VERSION_EXACT)
if (${_prefix}_FIND_VERSION_COUNT GREATER 1)
set(_${_prefix}_append_versions ${${_prefix}_FIND_VERSION_MAJOR}.${${_prefix}_FIND_VERSION_MINOR})
endif ()
elseif (${_prefix}_FIND_VERSION)
# once there is a different major version supported this should become a loop
if (NOT ${_prefix}_FIND_VERSION_MAJOR GREATER 5)
if (${_prefix}_FIND_VERSION_COUNT EQUAL 1)
set(_${_prefix}_append_versions ${${_prefix}_VERSIONS5})
else ()
foreach (subver IN LISTS ${_prefix}_VERSIONS5)
if (NOT subver VERSION_LESS ${${_prefix}_FIND_VERSION})
list(APPEND _${_prefix}_append_versions ${subver})
endif ()
endforeach ()
endif ()
endif ()
else ()
# once there is a different major version supported this should become a loop
set(_${_prefix}_append_versions ${LUA_VERSIONS5})
endif ()
list(APPEND _${_prefix}_include_subdirs "include/lua" "include")
foreach (ver IN LISTS _${_prefix}_append_versions)
string(REGEX MATCH "^([0-9]+)\\.([0-9]+)$" _ver "${ver}")
list(APPEND _${_prefix}_include_subdirs
include/lua${_lua_suffix}${CMAKE_MATCH_1}${CMAKE_MATCH_2}
include/lua${_lua_suffix}${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
include/lua${_lua_suffix}-${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
)
# LuaJIT hides itself as Lua lib (maintaining ABI compat)
list(APPEND _${_prefix}_library_names
lua${CMAKE_MATCH_1}${CMAKE_MATCH_2}
lua${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
lua.${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
lua-${CMAKE_MATCH_1}.${CMAKE_MATCH_2}
)
endforeach ()
set(_${_prefix}_include_subdirs "${_${_prefix}_include_subdirs}" PARENT_SCOPE)
set(_${_prefix}_append_versions "${_${_prefix}_append_versions}" PARENT_SCOPE)
set(_${_prefix}_library_names "${_${_prefix}_library_names}" PARENT_SCOPE)
endfunction(_lua_set_version_vars)
-28
View File
@@ -1,28 +0,0 @@
# Distributed under the OSI-approved BSD 3-Clause License. See accompanying
# file Copyright.txt or https://cmake.org/licensing for details.
# Provides a common-mechanic for extracting Lua versions from Lua/LuaJIT headers
macro(_lua_check_header_version _header_file _prefix)
# At least 5.[012] have different ways to express the version
# so all of them need to be tested. Lua 5.2 defines LUA_VERSION
# and LUA_RELEASE as joined by the C preprocessor, so avoid those.
file(STRINGS "${_header_file}" lua_version_strings
REGEX "^#define[ \t]+LUA_(RELEASE[ \t]+\"Lua [0-9]|VERSION([ \t]+\"Lua [0-9]|_[MR])).*")
string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_MAJOR[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" ${_prefix}_VERSION_MAJOR ";${lua_version_strings};")
if (${_prefix}_VERSION_MAJOR MATCHES "^[0-9]+$")
string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_MINOR[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" "${_prefix}_VERSION_MINOR" ";${lua_version_strings};")
string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION_RELEASE[ \t]+\"([0-9])\"[ \t]*;.*" "\\1" "${_prefix}_VERSION_PATCH" ";${lua_version_strings};")
set(${_prefix}_VERSION_STRING "${${_prefix}_VERSION_MAJOR}.${${_prefix}_VERSION_MINOR}.${${_prefix}_VERSION_PATCH}")
else ()
string(REGEX REPLACE ".*;#define[ \t]+LUA_RELEASE[ \t]+\"Lua ([0-9.]+)\"[ \t]*;.*" "\\1" ${_prefix}_VERSION_STRING ";${lua_version_strings};")
if (NOT LUA_VERSION_STRING MATCHES "^[0-9.]+$")
string(REGEX REPLACE ".*;#define[ \t]+LUA_VERSION[ \t]+\"Lua ([0-9.]+)\"[ \t]*;.*" "\\1" ${_prefix}_VERSION_STRING ";${lua_version_strings};")
endif ()
string(REGEX REPLACE "^([0-9]+)\\.[0-9.]*$" "\\1" ${_prefix}_VERSION_MAJOR "${${_prefix}_VERSION_STRING}")
string(REGEX REPLACE "^[0-9]+\\.([0-9]+)[0-9.]*$" "\\1" ${_prefix}_VERSION_MINOR "${${_prefix}_VERSION_STRING}")
string(REGEX REPLACE "^[0-9]+\\.[0-9]+\\.([0-9]).*" "\\1" ${_prefix}_VERSION_PATCH "${${_prefix}_VERSION_STRING}")
endif ()
unset(lua_version_strings)
endmacro(_lua_check_header_version)
-74
View File
@@ -1,74 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
include(ExternalProject)
include(FindPackageHandleStandardArgs)
include(Common/Core)
# # Base variables
set(luabridge_version 1.0.2)
set(luabridge_lib luabridge_lib_${luabridge_version})
# # Useful locations
set(luabridge_build_toplevel "${CMAKE_BINARY_DIR}/vendor/luabridge_${luabridge_version}")
set(luabridge_include_dirs "${luabridge_build_toplevel}/Source")
# # luabridge library sources
set(luabridge_sources LuaBridge/LuaBridge.h)
prepend(luabridge_sources "${luabridge_build_toplevel}/Source/" ${luabridge_sources})
# # External project to get sources
ExternalProject_Add(LUABRIDGE_BUILD_SOURCE
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS FALSE
# # Use Git to get what we need
GIT_SHALLOW TRUE
GIT_SUBMODULES ""
GIT_REPOSITORY https://github.com/ThePhD/LuaBridge.git
PREFIX ${luabridge_build_toplevel}
SOURCE_DIR ${luabridge_build_toplevel}
DOWNLOAD_DIR ${luabridge_build_toplevel}
TMP_DIR "${luabridge_build_toplevel}-tmp"
STAMP_DIR "${luabridge_build_toplevel}-stamp"
INSTALL_DIR "${luabridge_build_toplevel}/local"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS "${luabridge_sources}")
add_library(${luabridge_lib} INTERFACE)
add_dependencies(${luabridge_lib} LUABRIDGE_BUILD_SOURCE)
target_include_directories(${luabridge_lib} INTERFACE ${luabridge_include_dirs})
target_link_libraries(${luabridge_lib} INTERFACE ${LUA_LIBRARIES})
if (NOT MSVC)
target_compile_options(${luabridge_lib} INTERFACE
-Wno-noexcept-type -Wno-ignored-qualifiers -Wno-unused-parameter)
endif()
set(LUABRIDGEBUILD_FOUND TRUE)
set(LUABRIDGE_LIBRARIES ${luabridge_lib})
set(LUABRIDGE_INCLUDE_DIRS ${luabridge_include_dirs})
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LuabridgeBuild
FOUND_VAR LUABRIDGEBUILD_FOUND
REQUIRED_VARS LUABRIDGE_LIBRARIES LUABRIDGE_INCLUDE_DIRS
VERSION_VAR luabridge_version)
-120
View File
@@ -1,120 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # Standard CMake Libraries
include(FindPackageHandleStandardArgs)
# Contain literally everything inside of this function to prevent spillage
function(find_lua_build LUA_VERSION)
# # # Variables
# # Core Paths
string(TOLOWER ${LUA_VERSION} LUA_BUILD_NORMALIZED_LUA_VERSION)
if (LUA_BUILD_NORMALIZED_LUA_VERSION MATCHES "luajit")
set(LUA_BUILD_LIBNAME ${LUA_VERSION})
elseif (BUILD_LUAJIT)
set(LUA_BUILD_LIBNAME luajit-${LUA_VERSION})
elseif (LUA_BUILD_NORMALIZED_LUA_VERSION MATCHES "lua")
set(LUA_BUILD_LIBNAME ${LUA_VERSION})
elseif (BUILD_LUA)
set(LUA_BUILD_LIBNAME lua-${LUA_VERSION})
else()
set(LUA_BUILD_LIBNAME lua-${LUA_VERSION})
endif()
set(LUA_BUILD_TOPLEVEL "${CMAKE_BINARY_DIR}/vendor/${LUA_BUILD_LIBNAME}")
set(LUA_BUILD_INSTALL_DIR "${LUA_BUILD_TOPLEVEL}")
# # Misc needed variables
set(LUA_BUILD_LIBRARY_DESCRIPTION "The base name of the library to build either the static or the dynamic library")
# Object file suffixes
if (MSVC)
set(LUA_BUILD_BUILD_DLL_DEFAULT ON)
set(LUA_BUILD_OBJECT_FILE_SUFFIX .obj)
else()
set(LUA_BUILD_BUILD_DLL_DEFAULT OFF)
set(LUA_BUILD_OBJECT_FILE_SUFFIX .o)
endif()
# # # Options
option(BUILD_LUA_AS_DLL ${LUA_BUILD_BUILD_DLL_DEFAULT} "Build Lua or LuaJIT as a Shared/Dynamic Link Library")
STRING(TOLOWER ${LUA_BUILD_LIBNAME} LUA_BUILD_NORMALIZED_LIBNAME)
if (NOT LUA_LIBRARY_NAME)
if (LUA_BUILD_NORMALIZED_LIBNAME MATCHES "luajit")
set(LUA_LIBRARY luajit)
else()
set(LUA_LIBRARY ${LUA_BUILD_LIBNAME})
endif()
else()
set(LUA_LIBRARY_NAME ${LUA_LIBRARY_NAME}
CACHE STRING
${LUA_BUILD_LIBRARY_DESCRIPTION})
endif()
# # Dependent Variables
# If we're building a DLL, then set the library type to SHARED
if (BUILD_LUA_AS_DLL)
set(LUA_BUILD_LIBRARY_TYPE SHARED)
else()
set(LUA_BUILD_LIBRARY_TYPE STATIC)
endif()
# # # Build Lua
# # Select either LuaJIT or Vanilla Lua here, based on what we discover
if (BUILD_LUAJIT OR LUA_BUILD_NORMALIZED_LUA_VERSION MATCHES "luajit")
include(${CMAKE_CURRENT_LIST_DIR}/FindLuaBuild/LuaJIT.cmake)
set(LUA_VERSION_STRING ${LUA_JIT_VERSION})
else()
include(${CMAKE_CURRENT_LIST_DIR}/FindLuaBuild/LuaVanilla.cmake)
set(LUA_VERSION_STRING ${LUA_VANILLA_VERSION})
endif()
# # Export variables to the parent scope
set(LUA_LIBRARIES ${LUA_LIBRARIES} PARENT_SCOPE)
set(LUA_INTERPRETER ${LUA_INTERPRETER} PARENT_SCOPE)
set(LUA_INCLUDE_DIRS ${LUA_INCLUDE_DIRS} PARENT_SCOPE)
set(LUA_VERSION_STRING ${LUA_VERSION_STRING} PARENT_SCOPE)
set(LUABUILD_FOUND TRUE PARENT_SCOPE)
endfunction(find_lua_build)
# Call and then immediately undefine to avoid polluting the global scope
if (LuaBuild_FIND_COMPONENTS)
list(GET LuaBuild_FIND_COMPONENTS 0 LUA_VERSION)
endif()
if (LuaBuild_FIND_VERSION)
if (LUA_VERSION)
set(LUA_VERSION "${LUA_VERSION}-${LuaBuild_FIND_VERSION}")
else()
set(LUA_VERSION "${LuaBuild_VERSION}")
endif()
endif()
if (NOT LUA_VERSION)
set(LUA_VERSION 5.4.4)
endif()
find_lua_build(${LUA_VERSION})
unset(find_lua_build)
# handle the QUIETLY and REQUIRED arguments and set LUABUILD_FOUND to TRUE if
# all listed variables are TRUE
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LuaBuild
FOUND_VAR LUABUILD_FOUND
REQUIRED_VARS LUA_LIBRARIES LUA_INCLUDE_DIRS
VERSION_VAR LUA_VERSION_STRING)
-441
View File
@@ -1,441 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# protect from multiple inclusion
if(lua_jit_build_included)
return()
endif(lua_jit_build_included)
set(lua_jit_build_included true)
# import necessary standard modules
include(ExternalProject)
# Latest iterations for specific sub-versions of LuaJIT
set(LUA_JIT_2.0_LATEST_VERSION 2.0.5)
set(LUA_JIT_${LUA_JIT_2.0_LATEST_VERSION}_COMMIT c88602f080dcafea6ba222a2f7cc1ea0e41ef3cc)
set(LUA_JIT_2.1_LATEST_VERSION 2.1.0-beta3)
set(LUA_JIT_${LUA_JIT_2.1_LATEST_VERSION}_COMMIT 80aaaeee99d7f7b06c9e75ed3a457c49d86fc4db)
# MD5 hashes taken off of LuaJIT's website
# must be updated whenever a new version appears
set(LUA_JIT_MD5_2.1.0-beta3.tar.gz eae40bc29d06ee5e3078f9444fcea39b)
set(LUA_JIT_MD5_2.1.0-beta3.zip 58d0480e1af0811e7ecee45498d62e2d)
set(LUA_JIT_MD5_2.1.0-beta2.tar.gz fa14598d0d775a7ffefb138a606e0d7b)
set(LUA_JIT_MD5_2.1.0-beta2.zip b5d943c0174ca217736e2ddc2d9721c3)
set(LUA_JIT_MD5_2.1.0-beta1.tar.gz 5a5bf71666e77cf6e7a1ae851127b834)
set(LUA_JIT_MD5_2.1.0-beta1.zip 4b5c2c9aef0e7c0b622b09e7c84d566b)
set(LUA_JIT_MD5_2.0.5.tar.gz 48353202cbcacab84ee41a5a70ea0a2c)
set(LUA_JIT_MD5_2.0.5.zip f7cf52a049d74aee4e624bdc1160b80d)
set(LUA_JIT_MD5_2.0.4.tar.gz dd9c38307f2223a504cbfb96e477eca0)
set(LUA_JIT_MD5_2.0.4.zip ed1f0caf3d390171f423f6f1b5c57aac)
set(LUA_JIT_MD5_2.0.3.tar.gz f14e9104be513913810cd59c8c658dc0)
set(LUA_JIT_MD5_2.0.3.zip 6c0f6958d5e1f67734fb1ff514ec4c84)
set(LUA_JIT_MD5_2.0.2.tar.gz 112dfb82548b03377fbefbba2e0e3a5b)
set(LUA_JIT_MD5_2.0.2.zip a57c7d1b8eaf46559303dcfd56404045)
set(LUA_JIT_MD5_2.0.1.tar.gz 85e406e8829602988eb1233a82e29f1f)
set(LUA_JIT_MD5_2.0.1.zip cf4aee0e40b220054ee3cffbe0cd6ed5)
set(LUA_JIT_MD5_2.0.0.tar.gz 97a2b87cc0490784f54b64cfb3b8f5ad)
set(LUA_JIT_MD5_2.0.0.zip 467f4f531f7e08ee252f5030ecada7ed)
set(LUA_JIT_MD5_2.0.0-beta11.tar.gz 824aa2684a11e3cc3abe87350a7b6139)
set(LUA_JIT_MD5_2.0.0-beta11.zip 8629401437048e477c94bd791b0a823a)
set(LUA_JIT_MD5_2.0.0-beta10.tar.gz ed66689b96f7ad7bfeffe0b4ff2d63d4)
set(LUA_JIT_MD5_2.0.0-beta10.zip f6bbd472726b761b29438c4a06b5ab3c)
set(LUA_JIT_MD5_2.0.0-beta9.tar.gz e7e03e67e2550817358bc28b44270c6d)
set(LUA_JIT_MD5_2.0.0-beta9.zip 3f9ca0309f26e789c6c3246c83696f84)
set(LUA_JIT_MD5_2.0.0-beta8.tar.gz f0748a73ae268d49b1d01f56c4fe3e61)
set(LUA_JIT_MD5_2.0.0-beta8.zip fb096a90c9e799c8922f32095ef3d93c)
set(LUA_JIT_MD5_2.0.0-beta7.tar.gz b845dec15dd9eba2fd17d865601a52e5)
set(LUA_JIT_MD5_2.0.0-beta7.zip e10fc2b19de52d8770cdf24f1791dd77)
set(LUA_JIT_MD5_2.0.0-beta6.tar.gz bfcbe2a11162cfa84d5a1693b442c8bf)
set(LUA_JIT_MD5_2.0.0-beta6.zip f64945c5ecaf3ea71a829fdbb5cb196c)
set(LUA_JIT_MD5_2.0.0-beta5.tar.gz 7e0dfa03a140148149a1021d4ffd5c57)
set(LUA_JIT_MD5_2.0.0-beta5.zip be8087fcb576c30ffbb6368ebc284498)
set(LUA_JIT_MD5_2.0.0-beta4.tar.gz 5c5a9305b3e06765e1dae138e1a95c3a)
set(LUA_JIT_MD5_2.0.0-beta4.zip d0b241be6207fa7d97b6afc41368e05f)
set(LUA_JIT_MD5_2.0.0-beta3.tar.gz 313b6f164e93e1bbac7bf87abb58d4a1)
set(LUA_JIT_MD5_2.0.0-beta3.zip bea9c7bcd5084f98830e31956f276ff6)
set(LUA_JIT_MD5_2.0.0-beta2.tar.gz 2ebcc38fa1d9756dc2e341f191701120)
set(LUA_JIT_MD5_2.0.0-beta2.zip 94086f99f647d46a8360adeb11851d66)
set(LUA_JIT_MD5_2.0.0-beta1.tar.gz 9ed7646d03580a1cec4abeb74ca44843)
set(LUA_JIT_MD5_2.0.0-beta1.zip 19d5bac616fa739343c7158d9d99a3f3)
set(LUA_JIT_MD5_1.1.8.tar.gz ad0e319483fa235e3979537a748631e9)
set(LUA_JIT_MD5_1.1.8.zip 92870c80f504c34c9b7547cd6c5562d0)
set(LUA_JIT_MD5_1.1.7.tar.gz 3aed0795f7c8725d3613269cd56f8e5a)
set(LUA_JIT_MD5_1.1.7.zip 40a8dbc214306bb4b9849fcf026c4ee0)
set(LUA_JIT_MD5_1.1.6.tar.gz 1a1320e09d0cd5b793014556fb7d64c9)
set(LUA_JIT_MD5_1.1.6.zip 350d7b9230637056fbd6158b95e8fa11)
set(LUA_JIT_MD5_1.1.5.tar.gz b99d244ba4fc1979946ae1025368fc5c)
set(LUA_JIT_MD5_1.1.5.zip d3ffbae3bfcd5914b02dc00b1118a59d)
set(LUA_JIT_MD5_1.1.4.tar.gz 9fe29cfb8126bc9c4302701c06965f1c)
set(LUA_JIT_MD5_1.1.4.zip 30d318e3287000ecf4c93b29e8783183)
set(LUA_JIT_MD5_1.1.3.tar.gz f5db1a147ed3d34677ad1ef310c56da7)
set(LUA_JIT_MD5_1.1.3.zip 5949e7bce9d97c37c282e1cbe85aa378)
set(LUA_JIT_MD5_1.1.2.tar.gz 4ae25ce7e3f301d1fcf0b713016edab0)
set(LUA_JIT_MD5_1.1.0.tar.gz 16d880a98a1ff6608ac1039c802233db)
set(LUA_JIT_MD5_1.0.3.tar.gz d0a63d5394cca549889bd820a05b32d2)
# Clean up some variables
string(TOLOWER ${LUA_VERSION} LUA_JIT_NORMALIZED_LUA_VERSION)
if (LUA_JIT_NORMALIZED_LUA_VERSION MATCHES "([0-9]+\\.[0-9]+\\.[0-9]+(-[A-Za-z0-9_-]+)?)")
# 3-digit with optional beta1/beta2/beta3 (or whatever): probably okay?
set(LUA_JIT_VERSION ${CMAKE_MATCH_1})
elseif (LUA_JIT_NORMALIZED_LUA_VERSION MATCHES "([0-9]+\\.[0-9]+)")
# extend version number with prefix
if (${CMAKE_MATCH_1} EQUAL 2)
if (${CMAKE_MATCH_2} EQUAL 0)
set(LUA_JIT_VERSION ${LUA_JIT_2.0_LATEST_VERSION})
elseif (${CMAKE_MATCH_2} EQUAL 1)
set(LUA_JIT_VERSION ${LUA_JIT_2.1_LATEST_VERSION})
endif()
endif()
if (NOT LUA_JIT_VERSION)
# Just pick a default version and roll with it
set(LUA_JIT_VERSION ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.0)
endif()
elseif (LUA_JIT_NORMALIZED_LUA_VERSION MATCHES "latest")
set(LUA_JIT_VERSION ${LUA_JIT_2.1_LATEST_VERSION})
else()
MESSAGE(FATAL "Cannot deduce LuaJIT version from ${LUA_VERSION}")
endif()
FIND_PACKAGE_MESSAGE(LUABUILD
"Selecting LuaJIT ${LUA_JIT_VERSION} from '${LUA_VERSION}' and building a ${LUA_BUILD_LIBRARY_TYPE} library..."
"[${LUA_JIT_VERSION}][${LUA_VERSION}][${LUA_BUILD_LIBRARY_TYPE}]")
# Get hashes for the build
# LuaJIT unfortunately does not give us SHA1 hashes as well
# set(LUA_JIT_SHA1 ${LUA_JIT_SHA1_${LUA_JIT_VERSION}})
if (WIN32)
set(LUA_JIT_MD5 ${LUA_JIT_MD5_${LUA_JIT_VERSION}.zip})
set(LUA_JIT_DOWNLOAD_URI http://luajit.org/download/LuaJIT-${LUA_JIT_VERSION}.zip)
else()
set(LUA_JIT_MD5 ${LUA_JIT_MD5_${LUA_JIT_VERSION}.tar.gz})
set(LUA_JIT_DOWNLOAD_URI http://luajit.org/download/LuaJIT-${LUA_JIT_VERSION}.tar.gz)
endif()
if (LUA_JIT_MD5)
set(LUA_JIT_DOWNLOAD_MD5_COMMAND URL_MD5 ${LUA_JIT_MD5})
else ()
set(LUA_JIT_DOWNLOAD_MD5_COMMAND "")
endif()
if (LUA_JIT_SHA1)
set(LUA_JIT_DOWNLOAD_SHA1_COMMAND URL_HASH SHA1=${LUA_JIT_SHA1})
else ()
set(LUA_JIT_DOWNLOAD_SHA1_COMMAND "")
endif()
set(LUA_JIT_SOURCE_DIR "${LUA_BUILD_TOPLEVEL}/src")
set(LUA_JIT_INSTALL_DIR "${LUA_BUILD_TOPLEVEL}/install")
set(LUA_JIT_INCLUDE_DIRS "${LUA_JIT_SOURCE_DIR}")
file(MAKE_DIRECTORY ${LUA_JIT_SOURCE_DIR})
file(MAKE_DIRECTORY ${LUA_JIT_INSTALL_DIR})
set(LUA_JIT_LIB_FILENAME "${CMAKE_STATIC_LIBRARY_PREFIX}${LUA_BUILD_LIBNAME}${CMAKE_STATIC_LIBRARY_SUFFIX}")
set(LUA_JIT_IMP_LIB_FILENAME "${CMAKE_IMPORT_LIBRARY_PREFIX}${LUA_BUILD_LIBNAME}${CMAKE_IMPORT_LIBRARY_SUFFIX}")
set(LUA_JIT_LIB_EXP_FILENAME "${LUA_BUILD_LIBNAME}.exp")
set(LUA_JIT_DLL_FILENAME "${CMAKE_SHARED_LIBRARY_PREFIX}${LUA_BUILD_LIBNAME}${CMAKE_SHARED_LIBRARY_SUFFIX}")
set(LUA_JIT_EXE_FILENAME "${LUA_BUILD_LIBNAME}${CMAKE_EXECUTABLE_SUFFIX}")
set(LUA_JIT_LIB_FILE "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/${LUA_JIT_LIB_FILENAME}")
set(LUA_JIT_IMP_LIB_FILE "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/${LUA_JIT_IMP_LIB_FILENAME}")
set(LUA_JIT_LIB_EXP_FILE "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/${LUA_JIT_LIB_EXP_FILENAME}")
set(LUA_JIT_DLL_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${LUA_JIT_DLL_FILENAME}")
set(LUA_JIT_EXE_FILE "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/${LUA_JIT_EXE_FILENAME}")
# # # Do the build
if (MSVC)
# Visual C++ is predicated off running msvcbuild.bat
# which requires a Visual Studio Command Prompt
# make sure to find the right one
find_file(VCVARS_ALL_BAT NAMES vcvarsall.bat
HINTS "C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary/Build"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC/Auxiliary"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Community/VC"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Auxiliary/Build"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC/Auxiliary"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Professional/VC"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/VC/Auxiliary/Build"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/VC/Auxiliary"
"C:/Program Files (x86)/Microsoft Visual Studio/2017/Enterprise/VC"
"C:/Program Files/Microsoft Visual Studio/2017/Community/VC/Auxiliary/Build"
"C:/Program Files/Microsoft Visual Studio/2017/Community/VC/Auxiliary"
"C:/Program Files/Microsoft Visual Studio/2017/Community/VC"
"C:/Program Files/Microsoft Visual Studio/2017/Professional/VC/Auxiliary/Build"
"C:/Program Files/Microsoft Visual Studio/2017/Professional/VC/Auxiliary"
"C:/Program Files/Microsoft Visual Studio/2017/Professional/VC"
"C:/Program Files/Microsoft Visual Studio/2017/Enterprise/VC/Auxiliary/Build"
"C:/Program Files/Microsoft Visual Studio/2017/Enterprise/VC/Auxiliary"
"C:/Program Files/Microsoft Visual Studio/2017/Enterprise/VC"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Auxiliary/Build"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC/Auxiliary"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Community/VC"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Auxiliary/Build"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC/Auxiliary"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Professional/VC"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary"
"C:/Program Files (x86)/Microsoft Visual Studio/2019/Enterprise/VC"
"C:/Program Files/Microsoft Visual Studio/2019/Community/VC/Auxiliary/Build"
"C:/Program Files/Microsoft Visual Studio/2019/Community/VC/Auxiliary"
"C:/Program Files/Microsoft Visual Studio/2019/Community/VC"
"C:/Program Files/Microsoft Visual Studio/2019/Professional/VC/Auxiliary/Build"
"C:/Program Files/Microsoft Visual Studio/2019/Professional/VC/Auxiliary"
"C:/Program Files/Microsoft Visual Studio/2019/Professional/VC"
"C:/Program Files/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary/Build"
"C:/Program Files/Microsoft Visual Studio/2019/Enterprise/VC/Auxiliary"
"C:/Program Files/Microsoft Visual Studio/2019/Enterprise/VC")
if (VCVARS_ALL_BAT MATCHES "VCVARS_ALL_BAT-NOTFOUND")
MESSAGE(FATAL_ERROR "Cannot find 'vcvarsall.bat' file or similar needed to build LuaJIT ${LUA_VERSION} on Windows")
endif()
if (CMAKE_SIZEOF_VOID_P LESS_EQUAL 4)
set(LUA_JIT_MAKE_COMMAND "${VCVARS_ALL_BAT}" x86)
else()
set(LUA_JIT_MAKE_COMMAND "${VCVARS_ALL_BAT}" x64)
endif()
set(LUA_JIT_MAKE_COMMAND ${LUA_JIT_MAKE_COMMAND} && cd src && msvcbuild.bat)
if (CMAKE_BUILD_TYPE MATCHES "Debug")
set(LUA_JIT_MAKE_COMMAND ${LUA_JIT_MAKE_COMMAND} debug)
endif()
if (NOT BUILD_LUA_AS_DLL)
set(LUA_JIT_MAKE_COMMAND ${LUA_JIT_MAKE_COMMAND} static)
endif()
set(LUA_JIT_PREBUILT_LIB "lua51.lib")
set(LUA_JIT_PREBUILT_IMP_LIB "lua51.lib")
set(LUA_JIT_PREBUILT_DLL "lua51.dll")
set(LUA_JIT_PREBUILT_EXP "lua51.exp")
set(LUA_JIT_PREBUILT_EXE "luajit.exe")
else ()
# get the make command we need for this system
find_program(MAKE_PROGRAM NAMES make mingw32-make mingw64-make)
if (MAKE_PROGRAM MATCHES "MAKE_PROGRAM-NOTFOUND")
MESSAGE(FATAL_ERROR "Cannot find 'make' program or similar needed to build LuaJIT ${LUA_VERSION} (perhaps place it in the PATH environment variable if it is not already?)")
endif()
# we can simply reuse the makefile here
# so define it as an external project and then just have the proper
# build/install/test commands
# make sure to apply -pagezero_size 10000 -image_base 100000000 (done later for XCode Targets)
set(LUA_JIT_MAKE_BUILD_MODIFICATIONS "LUAJIT_T=${LUA_JIT_EXE_FILENAME}")
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "LUAJIT_A=${LUA_JIT_LIB_FILENAME}")
set(LUA_JIT_MAKE_CFLAGS_MODIFICATIONS "")
set(LUA_JIT_MAKE_HOST_CFLAGS_MODIFICATIONS "")
set(LUA_JIT_MAKE_TARGET_CFLAGS_MODIFICATIONS "-fPIC")
if (BUILD_LUA_AS_DLL)
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "LUAJIT_SO=${LUA_JIT_DLL_FILENAME}" "TARGET_SONAME=${LUA_JIT_DLL_FILENAME}" "TARGET_DYLIBNAME=${LUA_JIT_DLL_FILENAME}" "TARGET_DLLNAME=${LUA_JIT_DLL_FILENAME}")
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "BUILDMODE=dynamic")
else()
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "BUILDMODE=static")
endif()
if (IS_X86)
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "CC=${CMAKE_C_COMPILER} -m32")
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "LDFLAGS=-m32")
#set(LUA_JIT_MAKE_CFLAGS_MODIFICATIONS "${LUA_JIT_MAKE_CFLAGS_MODIFICATIONS} -m32")
#set(LUA_JIT_MAKE_HOST_CFLAGS_MODIFICATIONS "${LUA_JIT_MAKE_HOST_CFLAGS_MODIFICATIONS} -m32")
#set(LUA_JIT_MAKE_TARGET_CFLAGS_MODIFICATIONS "${LUA_JIT_MAKE_TARGET_CFLAGS_MODIFICATIONS} -m32")
endif()
set(LUA_JIT_PREBUILT_DLL ${LUA_JIT_DLL_FILENAME})
set(LUA_JIT_PREBUILT_LIB ${LUA_JIT_LIB_FILENAME})
set(LUA_JIT_PREBUILT_IMP_LIB ${LUA_JIT_IMP_LIB_FILENAME})
set(LUA_JIT_PREBUILT_EXE ${LUA_JIT_EXE_FILENAME})
set(LUA_JIT_PREBUILT_EXP ${LUA_JIT_LIB_EXP_FILENAME})
if (WIN32)
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "HOST_SYS=Windows" "TARGET_SYS=Windows" "TARGET_AR=ar rcus")
endif()
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "CFLAGS=${LUA_JIT_MAKE_CFLAGS_MODIFICATIONS}")
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "TARGET_CFLAGS=${LUA_JIT_MAKE_TARGET_CFLAGS_MODIFICATIONS}")
list(APPEND LUA_JIT_MAKE_BUILD_MODIFICATIONS "HOST_CFLAGS=${LUA_JIT_MAKE_HOST_CFLAGS_MODIFICATIONS}")
set(LUA_JIT_MAKE_COMMAND "${MAKE_PROGRAM}" ${LUA_JIT_MAKE_BUILD_MODIFICATIONS})
endif()
set(LUA_JIT_BUILD_COMMAND BUILD_COMMAND ${LUA_JIT_MAKE_COMMAND})
set(lualib luajit_lib_${LUA_JIT_VERSION})
set(luainterpreter luajit_${LUA_JIT_VERSION})
file(TO_CMAKE_PATH "${LUA_JIT_SOURCE_DIR}/${LUA_JIT_PREBUILT_LIB}" LUA_JIT_SOURCE_LUA_LIB)
file(TO_CMAKE_PATH "${LUA_JIT_SOURCE_DIR}/${LUA_JIT_PREBUILT_IMP_LIB}" LUA_JIT_SOURCE_LUA_IMP_LIB)
file(TO_CMAKE_PATH "${LUA_JIT_SOURCE_DIR}/${LUA_JIT_PREBUILT_EXE}" LUA_JIT_SOURCE_LUA_INTERPRETER)
file(TO_CMAKE_PATH "${LUA_JIT_SOURCE_DIR}/${LUA_JIT_PREBUILT_DLL}" LUA_JIT_SOURCE_LUA_DLL)
file(TO_CMAKE_PATH "${LUA_JIT_SOURCE_DIR}/${LUA_JIT_PREBUILT_EXP}" LUA_JIT_SOURCE_LUA_LIB_EXP)
file(TO_CMAKE_PATH "${LUA_JIT_DLL_FILE}" LUA_JIT_DESTINATION_LUA_DLL)
file(TO_CMAKE_PATH "${CMAKE_ARCHIVE_OUTPUT_DIRECTORY}/${LUA_JIT_LIB_EXP_FILENAME}" LUA_JIT_DESTINATION_LUA_LIB_EXP)
file(TO_CMAKE_PATH "${LUA_JIT_IMP_LIB_FILE}" LUA_JIT_DESTINATION_LUA_IMP_LIB)
file(TO_CMAKE_PATH "${LUA_JIT_LIB_FILE}" LUA_JIT_DESTINATION_LUA_LIB)
file(TO_CMAKE_PATH "${LUA_JIT_EXE_FILE}" LUA_JIT_DESTINATION_LUA_INTERPRETER)
if (WIN32 AND NOT MSVC)
string(COMPARE EQUAL ${LUA_JIT_VERSION} ${LUA_JIT_2.0_LATEST_VERSION} lua_jit_same_version_20)
string(COMPARE EQUAL ${LUA_JIT_VERSION} ${LUA_JIT_2.1_LATEST_VERSION} lua_jit_same_version_21)
if (lua_jit_same_version_20 OR lua_jit_same_version_21)
#set (LUA_JIT_GIT_COMMIT ${LUA_JIT_${LUA_JIT_VERSION}_COMMIT})
#set(LUA_JIT_GIT_TAG GIT_TAG ${LUA_JIT_GIT_COMMIT})
endif()
elseif(LUA_JIT_NORMALIZED_LUA_VERSION MATCHES "latest")
set(LUA_JIT_PULL_LATEST TRUE)
endif()
set(LUA_JIT_BYPRODUCTS "${LUA_JIT_SOURCE_LUA_DLL}" "${LUA_JIT_SOURCE_LUA_INTERPRETER}")
set(LUA_JIT_INSTALL_BYPRODUCTS "${LUA_JIT_DESTINATION_LUA_DLL}" "${LUA_JIT_DESTINATION_LUA_INTERPRETER}")
if (BUILD_LUA_AS_DLL AND MSVC)
set(LUA_JIT_BYPRODUCTS ${LUA_JIT_BYPRODUCTS} "${LUA_JIT_SOURCE_LUA_LIB_EXP}")
set(LUA_JIT_INSTALL_BYPRODUCTS ${LUA_JIT_INSTALL_BYPRODUCTS} "${LUA_JIT_DESTINATION_LUA_LIB_EXP}")
endif()
if (CMAKE_IMPORT_LIBRARY_SUFFIX AND BUILD_LUA_AS_DLL)
set(LUA_JIT_BYPRODUCTS ${LUA_JIT_BYPRODUCTS} "${LUA_JIT_SOURCE_LUA_IMP_LIB}")
set(LUA_JIT_INSTALL_BYPRODUCTS "${LUA_JIT_INSTALL_BYPRODUCTS}" "${LUA_JIT_DESTINATION_LUA_IMP_LIB}")
else()
set(LUA_JIT_BYPRODUCTS ${LUA_JIT_BYPRODUCTS} "${LUA_JIT_SOURCE_LUA_LIB}")
set(LUA_JIT_INSTALL_BYPRODUCTS ${LUA_JIT_INSTALL_BYPRODUCTS} "${LUA_JIT_DESTINATION_LUA_LIB}")
endif()
# # Post-Build moving steps for necessary items
# Add post-step to move library afterwards
set(LUA_JIT_POSTBUILD_COMMENTS "Executable - Moving \"${LUA_JIT_SOURCE_LUA_INTERPRETER}\" to \"${LUA_JIT_DESTINATION_LUA_INTERPRETER}\"...")
set(LUA_JIT_POSTBUILD_COMMANDS COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${LUA_JIT_SOURCE_LUA_INTERPRETER}" "${LUA_JIT_DESTINATION_LUA_INTERPRETER}")
if (BUILD_LUA_AS_DLL)
if (MSVC)
set(LUA_JIT_POSTBUILD_COMMENTS "${LUA_JIT_POSTBUILD_COMMENTS} Import Library - Moving \"${LUA_JIT_SOURCE_LUA_IMP_LIB}\" to \"${LUA_JIT_DESTINATION_LUA_IMP_LIB}\"...")
set(LUA_JIT_POSTBUILD_COMMANDS ${LUA_JIT_POSTBUILD_COMMANDS} COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${LUA_JIT_SOURCE_LUA_IMP_LIB}" "${LUA_JIT_DESTINATION_LUA_IMP_LIB}")
set(LUA_JIT_POSTBUILD_COMMENTS "${LUA_JIT_POSTBUILD_COMMENTS} Library - Moving \"${LUA_JIT_SOURCE_LUA_LIB_EXP}\" to \"${LUA_JIT_DESTINATION_LUA_LIB_EXP}\"...")
set(LUA_JIT_POSTBUILD_COMMANDS ${LUA_JIT_POSTBUILD_COMMANDS} && "${CMAKE_COMMAND}" -E copy_if_different "${LUA_JIT_SOURCE_LUA_LIB_EXP}" "${LUA_JIT_DESTINATION_LUA_LIB_EXP}")
endif()
set(LUA_JIT_POSTBUILD_COMMENTS "${LUA_JIT_POSTBUILD_COMMENTS} Dynamic Library - Moving \"${LUA_JIT_SOURCE_LUA_DLL}\" to \"${LUA_JIT_DESTINATION_LUA_DLL}\"...")
set(LUA_JIT_POSTBUILD_COMMANDS ${LUA_JIT_POSTBUILD_COMMANDS} COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${LUA_JIT_SOURCE_LUA_DLL}" "${LUA_JIT_DESTINATION_LUA_DLL}")
else()
set(LUA_JIT_POSTBUILD_COMMENTS "${LUA_JIT_POSTBUILD_COMMENTS} Library - Moving \"${LUA_JIT_SOURCE_LUA_LIB}\" to \"${LUA_JIT_DESTINATION_LUA_LIB}\"...")
set(LUA_JIT_POSTBUILD_COMMANDS ${LUA_JIT_POSTBUILD_COMMANDS} COMMAND "${CMAKE_COMMAND}" -E copy_if_different "${LUA_JIT_SOURCE_LUA_LIB}" "${LUA_JIT_DESTINATION_LUA_LIB}")
endif()
if (LUA_LOCAL_DIR)
file(COPY "${LUA_LOCAL_DIR}/"
DESTINATION "${LUA_BUILD_TOPLEVEL}"
FILES_MATCHING REGEX ".*"
)
add_custom_command(OUTPUT ${LUA_JIT_BYPRODUCTS}
COMMAND ${LUA_JIT_MAKE_COMMAND}
WORKING_DIRECTORY "${LUA_BUILD_TOPLEVEL}"
DEPENDS "${LUA_BUILD_TOPLEVEL}/Makefile" "${LUA_BUILD_TOPLEVEL}/src/msvcbuild.bat"
COMMENT "Building LuaJIT ${LUA_JIT_VERSION}..."
)
add_custom_target(LUA_JIT-move
${LUA_JIT_POSTBUILD_COMMANDS}
COMMENT ${LUA_JIT_POSTBUILD_COMMENTS}
BYPRODUCTS ${LUA_JIT_INSTALL_BYPRODUCTS}
DEPENDS ${LUA_JIT_BYPRODUCTS}
)
elseif (LUA_JIT_GIT_COMMIT OR LUA_JIT_PULL_LATEST)
if (LUA_JIT_PULL_LATEST)
MESSAGE(STATUS "Latest LuaJIT has been requested: pulling from git...")
elseif (LUA_JIT_GIT_COMMIT)
MESSAGE(STATUS "LuaJIT '${LUA_VERSION}' requested has broken static library builds: using git '${LUA_JIT_GIT_COMMIT}'...")
endif()
ExternalProject_Add(LUA_JIT
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS FALSE
PREFIX "${LUA_BUILD_TOPLEVEL}"
SOURCE_DIR "${LUA_BUILD_TOPLEVEL}"
DOWNLOAD_DIR "${LUA_BUILD_TOPLEVEL}"
TMP_DIR "${LUA_BUILD_TOPLEVEL}-tmp"
STAMP_DIR "${LUA_BUILD_TOPLEVEL}-stamp"
INSTALL_DIR "${LUA_BUILD_INSTALL_DIR}"
GIT_REPOSITORY https://github.com/LuaJIT/LuaJIT.git
GIT_REMOTE_NAME origin
${LUA_JIT_GIT_TAG}
GIT_SHALLOW TRUE
CONFIGURE_COMMAND ""
${LUA_JIT_BUILD_COMMAND}
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS ${LUA_JIT_BYPRODUCTS})
else()
ExternalProject_Add(LUA_JIT
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS TRUE
# LuaJIT does not offer a TLS/SSL port
TLS_VERIFY FALSE
PREFIX "${LUA_BUILD_TOPLEVEL}"
SOURCE_DIR "${LUA_BUILD_TOPLEVEL}"
DOWNLOAD_DIR "${LUA_BUILD_TOPLEVEL}"
TMP_DIR "${LUA_BUILD_TOPLEVEL}-tmp"
STAMP_DIR "${LUA_BUILD_TOPLEVEL}-stamp"
INSTALL_DIR "${LUA_BUILD_INSTALL_DIR}"
URL "${LUA_JIT_DOWNLOAD_URI}"
${LUA_JIT_DOWNLOAD_MD5_COMMAND}
${LUA_JIT_DOWNLOAD_SHA1_COMMAND}
CONFIGURE_COMMAND ""
${LUA_JIT_BUILD_COMMAND}
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS ${LUA_JIT_BYPRODUCTS})
endif()
if (NOT LUA_LOCAL_DIR)
ExternalProject_Add_Step(LUA_JIT move
ALWAYS TRUE
${LUA_JIT_POSTBUILD_COMMANDS}
WORKING_DIRECTORY "${CMAKE_CURRENT_BINARY_DIR}"
COMMENT ${LUA_JIT_POSTBUILD_COMMENTS}
DEPENDEES build
DEPENDS ${LUA_JIT_BYPRODUCTS}
BYPRODUCTS ${LUA_JIT_INSTALL_BYPRODUCTS})
ExternalProject_Add_StepTargets(LUA_JIT move)
endif()
# # Lua Library
add_library(${lualib} INTERFACE)
add_dependencies(${lualib} LUA_JIT-move)
target_include_directories(${lualib}
INTERFACE "${LUA_JIT_SOURCE_DIR}")
target_link_libraries(${lualib}
INTERFACE ${CMAKE_DL_LIBS})
if (BUILD_LUA_AS_DLL)
if (MSVC)
target_link_libraries(${lualib}
INTERFACE "${LUA_JIT_DESTINATION_LUA_LIB}")
else()
target_link_libraries(${lualib}
INTERFACE "${LUA_JIT_DESTINATION_LUA_DLL}")
endif()
else()
target_link_libraries(${lualib}
INTERFACE "${LUA_JIT_DESTINATION_LUA_LIB}")
endif()
if (XCODE)
target_compile_options(${lualib}
INTERFACE -pagezero_size 10000 -image_base 100000000)
endif ()
# # set externally-visible target indicator
set(LUA_LIBRARIES ${lualib})
set(LUA_INTERPRETER "")
set(LUA_INCLUDE_DIRS "${LUA_JIT_INCLUDE_DIRS}")
-356
View File
@@ -1,356 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# Include guard
if(_lua_vanilla_build_included)
return()
endif(_lua_vanilla_build_included)
set(_lua_vanilla_build_included true)
# import necessary standard modules
include(ExternalProject)
# import other modules
include(Common/Core)
# Latest versions for specific sub-versions of Lua
set(LUA_VANILLA_5.1_LATEST_VERSION 5.1.5)
set(LUA_VANILLA_5.2_LATEST_VERSION 5.2.4)
set(LUA_VANILLA_5.3_LATEST_VERSION 5.3.6)
set(LUA_VANILLA_5.4_LATEST_VERSION 5.4.4)
# Clean up some variables
if (LUA_VERSION MATCHES "^([0-9]+)\\.([0-9]+)\\.([0-9]+)$")
# probably okay!
set(LUA_VANILLA_VERSION ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.${CMAKE_MATCH_3})
elseif (LUA_VERSION MATCHES "([0-9]+)\\.([0-9]+)")
# extend version number with prefix
if (${CMAKE_MATCH_1} EQUAL 5)
if (${CMAKE_MATCH_2} EQUAL 1)
set(LUA_VANILLA_VERSION ${LUA_VANILLA_5.1_LATEST_VERSION})
elseif (${CMAKE_MATCH_2} EQUAL 2)
set(LUA_VANILLA_VERSION ${LUA_VANILLA_5.2_LATEST_VERSION})
elseif (${CMAKE_MATCH_2} EQUAL 3)
set(LUA_VANILLA_VERSION ${LUA_VANILLA_5.3_LATEST_VERSION})
elseif (${CMAKE_MATCH_2} EQUAL 4)
set(LUA_VANILLA_VERSION ${LUA_VANILLA_5.4_LATEST_VERSION})
else()
# default to whatever the first two
# numbers happen to be, plus build 0
set(LUA_VANILLA_VERSION ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.0)
endif()
endif()
if(NOT LUA_VANILLA_VERSION)
# default to whatever the first two
# numbers happen to be, plus build 0
set(LUA_VANILLA_VERSION ${CMAKE_MATCH_1}.${CMAKE_MATCH_2}.0)
endif()
else()
message(FATAL_ERROR "Cannot deduce the proper Lua version from ${LUA_VERSION}")
endif()
if (BUILD_LUA_AS_CXX)
set(LUA_VANILLA_LANGUAGE CXX)
set(LUA_VANILLA_LANGUAGE_STANDARD 98)
else()
set(LUA_VANILLA_LANGUAGE C)
set(LUA_VANILLA_LANGUAGE_STANDARD 99)
endif()
FIND_PACKAGE_MESSAGE(LUABUILD
"Selecting PUC-RIO Lua ${LUA_VANILLA_VERSION} from '${LUA_VERSION}' and building a ${LUA_BUILD_LIBRARY_TYPE} library with ${LUA_VANILLA_LANGUAGE} linkage..."
"[${LUA_VANILLA_VERSION}][${LUA_VERSION}][${LUA_BUILD_LIBRARY_TYPE}][${LUA_VANILLA_LANGUAGE}]")
# # # Makefile and self-build configurations
# # Potential compiler variables
if (MSVC)
if (BUILD_LUA_AS_DLL)
set(LUA_VANILLA_DLL_DEFINE LUA_BUILD_AS_DLL)
else()
set(LUA_VANILLA_DLL_DEFINE "")
endif()
else()
set(LUA_VANILLA_LUALIB_COMPILER_OPTIONS "")
set(LUA_VANILLA_DLL_DEFINE "")
endif()
# # Source files for natural build, if we have to go that far
# retrieve source files
set(LUA_VANILLA_DOWNLOAD_URL https://www.lua.org/ftp/lua-${LUA_VANILLA_VERSION}.tar.gz)
if (LUA_VANILLA_VERSION MATCHES "^5\\.1")
set(LUA_VANILLA_LIB_SOURCES lapi.c lcode.c ldebug.c ldo.c ldump.c lfunc.c
lgc.c llex.c lmem.c lobject.c lopcodes.c lparser.c lstate.c
lstring.c ltable.c ltm.c lundump.c lvm.c lzio.c lauxlib.c
lbaselib.c ldblib.c liolib.c lmathlib.c loslib.c ltablib.c
lstrlib.c loadlib.c linit.c)
set(LUA_VANILLA_LUA_SOURCES lua.c )
if (LUA_BUILD_LUA_COMPILER)
set(LUA_VANILLA_LUAC_SOURCES luac.c print.c )
endif()
set(LUA_VANILLA_GENERATE_LUA_HPP true)
elseif (LUA_VANILLA_VERSION MATCHES "^5\\.2")
set(LUA_VANILLA_LIB_SOURCES lapi.c lcode.c lctype.c ldebug.c ldo.c ldump.c
lfunc.c lgc.c llex.c lmem.c lobject.c lopcodes.c lparser.c
lstate.c lstring.c ltable.c ltm.c lundump.c lvm.c lzio.c
lauxlib.c lbaselib.c lbitlib.c lcorolib.c ldblib.c liolib.c
lmathlib.c loslib.c lstrlib.c ltablib.c loadlib.c linit.c)
set(LUA_VANILLA_LUA_SOURCES lua.c )
if (LUA_BUILD_LUA_COMPILER)
set(LUA_VANILLA_LUAC_SOURCES luac.c )
endif()
set(LUA_VANILLA_GENERATE_LUA_HPP false)
elseif (LUA_VANILLA_VERSION MATCHES "^5\\.3")
set(LUA_VANILLA_LIB_SOURCES lapi.c lcode.c lctype.c ldebug.c ldo.c ldump.c
lfunc.c lgc.c llex.c lmem.c lobject.c lopcodes.c lparser.c lstate.c
lstring.c ltable.c ltm.c lundump.c lvm.c lzio.c lauxlib.c
lbaselib.c lbitlib.c lcorolib.c ldblib.c liolib.c lmathlib.c
loslib.c lstrlib.c ltablib.c lutf8lib.c loadlib.c linit.c)
set(LUA_VANILLA_LUA_SOURCES lua.c )
if (LUA_BUILD_LUA_COMPILER)
set(LUA_VANILLA_LUAC_SOURCES luac.c )
endif()
set(LUA_VANILLA_GENERATE_LUA_HPP false)
elseif (LUA_VANILLA_VERSION MATCHES "^5\\.4")
if (LUA_VANILLA_VERSION MATCHES "work" OR LUA_VANILLA_VERSION MATCHES "alpha" OR LUA_VANILLA_VERSION MATCHES "beta")
set(LUA_VANILLA_DOWNLOAD_URL https://www.lua.org/work/lua-${LUA_VANILLA_VERSION}.tar.gz)
endif()
set(LUA_VANILLA_LIB_SOURCES lapi.c lauxlib.c lbaselib.c lcode.c lcorolib.c
lctype.c ldblib.c ldebug.c ldo.c ldump.c lfunc.c lgc.c linit.c liolib.c
llex.c lmathlib.c lmem.c loadlib.c lobject.c lopcodes.c loslib.c
lparser.c lstate.c lstring.c lstrlib.c ltable.c ltablib.c ltm.c lundump.c
lutf8lib.c lvm.c lzio.c)
set(LUA_VANILLA_LUA_SOURCES lua.c )
if (LUA_BUILD_LUA_COMPILER)
set(LUA_VANILLA_LUAC_SOURCES luac.c )
endif()
set(LUA_VANILLA_GENERATE_LUA_HPP false)
else()
MESSAGE(WARNING "Using Lua 5.4.1 file list for ${LUA_VERSION} version")
set(LUA_VANILLA_LIB_SOURCES lapi.c lauxlib.c lbaselib.c lcode.c lcorolib.c
lctype.c ldblib.c ldebug.c ldo.c ldump.c lfunc.c lgc.c linit.c liolib.c
llex.c lmathlib.c lmem.c loadlib.c lobject.c lopcodes.c loslib.c
lparser.c lstate.c lstring.c lstrlib.c ltable.c ltablib.c ltm.c lundump.c
lutf8lib.c lvm.c lzio.c)
set(LUA_VANILLA_LUA_SOURCES lua.c )
if (LUA_BUILD_LUA_COMPILER)
set(LUA_VANILLA_LUAC_SOURCES luac.c )
endif()
set(LUA_VANILLA_GENERATE_LUA_HPP false)
endif()
set(LUA_VANILLA_SOURCE_DIR "${LUA_BUILD_TOPLEVEL}/src")
prepend(LUA_VANILLA_LIB_SOURCES "${LUA_VANILLA_SOURCE_DIR}/" ${LUA_VANILLA_LIB_SOURCES})
prepend(LUA_VANILLA_LUA_SOURCES "${LUA_VANILLA_SOURCE_DIR}/" ${LUA_VANILLA_LUA_SOURCES})
# download, just for the sake of download + extract
# or pull from local folder
if (LUA_LOCAL_DIR)
file(COPY "${LUA_LOCAL_DIR}/src"
DESTINATION "${LUA_BUILD_TOPLEVEL}")
file(COPY "${LUA_LOCAL_DIR}/include"
DESTINATION "${LUA_BUILD_TOPLEVEL}")
add_custom_target(LUA_VANILLA
DEPENDS "${LUA_VANILLA_LIB_SOURCES}" "${LUA_VANILLA_LUA_SOURCES}")
set(LUA_VANILLA_INCLUDE_DIRS ${LUA_VANILLA_INCLUDE_DIRS} "${LUA_VANILLA_SOURCE_DIR}" "${LUA_BUILD_TOPLEVEL}/include")
else()
ExternalProject_Add(LUA_VANILLA
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS FALSE
TLS_VERIFY TRUE
PREFIX ${LUA_BUILD_TOPLEVEL}
SOURCE_DIR ${LUA_BUILD_TOPLEVEL}
DOWNLOAD_DIR ${LUA_BUILD_TOPLEVEL}
TMP_DIR "${LUA_BUILD_TOPLEVEL}-tmp"
STAMP_DIR "${LUA_BUILD_TOPLEVEL}-stamp"
INSTALL_DIR "${LUA_BUILD_INSTALL_DIR}"
URL ${LUA_VANILLA_DOWNLOAD_URL}
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS "${LUA_VANILLA_LIB_SOURCES}" "${LUA_VANILLA_LUA_SOURCES}")
# make a quick lua.hpp for 5.1 targets that don't have it
if (LUA_VANILLA_GENERATE_LUA_HPP)
set(LUA_VANILLA_LUA_HPP_CONTENT "// lua.hpp
// Lua header files for C++
// <<extern \"C\">> not supplied automatically because Lua also compiles as C++
extern \"C\" {
#include \"lua.h\"
#include \"lualib.h\"
#include \"lauxlib.h\"
}
")
set(LUA_VANILLA_SOURCE_LUA_HPP "${LUA_BUILD_TOPLEVEL}-tmp/lua.hpp")
set(LUA_VANILLA_DESTINATION_LUA_HPP "${LUA_VANILLA_SOURCE_DIR}/lua.hpp")
file(WRITE "${LUA_VANILLA_SOURCE_LUA_HPP}" "${LUA_VANILLA_LUA_HPP_CONTENT}")
file(TO_NATIVE_PATH "${LUA_VANILLA_SOURCE_LUA_HPP}" LUA_VANILLA_SOURCE_LUA_HPP)
file(TO_NATIVE_PATH "${LUA_VANILLA_DESTINATION_LUA_HPP}" LUA_VANILLA_DESTINATION_LUA_HPP)
ExternalProject_Add_Step(LUA_VANILLA
prebuild
# after download, before build
DEPENDEES download
DEPENDERS build
BYPRODUCTS "${LUA_VANILLA_DESTINATION_LUA_HPP}"
COMMENT "Moving \"${LUA_VANILLA_SOURCE_LUA_HPP}\" to \"${LUA_VANILLA_DESTINATION_LUA_HPP}\"..."
COMMAND "${CMAKE_COMMAND}" -E copy "${LUA_VANILLA_SOURCE_LUA_HPP}" "${LUA_VANILLA_DESTINATION_LUA_HPP}")
endif()
set(LUA_VANILLA_INCLUDE_DIRS ${LUA_VANILLA_SOURCE_DIR})
endif()
# # Target names
set(liblua "liblua-${LUA_VANILLA_VERSION}")
set(luainterpreter "lua-${LUA_VANILLA_VERSION}")
set(luacompiler "luac-${LUA_VANILLA_VERSION}")
# Lua does not out-of-the-box support building
# a shared library: http://lua-users.org/lists/lua-l/2006-10/msg00098.html
# in this case, we essentially need to
# build Lua for our purposes, which is annoying
# the external project is just a dummy to get and extract the file:
# after that, we define actual targets...!
# make an actual, buildable target
# that other parts of the code can depend on
add_library(${liblua} ${LUA_BUILD_LIBRARY_TYPE} "${LUA_VANILLA_LIB_SOURCES}")
set_target_properties(${liblua}
PROPERTIES
LANGUAGE ${LUA_VANILLA_LANGUAGE}
LINKER_LANGUAGE ${LUA_VANILLA_LANGUAGE}
${LUA_VANILLA_LANGUAGE}_STANDARD ${LUA_VANILLA_LANGUAGE_STANDARD}
${LUA_VANILLA_LANGUAGE}_EXTENSIONS TRUE
POSITION_INDEPENDENT_CODE TRUE
OUTPUT_NAME ${LUA_BUILD_LIBNAME}
RUNTIME_OUTPUT_NAME ${LUA_BUILD_LIBNAME}
LIBRARY_OUTPUT_NAME ${LUA_BUILD_LIBNAME}
ARCHIVE_OUTPUT_NAME ${LUA_BUILD_LIBNAME})
set_source_files_properties(${LUA_VANILLA_LIB_SOURCES}
PROPERTIES LANGUAGE ${LUA_VANILLA_LANGUAGE})
target_include_directories(${liblua}
PUBLIC "${LUA_VANILLA_INCLUDE_DIRS}")
target_compile_definitions(${liblua}
PUBLIC LUA_COMPAT_ALL ${LUA_VANILLA_DLL_DEFINE})
if (MSVC)
target_compile_options(${liblua}
PRIVATE /W1)
else()
target_compile_options(${liblua}
PRIVATE -w)
endif()
if (WIN32)
#target_compile_definitions(${liblua}
# PRIVATE LUA_USE_WINDOWS)
else()
target_compile_definitions(${liblua}
PRIVATE LUA_USE_LINUX)
endif()
target_compile_options(${liblua}
PRIVATE ${LUA_VANILLA_LUALIB_COMPILER_OPTIONS})
add_dependencies(${liblua} LUA_VANILLA)
target_link_libraries(${liblua} PRIVATE ${CMAKE_DL_LIBS})
if (UNIX)
target_link_libraries(${liblua} PRIVATE m)
endif()
# we don't really need this section...
# Lua Interpreter
if (LUA_BUILD_LUA_INTERPRETER)
add_executable(${luainterpreter} ${LUA_VANILLA_LUA_SOURCES})
set_target_properties(${luainterpreter}
PROPERTIES
LANGUAGE ${LUA_VANILLA_LANGUAGE}
LINKER_LANGUAGE ${LUA_VANILLA_LANGUAGE}
${LUA_VANILLA_LANGUAGE}_STANDARD ${LUA_VANILLA_LANGUAGE_STANDARD}
${LUA_VANILLA_LANGUAGE}_EXTENSIONS TRUE
OUTPUT_NAME lua-${LUA_VANILLA_VERSION})
set_source_files_properties(${LUA_VANILLA_LUA_SOURCES}
PROPERTIES LANGUAGE ${LUA_VANILLA_LANGUAGE})
target_include_directories(${luainterpreter}
PRIVATE "${LUA_VANILLA_INCLUDE_DIRS}")
target_compile_definitions(${luainterpreter}
PUBLIC LUA_COMPAT_ALL ${LUA_VANILLA_DLL_DEFINE}
PRIVATE LUA_COMPAT_ALL ${LUA_VANILLA_DLL_DEFINE})
if (MSVC)
target_compile_options(${luainterpreter}
PRIVATE /W1)
else()
target_compile_options(${luainterpreter}
PRIVATE -w)
endif()
if (WIN32)
#target_compile_definitions(${luainterpreter}
# PRIVATE LUA_USE_WINDOWS)
else()
target_compile_definitions(${luainterpreter}
PRIVATE LUA_USE_LINUX)
endif()
target_link_libraries(${luainterpreter} PRIVATE ${liblua} ${CMAKE_DL_LIBS})
if (UNIX)
target_link_libraries(${luainterpreter} PRIVATE m readline)
endif()
endif()
# LuaC Compiler
if (LUA_BUILD_LUA_COMPILER)
add_executable(${luainterpreter} ${LUA_VANILLA_LUA_SOURCES})
set_target_properties(${luacompiler}
PROPERTIES
LANGUAGE ${LUA_VANILLA_LANGUAGE}
LINKER_LANGUAGE ${LUA_VANILLA_LANGUAGE}
OUTPUT_NAME luac-${LUA_VANILLA_VERSION})
set_source_files_properties(${LUA_VANILLA_LIB_SOURCES}
PROPERTIES LANGUAGE ${LUA_VANILLA_LANGUAGE})
target_include_directories(${luacompiler}
PRIVATE "${LUA_VANILLA_INCLUDE_DIRS}")
target_compile_definitions(${luacompiler}
PUBLIC LUA_COMPAT_ALL ${LUA_VANILLA_DLL_DEFINE}
PRIVATE LUA_COMPAT_ALL ${LUA_VANILLA_DLL_DEFINE})
if (MSVC)
target_compile_options(${luacompiler}
PRIVATE /W1)
else()
target_compile_options(${luacompiler}
PRIVATE -w)
endif()
if (WIN32)
#target_compile_definitions(${luacompiler}
# PRIVATE LUA_USE_WINDOWS)
else()
target_compile_definitions(${luacompiler}
PRIVATE LUA_USE_LINUX)
endif()
target_link_libraries(${luacompiler} PRIVATE ${liblua} ${CMAKE_DL_LIBS})
if (UNIX)
# TODO: make readline optional?
target_link_libraries(${luacompiler} PRIVATE m readline)
endif()
endif()
# set externally-visible target indicator
set(LUA_LIBRARIES ${liblua})
set(LUA_INTERPRETER ${luainterpreter})
if (LUA_BUILD_LUA_COMPILER)
set(LUA_COMPILER ${luacompiler})
endif()
set(LUA_INCLUDE_DIRS "${LUA_VANILLA_SOURCE_DIR}")
-75
View File
@@ -1,75 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
include(ExternalProject)
include(FindPackageHandleStandardArgs)
include(Common/Core)
# # Base variables
set(luwra_version 0.5.0)
set(luwra_lib luwra_lib_${luwra_version})
# # Useful locations
set(luwra_build_toplevel "${CMAKE_BINARY_DIR}/vendor/luwra_${luwra_version}")
set(luwra_include_dirs "${luwra_build_toplevel}/lib")
# # luwra library sources
set(luwra_sources luwra.hpp)
prepend(luwra_sources "${luwra_build_toplevel}/lib/" ${luwra_sources})
# # External project to get sources
ExternalProject_Add(LUWRA_BUILD_SOURCE
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS FALSE
# # Use Git to get what we need
GIT_SHALLOW TRUE
#GIT_TAG e513907fc8c2d59ebd91cd5992eddf54f7e23e21
GIT_REPOSITORY https://github.com/vapourismo/luwra.git
PREFIX ${luwra_build_toplevel}
SOURCE_DIR ${luwra_build_toplevel}
DOWNLOAD_DIR ${luwra_build_toplevel}
TMP_DIR "${luwra_build_toplevel}-tmp"
STAMP_DIR "${luwra_build_toplevel}-stamp"
INSTALL_DIR "${luwra_build_toplevel}/local"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS "${luwra_sources}")
add_library(${luwra_lib} INTERFACE)
add_dependencies(${luwra_lib} LUWRA_BUILD_SOURCE)
target_include_directories(${luwra_lib} INTERFACE ${luwra_include_dirs})
target_link_libraries(${luwra_lib} INTERFACE ${LUA_LIBRARIES})
if (NOT MSVC)
target_compile_options(${luwra_lib} INTERFACE
-Wno-noexcept-type -Wno-ignored-qualifiers -Wno-unused-parameter)
endif()
set(LUWRABUILD_FOUND TRUE)
set(LUWRA_LIBRARIES ${luwra_lib})
set(LUWRA_INCLUDE_DIRS ${luwra_include_dirs})
FIND_PACKAGE_HANDLE_STANDARD_ARGS(LuwraBuild
FOUND_VAR LUWRABUILD_FOUND
REQUIRED_VARS LUWRA_LIBRARIES LUWRA_INCLUDE_DIRS
VERSION_VAR luwra_version)
-68
View File
@@ -1,68 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
include(FindPackageHandleStandardArgs)
include(FeatureSummary)
find_program(Sphinx_Build_EXECUTABLE NAMES sphinx-build DOC "Path to sphinx-build executable")
if (Sphinx_Build_EXECUTABLE)
set(Sphinx_Build_FOUND YES)
endif()
if (Sphinx_Build_FOUND)
execute_process(
COMMAND ${Sphinx_Build_EXECUTABLE} --version
OUTPUT_VARIABLE Sphinx_Build_VERSION_OUTPUT
OUTPUT_STRIP_TRAILING_WHITESPACE
ENCODING UTF-8)
if (Sphinx_Build_VERSION_OUTPUT)
string(REGEX
MATCH "[^0-9]*([0-9]+)[.]([0-9]+)?[.]?([0-9]+)?[.]?([0-9]+)?.*"
Sphinx_Build_VERSION_CHECK ${Sphinx_Build_VERSION_OUTPUT})
endif()
if (Sphinx_Build_VERSION_CHECK)
string(JOIN "." Sphinx_Build_VERSION
${CMAKE_MATCH_1}
${CMAKE_MATCH_2}
${CMAKE_MATCH_3}
${CMAKE_MATCH_4})
set(Sphinx_Build_VERSION "${Sphinx_Build_VERSION}" CACHE STRING "sphinx-build version" FORCE)
endif()
endif()
find_package_handle_standard_args(Sphinx
REQUIRED_VARS Sphinx_Build_EXECUTABLE
VERSION_VAR Sphinx_Build_VERSION
HANDLE_COMPONENTS)
set_package_properties(Sphinx
PROPERTIES
DESCRIPTION "Sphinx Documentation Generator"
URL "https://sphinx-doc.org")
if (Sphinx_Build_FOUND AND NOT TARGET Sphinx::Build)
add_executable(Sphinx::Build IMPORTED)
set_property(TARGET Sphinx::Build PROPERTY IMPORTED_LOCATION ${Sphinx_Build_EXECUTABLE})
set_property(TARGET Sphinx::Build PROPERTY VERSION ${Sphinx_Build_VERSION})
mark_as_advanced(Sphinx_Build_EXECUTABLE Sphinx_Build_VERSION)
endif()
-92
View File
@@ -1,92 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # Standard CMake Libraries
include(ExternalProject)
include(FindPackageHandleStandardArgs)
include(Common/Core)
# # Base variables
set(toluapp_version 1.0.93)
# # Useful locations
set(toluapp_build_toplevel "${CMAKE_BINARY_DIR}/vendor/toluapp_${toluapp_version}")
set(toluapp_include_dirs "${toluapp_build_toplevel}/include")
# # ToLua library sources
set(toluapp_sources tolua_event.c tolua_event.h tolua_is.c tolua_map.c tolua_push.c tolua_to.c tolua_compat.h tolua_compat.c)
prepend(toluapp_sources "${toluapp_build_toplevel}/src/lib/" ${toluapp_sources})
list(APPEND toluapp_sources "${toluapp_build_toplevel}/include/tolua++.h")
# # External project to get sources
ExternalProject_Add(TOLUAPP_BUILD_SOURCE
BUILD_IN_SOURCE TRUE
BUILD_ALWAYS FALSE
# # Use Git to get what we need
#GIT_SUBMODULES ""
GIT_SHALLOW TRUE
GIT_REPOSITORY https://github.com/ThePhD/toluapp
PREFIX ${toluapp_build_toplevel}
SOURCE_DIR ${toluapp_build_toplevel}
DOWNLOAD_DIR ${toluapp_build_toplevel}
TMP_DIR "${toluapp_build_toplevel}-tmp"
STAMP_DIR "${toluapp_build_toplevel}-stamp"
INSTALL_DIR "${toluapp_build_toplevel}/local"
CONFIGURE_COMMAND ""
BUILD_COMMAND ""
INSTALL_COMMAND ""
TEST_COMMAND ""
BUILD_BYPRODUCTS "${toluapp_sources}")
set(toluapp_lib toluapp_lib_${toluapp_version})
add_library(${toluapp_lib} SHARED ${toluapp_sources})
add_dependencies(${toluapp_lib} TOLUAPP_BUILD_SOURCE)
set_target_properties(${toluapp_lib} PROPERTIES
OUTPUT_NAME toluapp-${toluapp_version}
POSITION_INDEPENDENT_CODE TRUE)
target_include_directories(${toluapp_lib}
PUBLIC ${toluapp_include_dirs})
target_link_libraries(${toluapp_lib} PRIVATE ${LUA_LIBRARIES} ${CMAKE_DL_LIBS})
if (MSVC)
target_compile_options(${toluapp_lib}
PRIVATE /W1)
target_compile_definitions(${toluapp_lib}
PRIVATE "TOLUA_API=__declspec(dllexport)")
else()
target_compile_options(${toluapp_lib}
PRIVATE -w
INTERFACE -Wno-noexcept-type
PUBLIC -Wno-ignored-qualifiers -Wno-unused-parameter)
endif()
# add compatibility define
target_compile_definitions(${toluapp_lib}
PRIVATE COMPAT53_PREFIX=toluapp_compat53)
# # Variables required by ToLuaBuild
set(TOLUAPP_LIBRARIES ${toluapp_lib})
set(TOLUAPP_INCLUDE_DIRS ${toluapp_include_dirs})
set(TOLUAPPBUILD_FOUND TRUE)
FIND_PACKAGE_HANDLE_STANDARD_ARGS(ToLuappBuild
FOUND_VAR TOLUAPPBUILD_FOUND
REQUIRED_VARS TOLUAPP_LIBRARIES TOLUAPP_INCLUDE_DIRS
VERSION_VAR toluapp_version)
-32
View File
@@ -1,32 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@PACKAGE_INIT@
include("${CMAKE_CURRENT_LIST_DIR}/sol2-targets.cmake")
if (TARGET sol2)
get_target_property(SOL2_INCLUDE_DIRS
sol2 INTERFACE_INCLUDE_DIRECTORIES)
set_and_check(SOL2_INCLUDE_DIRS "${SOL2_INCLUDE_DIRS}")
set(SOL2_LIBRARIES sol2)
endif()
-110
View File
@@ -1,110 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
---
BasedOnStyle: WebKit
IndentWidth: 5
TabWidth: 5
ContinuationIndentWidth: 5
UseTab: ForIndentation
# Namespaces
NamespaceIndentation: All
CompactNamespaces: true
FixNamespaceComments: true
# Overall Alignment
ColumnLimit: 65
AlignAfterOpenBracket: DontAlign # uses ContinuationIndentWidth for this instead
AccessModifierOffset: -5 # do not push public: or private: around
#AlignConsecutiveAssignments: true # affects more than what's expected: do not use
#AlignConsecutiveDeclarations: true # affects more than what's expected: do not use
# Type Alignment
DerivePointerAlignment: false
PointerAlignment: Left
AlwaysBreakTemplateDeclarations: true
AlwaysBreakBeforeMultilineStrings: true
# Comments
AlignTrailingComments: true
ReflowComments: true
# Macros
AlignEscapedNewlines: Left
#IndentPPDirectives: None
# Functions
AllowShortFunctionsOnASingleLine: None
AlwaysBreakAfterReturnType: None
BreakConstructorInitializers: BeforeComma
ConstructorInitializerIndentWidth: 0
ConstructorInitializerAllOnOneLineOrOnePerLine: true
BinPackArguments: false
BinPackParameters: true
# Classes
BreakBeforeInheritanceComma: false
# Braces
Cpp11BracedListStyle: false
BreakBeforeBraces: Custom
BraceWrapping:
AfterEnum: false
AfterStruct: false
AfterControlStatement: false
AfterClass: false
AfterNamespace: false
AfterStruct: false
AfterUnion: false
BeforeElse: true
BeforeCatch: true
IndentBraces: false
SplitEmptyFunction: false
SplitEmptyRecord: false
SplitEmptyNamespace: true
# Control Statements
AllowShortIfStatementsOnASingleLine: false
AllowShortLoopsOnASingleLine: false
AllowShortCaseLabelsOnASingleLine: false
IndentCaseLabels: false
# Spaces
SpaceAfterCStyleCast: false
SpacesInCStyleCastParentheses: false
SpaceAfterTemplateKeyword: true
SpaceBeforeAssignmentOperators: true
SpaceBeforeParens: ControlStatements
SpaceInEmptyParentheses: false
SpacesInAngles: false
SpacesInParentheses: false
SpacesInSquareBrackets: false
MaxEmptyLinesToKeep: 3
# OCD
SortUsingDeclarations: true
SortIncludes: false
---
Language: Cpp
Standard: Cpp11
-118
View File
@@ -1,118 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 Examples
function(sol2_add_example_properties target-name)
target_link_libraries(${target-name}
PUBLIC Threads::Threads ${LUA_LIBRARIES} ${CMAKE_DL_LIBS})
target_compile_definitions(${target-name}
PUBLIC SOL_PRINT_ERRORS=1)
target_compile_options(${target-name}
PRIVATE
${--template-debugging-mode}
${--big-obj}
${--disable-permissive}
${--pedantic}
${--warn-all}
${--warn-pedantic}
${--warn-extra}
${--warn-errors}
${--utf8-literal-encoding}
${--utf8-source-encoding}
${--allow-unknown-warning}
${--allow-unknown-warning-option}
${--allow-noexcept-type}
${--allow-microsoft-cast}
${--allow-unreachable-code}
${--allow-padding-from-alignment}
)
target_compile_definitions(${target-name}
PRIVATE _CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
if (SOL2_CI)
target_compile_definitions(${target-name}
PRIVATE SOL2_CI)
endif()
if (SOL2_TESTS_EXAMPLES)
add_test(NAME ${target-name} COMMAND ${target-name})
endif()
if(SOL2_ENABLE_INSTALL)
install(TARGETS ${target-name} RUNTIME DESTINATION bin)
endif()
endfunction()
if (SOL2_DYNAMIC_LOADING_EXAMPLES OR SOL2_DYNAMIC_LOADING_EXAMPLES_SINGLE)
# # require_from_dll example
# just add the subdirectory
add_subdirectory(require_dll_example)
endif()
if (SOL2_INTEROP_EXAMPLES OR SOL2_INTEROP_EXAMPLES_SINGLE)
# # interop examples
add_subdirectory(interop/kaguya)
add_subdirectory(interop/tolua)
add_subdirectory(interop/LuaBridge)
add_subdirectory(interop/luwra)
endif()
# # In-depth customization example
add_subdirectory(customization)
# # single-source compilable examples
file(GLOB sol2.examples.sources source/*.cpp source/tutorials/*.cpp source/tutorials/quick_n_dirty/*.cpp source/docs/*.cpp)
function (MAKE_EXAMPLE example_source_file example_prefix target_sol)
get_filename_component(example_name ${example_source_file} NAME_WE)
file(RELATIVE_PATH example_source_file_relative ${CMAKE_SOURCE_DIR} ${example_source_file})
get_filename_component(example_output_relative_dir ${example_source_file_relative} DIRECTORY)
file(TO_CMAKE_PATH "${example_output_relative_dir}" example_output_relative_dir_name)
STRING(REGEX REPLACE "/" "." example_output_relative_dir_name "${example_output_relative_dir}")
if (example_output_relative_dir_name STREQUAL "")
set(example_output_name ${example_name})
set(example_name "${example_prefix}.${example_name}")
else()
set(example_output_name ${example_output_relative_dir_name}.${example_name})
set(example_name "${example_prefix}.${example_output_relative_dir_name}.${example_name}")
endif()
add_executable(${example_name} ${example_source_file})
sol2_add_example_properties(${example_name})
target_link_libraries(${example_name}
PRIVATE ${target_sol})
endfunction(MAKE_EXAMPLE)
if (SOL2_EXAMPLES)
foreach(example_source_file ${sol2.examples.sources})
MAKE_EXAMPLE(${example_source_file} "sol2" sol2::sol2)
endforeach()
endif()
if (SOL2_EXAMPLES_SINGLE)
foreach(example_source_file ${sol2.examples.sources})
MAKE_EXAMPLE(${example_source_file} "sol2.single" sol2::sol2::single)
endforeach()
endif()
-64
View File
@@ -1,64 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 Customization Examples
function (MAKE_CUSTOMIZATION_EXAMPLE example_suffix target_sol)
set(customization_example_name customization_to_table${example_suffix})
add_executable(${customization_example_name} source/main.cpp source/lua_interop.cpp source/lua_zm_interop.cpp)
set_target_properties(${customization_example_name}
PROPERTIES
OUTPUT_NAME "${customization_example_name}"
EXPORT_NAME sol2::${customization_example_name})
if (MSVC)
target_compile_options(${customization_example_name}
PRIVATE /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${customization_example_name}
PRIVATE UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${customization_example_name}
PRIVATE -std=c++1z
-ftemplate-backtrace-limit=0
-Wno-unknown-warning -Wno-unknown-warning-option
-Wall -Wpedantic -Werror -pedantic -pedantic-errors
-Wno-noexcept-type)
endif()
target_link_libraries(${customization_example_name}
PRIVATE Threads::Threads ${target_sol} ${LUA_LIBRARIES})
target_include_directories(${customization_example_name}
PRIVATE include)
endfunction()
if (SOL2_EXAMPLES)
MAKE_CUSTOMIZATION_EXAMPLE("" sol2::sol2)
endif()
if (SOL2_EXAMPLES_SINGLE)
MAKE_CUSTOMIZATION_EXAMPLE(".single" sol2::sol2::single)
endif()
-25
View File
@@ -1,25 +0,0 @@
#pragma once
#ifndef PROGRAM_ENTITY_HPP
#define PROGRAM_ENTITY_HPP
#include <zm/vec3.hpp>
class entity {
private:
zm::vec3 position_;
public:
entity() {
this->position_ = { 1, 1, 1 };
}
zm::vec3 get_position() const {
return this->position_;
}
void set_position(zm::vec3 v) {
this->position_ = v;
}
};
#endif // PROGRAM_ENTITY_HPP
@@ -1,13 +0,0 @@
#pragma once
#ifndef PROGRAM_LUA_INTEROP_HPP
#define PROGRAM_LUA_INTEROP_HPP
#include <lua_zm_interop.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/forward.hpp>
void register_lua(sol::state& lua);
#endif // PROGRAM_LUA_INTEROP_HPP
@@ -1,23 +0,0 @@
#pragma once
#ifndef PROGRAM_LUA_ZM_INTEROP_HPP
#define PROGRAM_LUA_ZM_INTEROP_HPP
#define SOL_ALL_SAFETIES_ON 1
#include <sol/forward.hpp>
#include <zm/vec3.hpp>
#include <functional>
bool sol_lua_check(sol::types<zm::vec3>, lua_State* L, int index,
std::function<sol::check_handler_type> handler,
sol::stack::record& tracking);
zm::vec3 sol_lua_get(sol::types<zm::vec3>, lua_State* L,
int index, sol::stack::record& tracking);
int sol_lua_push(
sol::types<zm::vec3>, lua_State* L, const zm::vec3& v);
#endif // PROGRAM_LUA_ZM_INTEROP_HPP
-74
View File
@@ -1,74 +0,0 @@
#pragma once
#ifndef ZM_VEC3_HPP
#define ZM_VEC3_HPP
#include <cstddef>
namespace zm {
struct vec3 {
#if defined(__clang__)
#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wgnu-anonymous-struct"
#pragma clang diagnostic ignored "-Wnested-anon-types"
#elif defined(__GNUC__)
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wpedantic"
#elif defined(_MSC_VER)
#pragma warning(push)
#pragma warning(disable : 4201) // nonstandard extension used :
// nameless struct/union
#pragma warning(disable : 4324) // structure was padded due to
// alignment specifier
#endif
union {
float elements[3];
struct {
union {
float x, r, s;
};
union {
float y, g, t;
};
union {
float z, b, p;
};
};
};
#if defined(__clang__)
#pragma clang diagnostic pop
#elif defined(__GNUC__)
#pragma GCC diagnostic pop
#elif defined(_MSC_VER)
#pragma warning(pop)
#endif
vec3() : x(0), y(0), z(0) {
}
vec3(float x_, float y_, float z_)
: x(x_), y(y_), z(z_) {
}
constexpr float* data() {
return elements;
}
constexpr const float* data() const {
return this->elements;
}
constexpr float& operator[](std::size_t i) {
return this->elements[i];
}
constexpr const float& operator[](
std::size_t i) const {
return this->elements[i];
}
};
} // namespace zm
#endif // ZM_VEC3_HPP
@@ -1,13 +0,0 @@
#include <lua_interop.hpp>
#include <entity.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
void register_lua(sol::state& lua) {
lua.new_usertype<entity>("entity",
"position",
sol::property(
&entity::get_position, &entity::set_position));
}
@@ -1,38 +0,0 @@
#include <lua_zm_interop.hpp>
#include <zm/vec3.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
bool sol_lua_check(sol::types<zm::vec3>, lua_State* L, int index,
std::function<sol::check_handler_type> handler,
sol::stack::record& tracking) {
// use sol's method for checking
// specifically for a table
return sol::stack::check<sol::lua_table>(
L, index, handler, tracking);
}
zm::vec3 sol_lua_get(sol::types<zm::vec3>, lua_State* L,
int index, sol::stack::record& tracking) {
sol::lua_table vec3table
= sol::stack::get<sol::lua_table>(L, index, tracking);
float x = vec3table["x"];
float y = vec3table["y"];
float z = vec3table["z"];
return zm::vec3 { x, y, z };
}
int sol_lua_push(
sol::types<zm::vec3>, lua_State* L, const zm::vec3& v) {
// create table
sol::state_view lua(L);
sol::table vec3table = sol::table::create_with(
L, "x", v.x, "y", v.y, "z", v.z);
// use base sol method to
// push the table
int amount = sol::stack::push(L, vec3table);
// return # of things pushed onto stack
return amount;
}
-42
View File
@@ -1,42 +0,0 @@
#include <lua_interop.hpp>
#include <entity.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== customization: vec3 as table ==="
<< std::endl;
sol::state lua;
lua.open_libraries(sol::lib::base);
std::cout << "registering entities into Lua ..."
<< std::endl;
register_lua(lua);
std::cout << "running script ..." << std::endl;
const auto& script = R"lua(
local e = entity.new()
local pos = e.position
print("pos type", type(pos))
print("pos", pos.x, pos.y, pos.z)
e.position = { x = 52, y = 5.5, z = 47.5 }
local new_pos = e.position
print("pos", pos.x, pos.y, pos.z)
print("new_pos", new_pos.x, new_pos.y, new_pos.z)
)lua";
sol::optional<sol::error> result = lua.safe_script(script);
if (result.has_value()) {
std::cerr << "Something went horribly wrong: "
<< result.value().what() << std::endl;
}
std::cout << "finishing ..." << std::endl;
std::cout << std::endl;
return 0;
}
-62
View File
@@ -1,62 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 interop Examples - luabridge
find_package(LuaBridgeBuild)
function (make_luabridge_interop_example target_library example_suffix)
set(example_name luabridge_interop_example)
set(example_name "${example_name}${example_suffix}")
add_executable(${example_name} source/LuaBridge.cpp)
target_link_libraries(${example_name}
PRIVATE ${LUA_LIBRARIES} ${LUABRIDGE_LIBRARIES}
${target_library} ${CMAKE_DL_LIBS})
if (MSVC)
target_compile_options(${example_name}
PRIVATE /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${example_name}
PRIVATE /W1
UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${example_name}
PRIVATE -std=c++1z -w
-Wno-unknown-warning -Wno-unknown-warning-option)
endif()
if (SOL2_TESTS_INTEROP_EXAMPLES)
add_test(NAME ${example_name} COMMAND ${example_name})
endif()
endfunction()
if (SOL2_INTEROP_EXAMPLES)
make_luabridge_interop_example(sol2::sol2 "")
endif()
if (SOL2_INTEROP_EXAMPLES_SINGLE)
make_luabridge_interop_example(sol2::sol2::single ".single")
endif()
@@ -1,135 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#define SOL_ENABLE_INTEROP \
1 // MUST be defined to use interop features
#include <sol/sol.hpp>
#include <LuaBridge/LuaBridge.h>
#include <iostream>
// LuaBridge,
// no longer maintained, by VinnieFalco:
// https://github.com/vinniefalco/LuaBridge
struct A {
A(int v) : v_(v) {
}
void print() {
std::cout << "called A::print" << std::endl;
}
int value() const {
return v_;
}
private:
int v_ = 50;
};
template <typename T, typename Handler>
inline bool sol_lua_interop_check(sol::types<T>, lua_State* L,
int relindex, sol::type index_type, Handler&& handler,
sol::stack::record& tracking) {
// just marking unused parameters for no compiler warnings
(void)index_type;
(void)handler;
tracking.use(1);
int index = lua_absindex(L, relindex);
T* corrected = luabridge::Userdata::get<T>(L, index, true);
return corrected != nullptr;
}
template <typename T>
inline std::pair<bool, T*> sol_lua_interop_get(sol::types<T> t,
lua_State* L, int relindex, void* unadjusted_pointer,
sol::stack::record& tracking) {
(void)unadjusted_pointer;
int index = lua_absindex(L, relindex);
if (!sol_lua_interop_check(t,
L,
index,
sol::type::userdata,
sol::no_panic,
tracking)) {
return { false, nullptr };
}
T* corrected = luabridge::Userdata::get<T>(L, index, true);
return { true, corrected };
}
void register_sol_stuff(lua_State* L) {
// grab raw state and put into state_view
// state_view is cheap to construct
sol::state_view lua(L);
// bind and set up your things: everything is entirely
// self-contained
lua["f"] = sol::overload(
[](A& from_luabridge) {
std::cout << "calling 1-argument version with "
"luabridge-created A { "
<< from_luabridge.value() << " }"
<< std::endl;
sol_c_assert(from_luabridge.value() == 24);
},
[](A& from_luabridge, int second_arg) {
std::cout << "calling 2-argument version with "
"luabridge-created A { "
<< from_luabridge.value()
<< " } and integer argument of "
<< second_arg << std::endl;
sol_c_assert(from_luabridge.value() == 24);
sol_c_assert(second_arg == 5);
});
}
void check_with_sol(lua_State* L) {
sol::state_view lua(L);
A& obj = lua["obj"];
(void)obj;
sol_c_assert(obj.value() == 24);
}
int main(int, char*[]) {
std::cout << "=== interop example (LuaBridge) ==="
<< std::endl;
std::cout << "code modified from LuaBridge's examples: "
"https://github.com/vinniefalco/LuaBridge"
<< std::endl;
struct closer {
void operator()(lua_State* L) {
lua_close(L);
}
};
std::unique_ptr<lua_State, closer> state(luaL_newstate());
lua_State* L = state.get();
luaL_openlibs(L);
luabridge::getGlobalNamespace(L)
.beginNamespace("test")
.beginClass<A>("A")
.addConstructor<void (*)(int)>()
.addFunction("print", &A::print)
.addFunction("value", &A::value)
.endClass()
.endNamespace();
register_sol_stuff(L);
if (luaL_dostring(L, R"(
obj = test.A(24)
f(obj) -- call 1 argument version
f(obj, 5) -- call 2 argument version
)")) {
lua_error(L);
}
check_with_sol(L);
return 0;
}
-61
View File
@@ -1,61 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 interop Examples - kaguya
find_package(KaguyaBuild)
function (make_kaguya_interop_example target_library example_suffix)
set(example_name kaguya_interop_example)
set(example_name "${example_name}${example_suffix}")
add_executable(${example_name} source/kaguya.cpp)
target_link_libraries(${example_name}
PRIVATE ${LUA_LIBRARIES} ${KAGUYA_LIBRARIES}
${target_library} ${CMAKE_DL_LIBS})
if (MSVC)
target_compile_options(${example_name}
PRIVATE /W1 /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${example_name}
PRIVATE UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${example_name}
PRIVATE -std=c++1z -w
-Wno-unknown-warning -Wno-unknown-warning-option)
endif()
if (SOL2_TESTS_INTEROP_EXAMPLES)
add_test(NAME ${example_name} COMMAND ${example_name})
endif()
endfunction()
if (SOL2_INTEROP_EXAMPLES)
make_kaguya_interop_example(sol2::sol2 "")
endif()
if (SOL2_INTEROP_EXAMPLES_SINGLE)
make_kaguya_interop_example(sol2::sol2::single ".single")
endif()
-141
View File
@@ -1,141 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#define SOL_ENABLE_INTEROP \
1 // MUST be defined to use interop features
#include <sol/sol.hpp>
#include <iostream>
// kaguya code lifted from README.md,
// written by satoren:
// https://github.com/satoren/kaguya
// Copyright satoren
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
struct ABC {
ABC() : v_(0) {
}
ABC(int value) : v_(value) {
}
int value() const {
return v_;
}
void setValue(int v) {
v_ = v;
}
void overload1() {
std::cout << "call overload1" << std::endl;
}
void overload2(int) {
std::cout << "call overload2" << std::endl;
}
private:
int v_;
};
template <typename T, typename Handler>
inline bool sol_lua_interop_check(sol::types<T>, lua_State* L,
int relindex, sol::type index_type, Handler&& handler,
sol::stack::record& tracking) {
// just marking unused parameters for no compiler warnings
(void)index_type;
(void)handler;
// using 1 element
tracking.use(1);
int index = lua_absindex(L, relindex);
// use kaguya's own detail wrapper check to see if it's
// correct
bool is_correct_type
= kaguya::detail::object_wrapper_type_check(L, index);
return is_correct_type;
}
template <typename T>
inline std::pair<bool, T*> sol_lua_interop_get(sol::types<T>,
lua_State* L, int relindex, void* unadjusted_pointer,
sol::stack::record& tracking) {
// you may not need to specialize this method every time:
// some libraries are compatible with sol2's layout
// kaguya's storage of data is incompatible with sol's
// it stores the data directly in the pointer, not a pointer
// inside of the `void*` therefore, leave the raw userdata
// pointer as-is, if it's of the right type
int index = lua_absindex(L, relindex);
if (!kaguya::detail::object_wrapper_type_check(L, index)) {
return { false, nullptr };
}
// using 1 element
tracking.use(1);
kaguya::ObjectWrapperBase* base
= kaguya::object_wrapper(L, index);
return { true, static_cast<T*>(base->get()) };
}
void register_sol_stuff(lua_State* L) {
// grab raw state and put into state_view
// state_view is cheap to construct
sol::state_view lua(L);
// bind and set up your things: everything is entirely
// self-contained
lua["f"] = sol::overload(
[](ABC& from_kaguya) {
std::cout << "calling 1-argument version with "
"kaguya-created ABC { "
<< from_kaguya.value() << " }"
<< std::endl;
sol_c_assert(from_kaguya.value() == 24);
},
[](ABC& from_kaguya, int second_arg) {
std::cout << "calling 2-argument version with "
"kaguya-created ABC { "
<< from_kaguya.value()
<< " } and integer argument of "
<< second_arg << std::endl;
sol_c_assert(from_kaguya.value() == 24);
sol_c_assert(second_arg == 5);
});
}
void check_with_sol(lua_State* L) {
sol::state_view lua(L);
ABC& obj = lua["obj"];
(void)obj;
sol_c_assert(obj.value() == 24);
}
int main(int, char*[]) {
std::cout << "=== interop example (kaguya) ==="
<< std::endl;
std::cout << "(code lifted from kaguya's README examples: "
"https://github.com/satoren/kaguya)"
<< std::endl;
kaguya::State state;
state["ABC"].setClass(
kaguya::UserdataMetatable<ABC>()
.setConstructors<ABC(), ABC(int)>()
.addFunction("get_value", &ABC::value)
.addFunction("set_value", &ABC::setValue)
.addOverloadedFunctions(
"overload", &ABC::overload1, &ABC::overload2)
.addStaticFunction("nonmemberfun",
[](ABC* self, int) { return 1; }));
register_sol_stuff(state.state());
state.dostring(R"(
obj = ABC.new(24)
f(obj) -- call 1 argument version
f(obj, 5) -- call 2 argument version
)");
check_with_sol(state.state());
return 0;
}
-61
View File
@@ -1,61 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 interop Examples - luwra
find_package(LuwraBuild)
function (make_luwra_interop_example target_library example_suffix)
set(example_name luwra_interop_example)
set(example_name "${example_name}${example_suffix}")
add_executable(${example_name} source/luwra.cpp)
target_link_libraries(${example_name}
PRIVATE ${LUA_LIBRARIES} ${LUWRA_LIBRARIES}
${target_library} ${CMAKE_DL_LIBS})
if (MSVC)
target_compile_options(${example_name}
PRIVATE /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${example_name}
PRIVATE /W1 UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${example_name}
PRIVATE -std=c++1z -w
-Wno-unknown-warning -Wno-unknown-warning-option)
endif()
if (SOL2_TESTS_INTEROP_EXAMPLES)
add_test(NAME ${example_name} COMMAND ${example_name})
endif()
endfunction()
if (SOL2_INTEROP_EXAMPLES)
make_luwra_interop_example(sol2::sol2 "")
endif()
if (SOL2_INTEROP_EXAMPLES_SINGLE)
make_luwra_interop_example(sol2::sol2::single ".single")
endif()
-131
View File
@@ -1,131 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#define SOL_ENABLE_INTEROP \
1 // MUST be defined to use interop features
#include <sol/sol.hpp>
#include <luwra.hpp>
#include <iostream>
// luwra,
// another C++ wrapper library:
// https://github.com/vapourismo/luwra
struct ABC {
ABC() : v_(0) {
}
ABC(int value) : v_(value) {
}
int value() const {
return v_;
}
void setValue(int v) {
v_ = v;
}
void overload1() {
std::cout << "call overload1" << std::endl;
}
void overload2(int) {
std::cout << "call overload2" << std::endl;
}
private:
int v_;
};
template <typename T, typename Handler>
inline bool sol_lua_interop_check(sol::types<T>, lua_State* L,
int relindex, sol::type index_type, Handler&& handler,
sol::stack::record& tracking) {
// just marking unused parameters for no compiler warnings
(void)index_type;
(void)handler;
// using 1 element
tracking.use(1);
int index = lua_absindex(L, relindex);
if (lua_getmetatable(L, index) == 1) {
luaL_getmetatable(
L, luwra::internal::UserTypeReg<T>::name.c_str());
bool is_correct_type = lua_rawequal(L, -2, -1) == 1;
lua_pop(L, 2);
return is_correct_type;
}
return false;
}
template <typename T>
inline std::pair<bool, T*> sol_lua_interop_get(sol::types<T> t,
lua_State* L, int relindex, void* unadjusted_pointer,
sol::stack::record& tracking) {
// you may not need to specialize this method every time:
// some libraries are compatible with sol2's layout
int index = lua_absindex(L, relindex);
if (!sol_lua_interop_check(t,
L,
index,
sol::type::userdata,
sol::no_panic,
tracking)) {
return { false, nullptr };
}
return { true, static_cast<T*>(unadjusted_pointer) };
}
void register_sol_stuff(lua_State* L) {
// grab raw state and put into state_view
// state_view is cheap to construct
sol::state_view lua(L);
// bind and set up your things: everything is entirely
// self-contained
lua["f"] = sol::overload(
[](ABC& from_luwra) {
std::cout << "calling 1-argument version with "
"luwra-created ABC { "
<< from_luwra.value() << " }"
<< std::endl;
sol_c_assert(from_luwra.value() == 24);
},
[](ABC& from_luwra, int second_arg) {
std::cout << "calling 2-argument version with "
"luwra-created ABC { "
<< from_luwra.value()
<< " } and integer argument of "
<< second_arg << std::endl;
sol_c_assert(from_luwra.value() == 24);
sol_c_assert(second_arg == 5);
});
}
void check_with_sol(lua_State* L) {
sol::state_view lua(L);
ABC& obj = lua["obj"];
(void)obj;
sol_c_assert(obj.value() == 24);
}
int main(int, char*[]) {
std::cout << "=== interop example (luwra) ===" << std::endl;
std::cout << "code modified from luwra's documentation "
"examples: https://github.com/vapourismo/luwra"
<< std::endl;
luwra::StateWrapper state;
state.registerUserType<ABC(int)>("ABC",
{ LUWRA_MEMBER(ABC, value),
LUWRA_MEMBER(ABC, setValue) },
{});
register_sol_stuff(state);
state.runString(R"(
obj = ABC(24)
f(obj) -- call 1 argument version
f(obj, 5) -- call 2 argument version
)");
check_with_sol(state);
return 0;
}
-63
View File
@@ -1,63 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 interop Examples - tolua
find_package(ToLuappBuild REQUIRED)
function(make_tolua_interop_example target_library example_suffix)
set(example_name tolua_interop_example)
set(example_name "${example_name}${example_suffix}")
add_executable(${example_name} source/tolua.cpp)
target_link_libraries(${example_name}
PRIVATE
${LUA_LIBRARIES} ${TOLUAPP_LIBRARIES} ${target_library} ${CMAKE_DL_LIBS})
if (MSVC)
target_compile_options(${example_name}
PRIVATE /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${example_name}
PRIVATE /W1 UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${example_name}
PRIVATE -std=c++1z -w
-Wno-unknown-warning -Wno-unknown-warning-option)
endif()
if (SOL2_TESTS_INTEROP_EXAMPLES)
add_test(NAME ${example_name} COMMAND ${example_name})
endif()
endfunction()
MESSAGE(STATUS ${SOL2_LUA_VERSION})
if (SOL2_INTEROP_EXAMPLES)
make_tolua_interop_example(sol2::sol2 "")
endif()
if (SOL2_INTEROP_EXAMPLES_SINGLE)
make_tolua_interop_example(sol2::sol2::single ".single")
endif()
-19
View File
@@ -1,19 +0,0 @@
#ifndef PLAYER_H
#define PLAYER_H
class Player {
private:
int m_health;
public:
Player() : m_health(0) {
}
void setHealth(int health) {
m_health = health;
}
int getHealth() const {
return m_health;
}
};
#endif // PLAYER_H
-8
View File
@@ -1,8 +0,0 @@
$#include "Player.h"
class Player {
Player();
~Player();
void setHealth(int _health);
int getHealth();
};
-113
View File
@@ -1,113 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#define SOL_ENABLE_INTEROP \
1 // MUST be defined to use interop features
#include <sol/sol.hpp>
#include "Player.h"
#include <tolua++.h>
// pick or replace the include
// with whatever generated file you've created
#include "tolua_Player.h"
#include <iostream>
// tolua code lifted from some blog, if the link dies
// I don't know where else you're gonna find the reference,
// http://usefulgamedev.weebly.com/tolua-example.html
/* NOTE: there is no sol_lua_interop_get here,
because tolua types are -- thankfully -- memory-compatible
in most cases with sol.
Please check other examples like kaguya or LuaBribe for an
example of how to also write the getter for your type*/
template <typename T, typename Handler>
inline bool sol_lua_interop_check(sol::types<T>, lua_State* L,
int relindex, sol::type index_type, Handler&& handler,
sol::stack::record& tracking) {
tracking.use(1);
// just marking unused parameters for no compiler warnings
(void)index_type;
(void)handler;
int index = lua_absindex(L, relindex);
std::string name = sol::detail::short_demangle<T>();
tolua_Error tolua_err {};
int r = tolua_isusertype(
L, index, name.c_str(), 0, &tolua_err);
if (r == 0) {
// tolua seems to leave garbage on the stack
// when the check fails
// thanks, tolua
lua_pop(L, 2);
return false;
}
return true;
}
void register_sol_stuff(lua_State* L) {
// grab raw state and put into state_view
// state_view is cheap to construct
sol::state_view lua(L);
// bind and set up your things: everything is entirely
// self-contained
lua["f"] = sol::overload(
[](Player& from_tolua) {
std::cout << "calling 1-argument version with "
"tolua-created Player { health:"
<< from_tolua.getHealth() << " }"
<< std::endl;
sol_c_assert(from_tolua.getHealth() == 4);
},
[](Player& from_tolua, int second_arg) {
std::cout << "calling 2-argument version with "
"tolua-created Player { health: "
<< from_tolua.getHealth()
<< " } and integer argument of "
<< second_arg << std::endl;
sol_c_assert(from_tolua.getHealth() == 4);
sol_c_assert(second_arg == 5);
});
}
void check_with_sol(lua_State* L) {
sol::state_view lua(L);
Player& obj = lua["obj"];
(void)obj;
sol_c_assert(obj.getHealth() == 4);
}
int main(int, char*[]) {
std::cout << "=== interop example (tolua) ===" << std::endl;
std::cout << "(code lifted from a sol2 user's use case: "
"https://github.com/ThePhD/sol2/issues/"
"511#issuecomment-331729884)"
<< std::endl;
lua_State* L = luaL_newstate();
luaL_openlibs(
L); // initalize all lua standard library functions
tolua_open(L); // initalize tolua
tolua_Player_open(
L); // make Player class accessible from LUA
register_sol_stuff(L);
const auto code = R"(
obj = Player:new()
obj:setHealth(4)
f(obj) -- call 1 argument version
f(obj, 5) -- call 2 argument version
)";
if (luaL_dostring(L, code)) {
lua_error(L); // crash on error
}
check_with_sol(L);
return 0;
}
-226
View File
@@ -1,226 +0,0 @@
/*
** Lua binding: Player
** Generated automatically by tolua++-1.0.93-lua53 on Sat Feb 10
*08:48:53 2018.
*/
#ifndef __cplusplus
#include "stdlib.h"
#endif
#include "string.h"
#include "tolua++.h"
/* Exported function */
TOLUA_API int tolua_Player_open(lua_State* tolua_S);
#include "Player.h"
/* function to release collected object via destructor */
#ifdef __cplusplus
static int tolua_collect_Player(lua_State* tolua_S) {
Player* self = (Player*)tolua_tousertype(tolua_S, 1, 0);
Mtolua_delete(self);
return 0;
}
#endif
/* function to register type */
static void tolua_reg_types(lua_State* tolua_S) {
tolua_usertype(tolua_S, "Player");
}
/* method: new of class Player */
#ifndef TOLUA_DISABLE_tolua_Player_Player_new00
static int tolua_Player_Player_new00(lua_State* tolua_S) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!tolua_isusertable(tolua_S, 1, "Player", 0, &tolua_err)
|| !tolua_isnoobj(tolua_S, 2, &tolua_err))
goto tolua_lerror;
else
#endif
{
{
Player* tolua_ret
= (Player*)Mtolua_new((Player)());
tolua_pushusertype(
tolua_S, (void*)tolua_ret, "Player");
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(
tolua_S, "#ferror in function 'new'.", &tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: new_local of class Player */
#ifndef TOLUA_DISABLE_tolua_Player_Player_new00_local
static int tolua_Player_Player_new00_local(lua_State* tolua_S) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!tolua_isusertable(tolua_S, 1, "Player", 0, &tolua_err)
|| !tolua_isnoobj(tolua_S, 2, &tolua_err))
goto tolua_lerror;
else
#endif
{
{
Player* tolua_ret
= (Player*)Mtolua_new((Player)());
tolua_pushusertype(
tolua_S, (void*)tolua_ret, "Player");
tolua_register_gc(tolua_S, lua_gettop(tolua_S));
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(
tolua_S, "#ferror in function 'new'.", &tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: delete of class Player */
#ifndef TOLUA_DISABLE_tolua_Player_Player_delete00
static int tolua_Player_Player_delete00(lua_State* tolua_S) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!tolua_isusertype(tolua_S, 1, "Player", 0, &tolua_err)
|| !tolua_isnoobj(tolua_S, 2, &tolua_err))
goto tolua_lerror;
else
#endif
{
Player* self
= (Player*)tolua_tousertype(tolua_S, 1, 0);
#ifndef TOLUA_RELEASE
if (!self)
tolua_error(tolua_S,
"invalid 'self' in function 'delete'",
NULL);
#endif
Mtolua_delete(self);
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(
tolua_S, "#ferror in function 'delete'.", &tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: setHealth of class Player */
#ifndef TOLUA_DISABLE_tolua_Player_Player_setHealth00
static int tolua_Player_Player_setHealth00(lua_State* tolua_S) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!tolua_isusertype(tolua_S, 1, "Player", 0, &tolua_err)
|| !tolua_isnumber(tolua_S, 2, 0, &tolua_err)
|| !tolua_isnoobj(tolua_S, 3, &tolua_err))
goto tolua_lerror;
else
#endif
{
Player* self
= (Player*)tolua_tousertype(tolua_S, 1, 0);
int _health = ((int)tolua_tonumber(tolua_S, 2, 0));
#ifndef TOLUA_RELEASE
if (!self)
tolua_error(tolua_S,
"invalid 'self' in function 'setHealth'",
NULL);
#endif
{ self->setHealth(_health); }
}
return 0;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,
"#ferror in function 'setHealth'.",
&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* method: getHealth of class Player */
#ifndef TOLUA_DISABLE_tolua_Player_Player_getHealth00
static int tolua_Player_Player_getHealth00(lua_State* tolua_S) {
#ifndef TOLUA_RELEASE
tolua_Error tolua_err;
if (!tolua_isusertype(tolua_S, 1, "Player", 0, &tolua_err)
|| !tolua_isnoobj(tolua_S, 2, &tolua_err))
goto tolua_lerror;
else
#endif
{
Player* self
= (Player*)tolua_tousertype(tolua_S, 1, 0);
#ifndef TOLUA_RELEASE
if (!self)
tolua_error(tolua_S,
"invalid 'self' in function 'getHealth'",
NULL);
#endif
{
int tolua_ret = (int)self->getHealth();
tolua_pushnumber(tolua_S, (lua_Number)tolua_ret);
}
}
return 1;
#ifndef TOLUA_RELEASE
tolua_lerror:
tolua_error(tolua_S,
"#ferror in function 'getHealth'.",
&tolua_err);
return 0;
#endif
}
#endif //#ifndef TOLUA_DISABLE
/* Open function */
TOLUA_API int tolua_Player_open(lua_State* tolua_S) {
tolua_open(tolua_S);
tolua_reg_types(tolua_S);
tolua_module(tolua_S, NULL, 0);
tolua_beginmodule(tolua_S, NULL);
#ifdef __cplusplus
tolua_cclass(
tolua_S, "Player", "Player", "", tolua_collect_Player);
#else
tolua_cclass(tolua_S, "Player", "Player", "", NULL);
#endif
tolua_beginmodule(tolua_S, "Player");
tolua_function(tolua_S, "new", tolua_Player_Player_new00);
tolua_function(
tolua_S, "new_local", tolua_Player_Player_new00_local);
tolua_function(
tolua_S, ".call", tolua_Player_Player_new00_local);
tolua_function(
tolua_S, "delete", tolua_Player_Player_delete00);
tolua_function(
tolua_S, "setHealth", tolua_Player_Player_setHealth00);
tolua_function(
tolua_S, "getHealth", tolua_Player_Player_getHealth00);
tolua_endmodule(tolua_S);
tolua_endmodule(tolua_S);
return 1;
}
#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM >= 501
TOLUA_API int luaopen_Player(lua_State* tolua_S) {
return tolua_Player_open(tolua_S);
};
#endif
-134
View File
@@ -1,134 +0,0 @@
# # # # sol2
# The MIT License (MIT)
#
# Copyright (c) 2013-2022 Rapptz, ThePhD, and contributors
#
# Permission is hereby granted, free of charge, to any person obtaining a copy of
# this software and associated documentation files (the "Software"), to deal in
# the Software without restriction, including without limitation the rights to
# use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
# the Software, and to permit persons to whom the Software is furnished to do so,
# subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
# FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
# COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
# IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
# CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
# # # sol2 Examples - require_from_dll
# # Reusable function to call for single target
# # Also hides variables from directory/global scope
function(make_require_from_dll_example target_lib example_lib_name_suffix)
# define sources
set(my_object_sources source/my_object.cpp)
set(require_from_dll_sources source/require_from_dll.cpp)
# define names
set(example_lib_name my_object)
set(example_name require_from_dll)
set(example_lib_name "${example_lib_name}${example_lib_name_suffix}")
set(example_name "${example_name}${example_lib_name_suffix}")
# add library target my_object for the require_from_dll program
add_library(${example_lib_name} SHARED ${my_object_sources})
set_target_properties(${example_lib_name} PROPERTIES
PREFIX "")
target_include_directories(${example_lib_name}
PUBLIC "${CMAKE_CURRENT_SOURCE_DIR}/include")
target_compile_definitions(${example_lib_name}
PUBLIC MY_OBJECT_DLL
PRIVATE MY_OBJECT_BUILD)
target_link_libraries(${example_lib_name}
PUBLIC ${target_lib} ${LUA_LIBRARIES} ${CMAKE_DL_LIBS})
target_include_directories(${example_lib_name}
PUBLIC "${LUA_INCLUDE_DIRS}")
if (MSVC)
target_compile_options(${example_lib_name}
PRIVATE /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${example_lib_name}
PRIVATE UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${example_lib_name}
PRIVATE -std=c++1z
-Wno-unknown-warning -Wno-unknown-warning-option
-Wall -Wextra -Wpedantic -pedantic -pedantic-errors
-Wno-noexcept-type)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# For another day, when C++ is not so crap
# and we have time to audit the entire lib
# for all uses of `detail::swallow`...
#target_compile_options(${test_target_name}
# PRIVATE -Wcomma)
endif()
if (IS_X86)
target_compile_options(${example_lib_name} BEFORE PRIVATE -m32)
endif()
endif()
# add executable target that represents require_from_dll program
add_executable(${example_name} ${require_from_dll_sources})
target_link_libraries(${example_name}
PRIVATE my_object ${LUA_LIBRARIES} ${target_lib} ${CMAKE_DL_LIBS})
target_include_directories(${example_name}
PRIVATE ${LUA_INCLUDE_DIRS})
if (MSVC)
target_compile_options(${example_name}
PRIVATE /std:c++latest /EHsc "$<$<CONFIG:Debug>:/MDd>"
"$<$<CONFIG:Release>:/MD>"
"$<$<CONFIG:RelWithDebInfo>:/MD>"
"$<$<CONFIG:MinSizeRel>:/MD>")
target_compile_definitions(${example_name}
PRIVATE UNICODE _UNICODE
_CRT_SECURE_NO_WARNINGS _CRT_SECURE_NO_DEPRECATE)
else()
target_compile_options(${example_name}
PRIVATE -std=c++1z
-Wno-unknown-warning -Wno-unknown-warning-option
-Wall -Wextra -Wpedantic -pedantic -pedantic-errors
-Wno-noexcept-type)
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
# For another day, when C++ is not so crap
# and we have time to audit the entire lib
# for all uses of `detail::swallow`...
#target_compile_options(${test_target_name}
# PRIVATE -Wcomma)
endif()
endif()
if (SOL2_TESTS_DYNAMIC_LOADING_EXAMPLES)
get_target_property(example_working_dir ${example_name} RUNTIME_OUTPUT_DIRECTORY)
add_test(NAME ${example_name} COMMAND ${example_name} WORKING_DIRECTORY "${example_working_dir}")
endif()
endfunction()
list(GET LUA_LIBRARIES 0 lua_lib_target)
get_target_property(lua_lib_type ${lua_lib_target} TYPE)
if (lua_lib_type MATCHES "STATIC")
# avoid multiply defined references due to linking in the same static library
# twice over, and get "multiple definition" errors during linking
return()
endif()
if (SOL2_DYNAMIC_LOADING_EXAMPLES)
make_require_from_dll_example(sol2::sol2 "")
endif()
if (SOL2_DYNAMIC_LOADING_EXAMPLES_SINGLE)
make_require_from_dll_example(sol2::sol2::single ".single")
endif()
@@ -1,29 +0,0 @@
#pragma once
#include <my_object/my_object_api.hpp>
// forward declare as a C struct
// so a pointer to lua_State can be part of a signature
extern "C" {
struct lua_State;
}
// you can replace the above if you're fine with including
// <sol.hpp> earlier than absolutely necessary
namespace my_object {
struct test {
int value;
test() = default;
test(int val) : value(val) {
}
};
} // namespace my_object
// this function needs to be exported from your
// dll. "extern 'C'" should do the trick, but
// we're including platform-specific stuff here to help
// see my_object_api.hpp for details
extern "C" MY_OBJECT_API int luaopen_my_object(lua_State* L);
@@ -1,28 +0,0 @@
#pragma once
namespace my_object {
#if defined _MSC_VER
#define MY_OBJECT_VC
#elif defined __GNUC__
#define MY_OBJECT_GCC
#elif defined __clang__
#define MY_OBJECT_CLANG
#endif
#if defined MY_OBJECT_VC
#if defined MY_OBJECT_DLL
#if defined MY_OBJECT_BUILD
#define MY_OBJECT_API __declspec(dllexport)
#else
#define MY_OBJECT_API __declspec(dllexport)
#endif // MY_OBJECT_BUILD - Building the Library vs. Using the
// Library
#else
#define MY_OBJECT_API
#endif // Building a DLL vs. Static Library
#else // g++ / clang++
#define MY_OBJECT_API __attribute__((visibility("default")))
#endif // MY_OBJECT_BUILD
} // namespace my_object
@@ -1,30 +0,0 @@
#include <my_object/my_object.hpp>
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
namespace my_object {
sol::table open_my_object(sol::this_state L) {
sol::state_view lua(L);
sol::table module = lua.create_table();
module.new_usertype<test>("test",
sol::constructors<test(), test(int)>(),
"value",
&test::value);
return module;
}
} // namespace my_object
extern "C" int luaopen_my_object(lua_State* L) {
// pass the lua_State,
// the index to start grabbing arguments from,
// and the function itself
// optionally, you can pass extra arguments to the function
// if that's necessary, but that's advanced usage and is
// generally reserved for internals only
return sol::stack::call_lua(
L, 1, my_object::open_my_object);
}
@@ -1,35 +0,0 @@
#define SOL_ALL_SAFETIES_ON 1
#include <sol/sol.hpp>
#include <my_object/my_object.hpp>
#include <iostream>
int main(int, char*[]) {
std::cout << "=== require from DLL ===" << std::endl;
sol::state lua;
lua.open_libraries(sol::lib::package, sol::lib::base);
const auto& code = R"(
mo = require("my_object")
obj = mo.test.new(24)
print(obj.value))";
auto script_result
= lua.safe_script(code, &sol::script_pass_on_error);
if (script_result.valid()) {
std::cout << "The DLL was require'd from successfully!"
<< std::endl;
}
else {
sol::error err = script_result;
std::cout << "Something bad happened: " << err.what()
<< std::endl;
}
sol_c_assert(script_result.valid());
my_object::test& obj = lua["obj"];
sol_c_assert(obj.value == 24);
return 0;
}
-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;
}

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