diff --git a/third/luaaa/.gitignore b/third/luaaa/.gitignore new file mode 100644 index 00000000..b3dbbc6e --- /dev/null +++ b/third/luaaa/.gitignore @@ -0,0 +1,40 @@ +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +# Others +.vs +.vscode +example/example +example/vs2015 +example/example +example/embedded diff --git a/third/luaaa/LICENSE b/third/luaaa/LICENSE new file mode 100644 index 00000000..d0a9f55d --- /dev/null +++ b/third/luaaa/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 gengyong + +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. diff --git a/third/luaaa/README.md b/third/luaaa/README.md new file mode 100644 index 00000000..f445e4c1 --- /dev/null +++ b/third/luaaa/README.md @@ -0,0 +1,429 @@ + +## Introduction + +Luaaa is a simple tool to bind c++ class to lua. + +It was implemented intent to use only one header file, with simple interface, easy to integrate to existing project. + +With luaaa, you don't need to write wrapper codes for existing class/function, and you don't need to run any other tool to generate wrapper codes. Just define the class to export and enjoy using it in lua. + +Luaaa has no dependencies to other libs but lua and c++11 standard lib, no cpp files. + +To use it, just copy and include 'luaaa.hpp' in source file. + +feel free to report bugs. +## Features + +* simple. +* no wrapper codes. +* works with lua from 5.1 to 5.4, and luajit. + +## Quick Start + +export a class to lua: +```cpp + +// include luaaa file +#include "luaaa.hpp" +using namespace luaaa; + + +// Your existing class +class Cat +{ +public: + Cat(); + virtual ~Cat(); +public: + void setName(const std::string&); + const std::string& getName() const; + void eat(const std::list& foods); + static void speak(const std::string& w); + //... +private: + //... +}; + + +lua_State * state; // create and init lua + +// To export it: +LuaClass luaCat(state, "AwesomeCat"); +luaCat.ctor(); +luaCat.fun("setName", &Cat::setName); +luaCat.fun("getName", &Cat::getName); +luaCat.fun("eat", &Cat::eat); +// static member fuction was exported as Lua class member fuction. +// from Lua, call it as same as other member fuctions. +luaCat.fun("speak", &Cat::speak); +luaCat.def("tag", "Cat"); + +// Done. + +``` + +ok, then you can access lua class "AwesomeCat" from lua. +```lua + +local cat = AwesomeCat.new("Bingo"); +cat:eat({"fish", "milk", "cookie", "odd thing" }); +cat:speak("Thanks!"); + +``` + +you can add property to AwesomeCat: +```cpp +luaCat.set("name", &Cat::setName); +luaCat.get("name", &Cat::getName); +luaCat.set("age", &Cat::setAge); +luaCat.get("age", &Cat::getAge); +``` + +then you can access property from lua as below: +```lua +local oldName = cat.name; +print("cat's old name:", oldName); +cat.name = "NewName"; +print("cat's new name:", cat.name); +``` +for the property getter, property type depends on the return value of getter function. + +property getter accepts a function likes below: +```cpp +// 1) member function of origin c++ class which has no parameter +luaCat.get("name", &Cat::getName); + +// 2) global function which has no parameter +//std::string getProp1() { +// return "whatever"; +//} +luaCat.get("prop1", getProp1); + +// 3) global function which has origin c++ class as the only ONE parameter, parameter can be const or non-const. +//std::string getProp2(const Cat& cat) { +// return cat.name; +//} +luaCat.get("prop2", getProp2); + +// 4) a lambda function which has no parameter +luaCat.get("prop3", []() -> float { return 0.123f; }); + +// 5) a lambda function which has origin c++ class as the only ONE parameter, parameter can be const or non-const. +luaCat.get("prop4", [](Cat& cat) -> float { return cat.getWeight(); }); + +``` + +for the property setter, property type depends on the parameter of setter function. + +property setter accepts a function likes below: +```cpp +// 1) member function of origin c++ class which has only ONE parameter +// in lua, +// cat.name = "some thing..."; +// will call c++ function: +// catObject.setName("some thing..."); +luaCat.set("name", &Cat::setName); +// in lua, +// cat.age = 2; +// will call c++ function: +// catObject.setAge(2); +luaCat.set("age", &Cat::setAge); + +// 2) global function which has only ONE parameter +//void setProp1(cons std::string p) { +// // do some thing... +//} +// in lua, +// cat.prop1 = "prop value"; +// will call c++ function: +// setProp1("prop value"); +luaCat.set("prop1", setProp1); + +// 3) global function which accepts an origin c++ class and an extra parameter, origin c++ class can be const or non-const. +//void setProp2(Cat& cat, const std::string p) { +// cat.setName(p); +//} +// in lua, +// cat.prop2 = "prop value"; +// will call c++ function: +// setProp2(catObject, "prop value"); +luaCat.set("prop2", setProp2); + +// 4) lambda function which has only ONE parameter +luaCat.set("prop3", [](float val) -> void { printf("set prop3=%f\n", val); }); + +// 5) lambda function which accepts an origin c++ class and an extra parameter, origin c++ class can be const or non-const. +luaCat.set("prop4", [](Cat& cat, float val) -> void { cat.setWeight(val); }); +``` + +if a property has only getter, it's read-only, if it has only setter, it's write-only, or if has both setter and getter, it can be read&write. + +if write a read-only property, or read a write-only property from lua, a lua exception will be rised: + +for example, with below defination: +```cpp +LuaClass luaCat(state, "AnotherCat"); +luaCat.ctor(); +luaCat.set("name", &Cat::setName); +luaCat.get("age", &Cat::getAge); +``` + +in lua: +```lua +local cat = AnotherCat.new("Orange"); +print("Cat name:", cat.name); +``` +will rise below exception: +```bash +lua err: [string "console"]:79: attempt to read Write-Only property 'name' of 'AwesomeCat' +``` + +```lua +local cat = AnotherCat.new("Orange"); +cat.age = 10; +``` +will rise below exception: +```bash +lua err: [string "console"]:1: attempt to write Read-Only property 'age' of 'AwesomeCat' +``` + + +to export constructors, for example, instance getter of singleton pattern: +```cpp +LuaClass luaWorld(L, "SingletonWorld"); +/// use class constructor as instance spawner, default destructor will be called from gc. +luaWorld.ctor(); + +/// use static function as instance spawner, default destructor will be called from gc. +luaWorld.ctor("newInstance", &SingletonWorld::newInstance); + +/// use static function as instance spawner and static function as delete function which be called from gc. +luaWorld.ctor("managedInstance", &SingletonWorld::newInstance , &SingletonWorld::delInstance); + +/// for singleton pattern, set deleter(gc) to nullptr to avoid singleton instance be destroyed. +luaWorld.ctor("getInstance", &SingletonWorld::getInstance, nullptr); +``` +instance spawner and delete function can be static member function or global function, +and delete function must accept one instance pointer which to be collect back or delete. + + +A 'ctor'(constructor) is always required for LuaClass, you can define more than one 'ctor'. +In most case, a 'ctor' likes below is enought: +```cpp +LuaClass luaCls(luaState, 'XXXname'); +luaCls.ctor(); +``` + +> above codes will define a lua object constructor named as 'new', in lua `XXXname.new()` equivalent to C++: + +```cpp +new XXX(); +``` + +> or change constructor name to 'create': + +```cpp +luaCls.ctor("create"); +``` + +> if C++ constructor is not the default constructor, add sigature to match C++ class constructor: + +```cpp +luaCls.ctor('create'); +``` + +> which defines a lua object constructor named as 'create', in lua `XXXname.create("string param")` equivalent to C++: + +```cpp +new XXX("string param"); +``` + + +static member function, global fuctions or constant can be export in module. +module has no constructor or destructor. +```cpp + +#include "luaaa.hpp" +using namespace luaaa; + +void func1(int); +void func2(int, int, int); +int func3(int, const char *, float, int, int , float); +bool globalFunc(const std::string&, const std::map&); + +lua_State * state; + +/* + init lua state here... +*/ + +LuaModule(state, "moduleName") MyMod; +MyMod.fun("func1", func1); +MyMod +.fun("func2", func2) +.fun("func3", func3) +.def("cstr", "this is cstring"); + +// or export function or some value to global(just emit module name) +LuaModule(state) +.fun("globalFunc", globalFunc) +.def("cint", 12345) +.def("dict", std::set({"cat", "dog", "cow"})); + +// etc... + +// Done. + +``` + +ok, then access it from lua: +```lua +-- access module members +MyMod.func1(123) +MyMod.func2(123, "456", 523.3) +MyMod.func3(123, "string or any can be cast to string", 1.23, "1000", "2000", "9.876") +print(MyMod.cstr) + +-- call global function +globalFunc("string or any thing can be cast to string", { key = "table will be cast to map"}) + +-- print global value 'dict' comes from c++ +for k,v in pairs(dict) do + print(tostring(k) .. " = " .. tostring(v)) +end + +``` + +to export c++ functions with same name, for example: +```cpp + bool samename(const std::string&); + void samename(int); + + class MyClass + { + public: + void sameNameFunc(int, int); + void sameNameFunc(int); + bool sameNameFunc(); + }; +``` +in this case, function signature is required here to know which function should be exported: +```cpp +MyMod.fun("func1", (bool(*)(const std::string&)) samename); +MyMod.fun("func2", (void(*)(int)) samename); + +LuaClass(state, "MyClass") + .fun("sameNameFunc1", (void(MyClass::*)(int, int)) &MyClass::sameNameFunc) + .fun("sameNameFunc2", (void(MyClass::*)(int) &MyClass::sameNameFunc)) + .fun("sameNameFunc3", (bool(MyClass::*)() &MyClass::sameNameFunc)); +``` + +to export lambda function: +```cpp +MyMod.fun("lambdaFunc", [](int a, int b) -> int { + return a * b; +}); +``` + + + + +to extend exported lua class, add below codes to your project: +```lua +-- put utility functions to name space 'luaaa' +luaaa = {} + +-- create subclass for base, obj can be exist table or nil +function luaaa:extend(base, obj) + derived = obj or {} + derived.new = function(self, ...) + o = base.new(...) + setmetatable(self, getmetatable(o)) + self["@"] = o + return self + end + return derived +end + +-- get base class of obj +function luaaa:base(obj) + if (type(obj) == "table") then + return obj["@"] + end + return nil +end + +``` + +extends exported lua class as below: +```lua +SpecialCat = luaaa:extend(AwesomeCat, {value = 1}) +-- or: +-- SpecialCat = luaaa:extend(AwesomeCat) +-- in this case there no attribute was extended + +function SpecialCat:onlyInSpecial() + print(self:getName() .. " has a special cat function") + print("Special cat " .. self:getName() .." has value:" .. self.value) +end + +function SpecialCat:speak(text) + print("Special cat[" .. self:getName() .. "] says: " .. text) + -- call override base method: + luaaa:base(self):speak(text) +end +``` + +then use SpecialCat: +```lua +xxx = SpecialCat:new("xxx") +xxx:speak("I am a special cat.") +xxx:onlyInSpecial() +``` + +## Advanced Topic + + + +## Run Example + +### 1. Linux / Unix / Macos + +1. install lua dev libs +```bash +# debian/ubuntu +$ sudo apt install lua5.3-dev +# redhat/centos/fedora +$ sudo yum install lua5.3-dev +``` + + +2. build & run. +```bash +$ cd example +$ g++ -std=c++11 example.cpp -I/usr/include/lua5.3 -o example -g -lstdc++ -llua5.3 +$ ./example +``` + +or use LLVM: +```bash +$ cd example +$ clang -std=c++11 example.cpp -I/usr/include/lua5.3 -o example -g -lstdc++ -llua5.3 +$ ./example +``` + +for embedded device, declare 'LUAAA_WITHOUT_CPP_STDLIB' to disable c++ stdlib. +``` +$ cd example +$ gcc -fno-exceptions -fno-rtti -std=c++11 embedded.cpp -I/usr/include/lua5.3 -o embedded -g -llua5.3 -DLUAAA_WITHOUT_CPP_STDLIB +$ ./embedded +``` + +### 2. Visual C++ + +Of course you know how to do it. + + +## License + +See the LICENSE file. diff --git a/third/luaaa/example/embedded.cpp b/third/luaaa/example/embedded.cpp new file mode 100644 index 00000000..b0ba21bd --- /dev/null +++ b/third/luaaa/example/embedded.cpp @@ -0,0 +1,490 @@ + + +#include +#include +#include + +#define LUAAA_WITHOUT_CPP_STDLIB 1 + +#include "../luaaa.hpp" + +#define LOG printf + +#if defined(_MSC_VER) +# define strncpy strncpy_s +#endif + + +//=============================================================================== +using namespace luaaa; +class MyType { +public: + MyType() :m_dummy(0) { + LOG("MyType::MyType\n"); + } + virtual ~MyType() { + LOG("MyType::~MyType\n"); + } +private: + int m_dummy; +}; + +class MyTypeB { +public: + MyTypeB() :m_dummy(0) { + LOG("MyTypeB::MyTypeB\n"); + } + virtual ~MyTypeB() { + LOG("MyTypeB::~MyTypeB\n"); + } +private: + int m_dummy; +}; + +void test1() +{ + lua_State* L = luaL_newstate(); + LuaClass myLuaType(L, "MyType"); + myLuaType.ctor(); + LOG("export MyType 1.\n"); + + LuaClass myLuaTypeB(L, "MyTypeB"); + myLuaTypeB.ctor(); + LOG("export MyTypeB 1.\n"); + + luaL_dostring(L, "local a = MyType.new();local b = MyTypeB.new();"); + + LOG("ready to close....\n"); + + lua_close(L); +} + +void test2() +{ + lua_State* L = luaL_newstate(); + LuaClass myLuaType(L, "MyType"); + myLuaType.ctor(); + printf("export MyType 2.\n"); + + lua_gc(L, LUA_GCCOLLECT, 0); + + LuaClass myLuaTypeB(L, "MyTypeB"); + myLuaTypeB.ctor(); + LOG("export MyTypeB 2.\n"); + + lua_gc(L, LUA_GCCOLLECT, 0); + + luaL_dostring(L, "local a = MyType.new();local b = MyTypeB.new();"); + + lua_gc(L, LUA_GCCOLLECT, 0); + + LOG("ready to close2....\n"); + + lua_close(L); +} + +void testExportMoreThanOnce() { + test1(); + test2(); +} + +//=============================================================================== +void bindToLUA(lua_State *); + +void runLuaExample(lua_State * ls) +{ + bindToLUA(ls); + + LOG("------------------------------------------\n"); + if (luaL_dofile(ls, "example.lua")) + { + LOG("lua err: %s", lua_tostring(ls, -1)); + lua_pop(ls, 1); + } +} + + +int main() +{ + testExportMoreThanOnce(); + + const luaL_Reg lualibs[] = { + { LUA_COLIBNAME, luaopen_base }, + { LUA_LOADLIBNAME, luaopen_package }, + { LUA_TABLIBNAME, luaopen_table }, + { LUA_IOLIBNAME, luaopen_io }, + { LUA_OSLIBNAME, luaopen_os }, + { LUA_STRLIBNAME, luaopen_string }, + { LUA_MATHLIBNAME, luaopen_math }, + { LUA_DBLIBNAME, luaopen_debug }, + { NULL, NULL } + }; + + auto ls = luaL_newstate(); + + if (ls != NULL) + { + const luaL_Reg *lib = lualibs; + for (; lib->func; lib++) { + lua_pushcfunction(ls, lib->func); + lua_pushstring(ls, lib->name); + lua_call(ls, 1, 0); + } + + runLuaExample(ls); + + lua_close(ls); + } + return 0; +} + + +//=============================================================================== +// example class +//=============================================================================== +#ifndef __PLACEMENT_NEW_INLINE +void * operator new(size_t sz, void * p) { + return p; +} + +void operator delete(void *, void *) noexcept { +} +#endif + +void * operator new(size_t sz) { + return malloc(sz); +} +void operator delete(void * p) noexcept { + free(p); +} + +void * operator new[](size_t sz) { + return malloc(sz); +} + +void operator delete[](void* p) { + return free(p); +} + + +class Cat +{ +public: + Cat() + : m_age(1), m_weight(1.0f) + { + LOG("Cat: a cat spawn at %p.\n", this); + } + + Cat(const char * name) + : m_age(1), m_weight(1.0f) + { + strncpy(m_name, name, sizeof(m_name)); + LOG("Cat: %s spawn at %p\n", m_name, this); + } + + ~Cat() + { + LOG("Cat: cat[%p] %s is free.\n", this, m_name); + } + + const char * getName() const { + return m_name; + } + + + const char * setName(const char * name) + { + strncpy(m_name, name, sizeof(m_name)); + return m_name; + } + + int setAge(const int age) + { + m_age = age; + return m_age; + } + + int getAge() const + { + return m_age; + } + + void eat(lua_State * L) + { + if (lua_istable(L, -1)) + { + lua_pushnil(L); + while (0 != lua_next(L, -2)) + { + const int top = lua_gettop(L); + const char * food = luaaa::LuaStack::get(L, top); + + LOG("%s eat %s.\n", m_name, food); + m_weight += 0.1f; + + lua_pop(L, 1); + } + lua_pop(L, 0); + } + + LOG("%s is getting fatter.\n", m_name); + return; + } + + void test(int a, const char * b, float c, const char * d, const char * e) + { + LOG("cat test: got params from lua: [0: %d, 1:%s, 2:%f, 3:%s, 4:%s]\n", a, b, c, d, e); + } + + const char * toString() const + { + static char buf[128]; + snprintf(buf, sizeof(buf), "%s is a cat, he is %d years old, has a weight of %f kg.", m_name, m_age, m_weight); + return buf; + } + + static void speak(const char * w) + { + LOG("%s, miaow~~\n", w); + } + +private: + char m_name[32]; + int m_age; + float m_weight; +}; + + +class SingletonWorld +{ +public: + static SingletonWorld * getInstance() { + if (s_instance == nullptr) { + s_instance = new SingletonWorld("singleton"); + } + return s_instance; + } + + static SingletonWorld * newInstance(const char * tagName) { + return new SingletonWorld(tagName); + } + + static void delInstance(SingletonWorld * instance) { + delete instance; + } +public: + const char * getTag() const { + return mTag; + } + + SingletonWorld() { + snprintf(mTag, sizeof(mTag), "%s", "default"); + LOG("SingletonWorld[%s] constructed.\n", mTag); + } + + SingletonWorld(const char * tagName) { + snprintf(mTag, sizeof(mTag), "%s", tagName); + LOG("SingletonWorld[%s] constructed.\n", mTag); + } + + ~SingletonWorld() { + LOG("SingletonWorld[%s] destructed.\n", mTag); + } +private: + char mTag[16]; + static SingletonWorld * s_instance; +}; + +SingletonWorld * SingletonWorld::s_instance = nullptr; + +class Position { +public: + float x; + float y; + float z; + + Position():x(0), y(0), z(0) {} + Position(float fx, float fy, float fz):x(fx), y(fy), z(fz) {} +}; + + + +//=============================================================================== +// example c++ functions +//=============================================================================== +void testSet() +{ + LOG("testSet: [unsupported]\n"); +} + +void testSetSet() +{ + LOG("testSetSet: [unsupported]\n"); +} + + +void testMapMap() +{ + LOG("testMapMap: [unsupported]\n"); +} + +void testMultipleParams(int a, int b, const char * c, float d, double e) +{ + LOG("c++ testCallback: got params from lua: [0: %d, 1:%d, 2:%s, 3:%f, 4:%g]\n", a, b, c, d, e); +} + +void testCallback(int (*f)(const char *, int, float), int val, const char * str) +{ + char strbuf[128]; + snprintf(strbuf, sizeof(strbuf), "a string from c:%s", str); + auto result = f(strbuf, val, 1.2345678f); + LOG("c++ testCallback: got result from lua callback: %d\n", result); +} + +//=============================================== +// declare custom LuaStack operators +//=============================================== +// for GCC, it must be delcared in namespace luaaa. +namespace luaaa { + template<> struct LuaStack + { + inline static Position get(lua_State * L, int idx) + { + Position result; + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + const int top = lua_gettop(L); + const char * name = LuaStack::get(L, top - 1); + if (strncmp(name, "x", 1) == 0) { + result.x = LuaStack::get(L, top); + } + else if (strncmp(name, "y", 1) == 0) { + result.y = LuaStack::get(L, top); + } + else if (strncmp(name, "z", 1) == 0) { + result.z = LuaStack::get(L, top); + } + lua_pop(L, 1); + } + lua_pop(L, 0); + } + return result; + } + + inline static void put(lua_State * L, const Position & v) + { + lua_newtable(L); + LuaStack::put(L, "x"); + LuaStack::put(L, v.x); + lua_rawset(L, -3); + LuaStack::put(L, "y"); + LuaStack::put(L, v.y); + lua_rawset(L, -3); + LuaStack::put(L, "z"); + LuaStack::put(L, v.z); + lua_rawset(L, -3); + } + }; +} + +Position testPosition(const Position& a, const Position& b) +{ + return Position(a.x + b.x, a.y + b.y, a.z + b.z); +} + + +//=============================================== +// below shows ho to bind c++ with lua +//=============================================== +using namespace luaaa; + +const char * getProp1(const Cat& cat) { + return cat.getName(); +} + +void setProp1(Cat& cat, const char * val) { + cat.setName(val); +} + +void bindToLUA(lua_State * L) +{ + // bind class to lua + LuaClass luaCat(L, "AwesomeCat"); + luaCat.ctor(); + luaCat.fun("setName", &Cat::setName); + luaCat.fun("getName", &Cat::getName); + luaCat.fun("setAge", &Cat::setAge); + luaCat.fun("getAge", &Cat::getAge); + luaCat.fun("eat", &Cat::eat); + luaCat.fun("test", &Cat::test); + luaCat.fun("speak", &Cat::speak); + luaCat.fun("__tostring", &Cat::toString); + luaCat.def("tag", "Animal"); + + luaCat.set("say", &Cat::speak); + luaCat.set("name", &Cat::setName); + luaCat.get("name", &Cat::getName); + luaCat.set("age", &Cat::setAge); + luaCat.get("age", &Cat::getAge); + + luaCat.set("prop1", setProp1); + luaCat.get("prop1", getProp1); + + // bind singleton class to lua + LuaClass luaWorld(L, "SingletonWorld"); + /// use class constructor as instance spawner, default destructor will be called from gc. + luaWorld.ctor(); + /// use static function as instance spawner, default destructor will be called from gc. + luaWorld.ctor("newInstance", &SingletonWorld::newInstance); + /// use static function as instance spawner and static function as delete function which be called from gc. + luaWorld.ctor("managedInstance", &SingletonWorld::newInstance , &SingletonWorld::delInstance); + /// for singleton pattern, set deleter(gc) to nullptr to avoid singleton instance be destroyed. + luaWorld.ctor("getInstance", &SingletonWorld::getInstance, nullptr); + luaWorld.fun("getTag", &SingletonWorld::getTag); + + + + // define a module with name "AwesomeMod" + LuaModule awesomeMod(L, "AwesomeMod"); + awesomeMod.def("cint", 20190101); + awesomeMod.def("cstr", "this is c string"); + + const char * dict[] = { + "AMICUS", "AMOS", "AMTRAK", "ANGELICA", "ANNIE OAKLEY", + "BEETHOVEN", "BERTHA", "BESSEYA", "BILLIE JEAN", "BIMBO", + "BISS", "DECATHLON", "DELIRIUM", "DELIUS", "DEMPSEY" + }; + + awesomeMod.def("dict", dict, sizeof(dict)/sizeof(dict[0])); + + int dict2[] = { + 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47 + }; + awesomeMod.def("dict2", dict2, sizeof(dict2) / sizeof(dict2[0])); + + awesomeMod.fun("testSet", testSet); + awesomeMod.fun("testSetSet", testSetSet); + awesomeMod.fun("testMapMap", testMapMap); + awesomeMod.fun("testMultipleParams", testMultipleParams); + awesomeMod.fun("testCallback", testCallback); + awesomeMod.fun("testPosition", testPosition); + + // put something to global, just emit the module name + LuaModule(L).def("pi", 3.1415926535897932); + + LuaModule(L).def("WITHOUT_CPP_STDLIB", true); + + // operations can be chained. + LuaClass(L, "int") + .ctor("new") + .def("type", "[c int *]") + .def("max", INT_MAX) + .def("min", INT_MIN); + +} + + diff --git a/third/luaaa/example/example.cpp b/third/luaaa/example/example.cpp new file mode 100644 index 00000000..dfb2bc0d --- /dev/null +++ b/third/luaaa/example/example.cpp @@ -0,0 +1,505 @@ + + +#include +#include +#include +#include +#include + +#include "../luaaa.hpp" + +#define LOG printf + + +void bindToLUA(lua_State *); + +void runLuaExample(lua_State * ls) +{ + bindToLUA(ls); + + do { + LOG("------------------------------------------\n"); + std::stringstream buffer; + std::ifstream file("example.lua"); + if (file) + { + buffer << file.rdbuf(); + file.close(); + } + + + int err = luaL_loadbuffer(ls, buffer.str().c_str(), buffer.str().length(), "console"); + if (err == 0) + { + err = lua_pcall(ls, 0, 0, 0); + } + + if (err) + { + LOG("lua err: %s", lua_tostring(ls, -1)); + lua_pop(ls, 1); + } + + } while (std::cin.get() != 27); + +} + + +int main() +{ + auto ls = luaL_newstate(); + luaL_openlibs(ls); + + if (ls != NULL) + { + runLuaExample(ls); + + lua_close(ls); + } + return 0; +} + + + +//=============================================================================== +// example c++ class +//=============================================================================== + + +class Cat +{ +public: + Cat() + : m_age(1), m_weight(1.0f) + { + LOG("Cat: a cat spawn at %p.\n", this); + } + + Cat(const std::string& name) + : m_name(name), m_age(1), m_weight(1.0f) + { + LOG("Cat: %s spawn at %p\n", m_name.c_str(), this); + } + + ~Cat() + { + LOG("Cat: cat[%p] %s is free.\n", this, m_name.c_str()); + } + + const std::string& getName() const { + LOG("Cat:get name\n"); + return m_name; + } + + + const std::string& setName(const std::string& name) + { + LOG("Cat:set name to %s\n", name.c_str()); + m_name = name; + return m_name; + } + + int setAge(const int age) + { + LOG("Cat:set age to %d\n", age); + m_age = age; + return m_age; + } + + int getAge() const + { + LOG("Cat:get age\n"); + return m_age; + } + + float setWeight(float w) + { + LOG("Cat:set weight to %f\n", w); + m_weight = w; + return m_weight; + } + + float getWeight() const + { + LOG("Cat:get weight\n"); + return m_weight; + } + + void eat(const std::list& foods) + { + for (auto & it : foods) + { + LOG("%s eat %s.\n", m_name.c_str(), it.c_str()); + m_weight += 0.1f; + } + LOG("%s is getting fatter.\n", m_name.c_str()); + } + + void test(int a, const std::string& b, float c, const std::string& d, const std::string& e) + { + LOG("cat test: got params from lua: [0: %d, 1:%s, 2:%f, 3:%s, 4:%s]\n", a, b.c_str(), c, d.c_str(), e.c_str()); + } + + std::string toString() const + { + std::stringstream result; + result << m_name << " is a cat, he is " << m_age <<" years old, has a weight of " << m_weight << " kg."; + return result.str(); + } + + static void speak(const std::string& w) + { + LOG("%s, miaow~~\n", w.c_str()); + } + + void testfunctor(std::function callback) + { + int result = callback(42); + LOG("Callback with argument 42 leads to %d.\n", result); + } + +public: + std::string prop1; + std::set prop3; +private: + std::string m_name; + int m_age; + float m_weight; +}; + + +std::string getProp1(const Cat& cat) { + printf("*** READ prop1 ***\n"); + return cat.prop1; +} + +void setProp1(Cat& cat, const std::string& val) { + printf("*** WRITE prop1 ***\n"); + cat.prop1 = val; +} + + +class SingletonWorld +{ +public: + static SingletonWorld * getInstance() { + static SingletonWorld instance("singleton"); + return &instance; + } + + static SingletonWorld * newInstance(const std::string tagName) { + return new SingletonWorld(tagName); + } + + static void delInstance(SingletonWorld * instance) { + delete instance; + } +public: + const std::string getTag() const { + return mTag; + } + + SingletonWorld() { + mTag = "default"; + LOG("SingletonWorld[%s] constructed.\n", mTag.c_str()); + } + + SingletonWorld(const std::string& tagName) : mTag(tagName) { + LOG("SingletonWorld[%s] constructed.\n", mTag.c_str()); + } + + ~SingletonWorld() { + LOG("SingletonWorld[%s] destructed.\n", mTag.c_str()); + } +private: + std::string mTag; +}; + +class Position { +public: + float x; + float y; + float z; + + Position():x(0), y(0), z(0) {} + Position(float fx, float fy, float fz):x(fx), y(fy), z(fz) {} +}; + + + +//=============================================================================== +// example c functions +//=============================================================================== +void testSet(const std::set& s1, const std::set& s2) +{ + LOG("testSet: set size: s1:%lu s2:%lu\n", s1.size(), s2.size()); + LOG("--------------------------\n"); + LOG("s1:"); + for (auto it = s1.begin(); it != s1.end(); ++it) + { + LOG("%d ", *it); + } + LOG("\ns2:"); + for (auto it = s2.begin(); it != s2.end(); ++it) + { + LOG("%d ", *it); + } + LOG("\n--------------------------\n"); +} + +void testSetSet(const std::multiset>& s) +{ + LOG("testSetSet: multiset> size: %lu\n", s.size()); + LOG("--------------------------\n"); + for (auto it = s.begin(); it != s.end(); ++it) + { + LOG("=>set size: %lu\n", it->size()); + for (auto nit = it->begin(); nit != it->end(); ++nit) + { + LOG("'%s', ", nit->c_str()); + } + LOG("\n"); + } + LOG("\n--------------------------\n"); +} + + +void testMapMap(const std::map>& s) +{ + LOG("testMapMap: map> size: %lu\n", s.size()); + LOG("--------------------------\n"); + for (auto it = s.begin(); it != s.end(); ++it) + { + LOG("'%s' => map size: %lu\n", it->first.c_str(), it->second.size()); + for (auto nit = it->second.begin(); nit != it->second.end(); ++nit) + { + LOG("%s = %s, ", nit->first.c_str(), nit->second.c_str()); + } + LOG("\n"); + } + LOG("\n--------------------------\n"); +} + + +const std::tuple testTuple(std::tuple info) { + LOG("c++ load lua list to tuple:\n"); + LOG("\t0: '%s'\n", std::get<0>(info).c_str()); + LOG("\t1: %d\n", std::get<1>(info)); + LOG("\t2: %g\n", std::get<2>(info)); + LOG("c++ returns tuple to lua:\n"); + return std::tuple(123, "string A", "string B", 0.123f); +} + +const std::tuple<> testTuple2(std::tuple<> info) { + LOG("c++ load lua list to empty tuple.\n"); + LOG("c++ returns empty tuple to lua:\n"); + return std::tuple<>(); +} + +void testMultipleParams(int a, int b, const std::string& c, float d, double e) +{ + LOG("c++ testCallback: got params from lua: [0: %d, 1: %d, 2: %s, 3: %f, 4: %g]\n", a, b, c.c_str(), d, e); +} + + +void testCallback(int (*f)(const std::string&, int, float), int val, const std::string& str) +{ + auto result = f("a string from c++:" + str, val, 1.2345678f); + LOG("c++ testCallback: got result from lua callback: %d\n", result); +} + +void testCallbackFunctor(std::function f, int val, const std::string& str) +{ + auto result = f("a string from c++:" + str, val, 8.7654321f); + LOG("c++ testCallbackFunctor: got result from lua callback: %d\n", result); +} + + +//=============================================== +// declare custom LuaStack operators +//=============================================== +// for GCC, it must be delcared in namespace luaaa. +namespace luaaa { + template<> struct LuaStack + { + inline static Position get(lua_State * L, int idx) + { + auto dict = LuaStack>::get(L, idx); + return Position(dict.find("x")->second, dict.find("y")->second, dict.find("z")->second); + } + + inline static void put(lua_State * L, const Position & v) + { + std::map dict; + dict["x"] = v.x; + dict["y"] = v.y; + dict["z"] = v.z; + LuaStack::put(L, dict); + } + }; +} +//*/ + +Position testPosition(const Position& a, const Position& b) +{ + return Position(a.x + b.x, a.y + b.y, a.z + b.z); +} + + +//=============================================== +// below shows ho to bind c++ with lua +//=============================================== +using namespace luaaa; + + +int module__index(lua_State* state) { + LOG("~~~~~~~~~~~~~~~~~~module__index:~~~~~~~~~~~~~~~~~~~"); + lua_pushinteger(state, 999); + return 1; +} + +int module__newindex(lua_State* state) { + LOG("~~~~~~~~~~~~~~~~~~module__newindex:~~~~~~~~~~~~~~~~~~~"); + lua_rawset(state, -3); + return 0; +} + +void moduleSetProp1(const std::string& val) { + LOG("moduleSetProp1:%s", val.c_str()); + return; +} + + +const char* moduleGetProp1() { + LOG("moduleGetProp1"); + return "string as prop1 value"; +} + +int moduleSetProp2(int val) { + LOG("moduleSetProp2:%d", val); + return val; +} + +const char* moduleGetProp2() { + LOG("moduleGetProp2"); + return "string as prop2 value"; +} + + + +void bindToLUA(lua_State * L) +{ + // bind class to lua + LuaClass luaCat(L, "AwesomeCat"); + luaCat.ctor(); + luaCat.fun("setName", &Cat::setName); + luaCat.fun("getName", &Cat::getName); + luaCat.fun("setAge", &Cat::setAge); + luaCat.fun("getAge", &Cat::getAge); + luaCat.fun("eat", &Cat::eat); + luaCat.fun("speak", &Cat::speak); + luaCat.fun("test", &Cat::test); + luaCat.fun("testfunctor", &Cat::testfunctor); + luaCat.fun(std::string("testFunctor1"), [](int n1, int n2) -> int { + LOG("testFunctor1:%d, %d\n", n1, n2); + return n1 * n2; + }); + luaCat.fun("testFunctor2", std::function([](int n1, int n2) { + LOG("testFunctor2:%d, %d\n", n1, n2); + })); + luaCat.fun("__tostring", &Cat::toString); + luaCat.def("tag", "Animal"); + + luaCat.set("say", &Cat::speak); + luaCat.set("name", &Cat::setName); + luaCat.get("name", &Cat::getName); + luaCat.set("age", &Cat::setAge); + luaCat.get("age", &Cat::getAge); + + luaCat.set("prop1", setProp1); + luaCat.get("prop1", getProp1); + luaCat.set("prop2", [](const Cat& cat, float val) -> void { printf("set prop2=%f\n", val); /*cat.setWeight(val)*/; }); + luaCat.get("prop2", [](Cat& cat) -> float { printf("get prop2\n"); return cat.getWeight(); }); + luaCat.set(std::string("prop3"), [](Cat& cat, const std::set& val) { printf("set prop3\n"); cat.prop3 = val; }); + luaCat.get(std::string("prop3"), [](const Cat& cat) -> std::set { printf("get prop3\n"); return cat.prop3; }); + luaCat.set(std::string("prop4"), [](float val) { printf("set prop4=%f\n", val); }); + luaCat.get(std::string("prop4"), []() -> float { printf("get prop4\n"); return 0.123f; }); + + // rise compile error + //luaCat.set(std::string("prop5"), [](float val, int v2) { printf("set prop5=%f\n", val); }); + //luaCat.get(std::string("prop5"), [](int) -> float { printf("get prop5\n"); return 0.123f; }); + + + // bind singleton class to lua + LuaClass luaWorld(L, "SingletonWorld"); + /// use class default constructor as instance spawner, default destructor will be called from gc. + luaWorld.ctor(); + /// use class constructor as instance spawner, default destructor will be called from gc. + luaWorld.ctor("createWithName"); + /// use static function as instance spawner, default destructor will be called from gc. + luaWorld.ctor("newInstance", &SingletonWorld::newInstance); + /// use static function as instance spawner and static function as delete function which be called from gc. + luaWorld.ctor("managedInstance", &SingletonWorld::newInstance , &SingletonWorld::delInstance); + /// for singleton pattern, set deleter(gc) to nullptr to avoid singleton instance be destroyed. + luaWorld.ctor("getInstance", &SingletonWorld::getInstance, nullptr); + luaWorld.fun("getTag", &SingletonWorld::getTag); + + + // define a module with name "AwesomeMod" + LuaModule awesomeMod(L, "AwesomeMod"); + awesomeMod.def("cint", 20190101); + awesomeMod.def("cstr", "this is c string"); + awesomeMod.def("acat", luaCat); + + std::list dict { + "AMICUS", "AMOS", "AMTRAK", "ANGELICA", "ANNIE OAKLEY", + "BEETHOVEN", "BERTHA", "BESSEYA", "BILLIE JEAN", "BIMBO", + "BISS", "DECATHLON", "DELIRIUM", "DELIUS", "DEMPSEY" + }; + + awesomeMod.def("dict", dict); + + // c++11 standard conatiners(array, vector, deque, list, forward_list, set/multiset, map/multimap, unordered_set/unordered_multiset, unordered_map/unordered_multimap) + awesomeMod.fun("testSet", testSet); + awesomeMod.fun("testSetSet", testSetSet); + awesomeMod.fun("testMapMap", testMapMap); + awesomeMod.fun("testMultipleParams", testMultipleParams); + awesomeMod.fun("testTuple", testTuple); + awesomeMod.fun("testTuple2", testTuple2); + awesomeMod.fun("testCallback", testCallback); + awesomeMod.fun("testCallbackFunctor", testCallbackFunctor); + awesomeMod.fun("testPosition", testPosition); + awesomeMod.fun("testFunctor1", [](int a, float b) { + LOG("awesomeMod call testFunctor1: %d, %f", a, b); + }); + awesomeMod.fun("testFunctor2", [](int a, float b) -> float { + LOG("awesomeMod call testFunctor2(%d * %f = %f):", a, b, a*b); + return a * b; + }); + + awesomeMod.set("prop1", moduleSetProp1); + awesomeMod.get("prop1", moduleGetProp1); + awesomeMod.set("prop2", moduleSetProp2); + awesomeMod.get("prop2", moduleGetProp2); + awesomeMod.set(std::string("prop3"), [](const std::string& val) { printf("set prop3=%s\n", val.c_str()); }); + awesomeMod.get(std::string("prop3"), []() -> std::string { printf("get prop3\n"); return "string as prop3"; }); + awesomeMod.set(std::string("prop4"), [](float val) { printf("set prop4=%f\n", val); }); + awesomeMod.get(std::string("prop4"), [](){ printf("get prop4\n"); return 0.123f; }); + + awesomeMod.fun("__index", module__index); + awesomeMod.fun("__newindex", module__newindex); + + // put something to global, just emit the module name + LuaModule(L).def("pi", 3.1415926535897932); + + LuaModule(L).def("WITHOUT_CPP_STDLIB", !!LUAAA_WITHOUT_CPP_STDLIB); + + // operations can be chained. + LuaClass(L, "int") + .ctor("new") + .def("type", std::string("[c int *]")) + .def("max", INT_MAX) + .def("min", INT_MIN); + +} + diff --git a/third/luaaa/example/example.lua b/third/luaaa/example/example.lua new file mode 100644 index 00000000..239c5221 --- /dev/null +++ b/third/luaaa/example/example.lua @@ -0,0 +1,289 @@ + + +luaaa = {} +function luaaa:extend(base, obj) + derived = obj or {} + derived.new = function(self, ...) + o = base.new(...) + setmetatable(self, getmetatable(o)) + self["@"] = o + return self + end + return derived +end + +function luaaa:base(obj) + if (type(obj) == "table") then + return obj["@"] + end + return nil +end + + +function serialize(obj) + local str = "" + local t = type(obj) + if t == "number" then + str = str .. obj + elseif t == "boolean" then + str = str .. tostring(obj) + elseif t == "string" then + str = str .. obj + elseif t == "table" then + str = str .. "{" + for k, v in pairs(obj) do + str = str .. "[" .. serialize(k) .. "]=" .. serialize(v) .. "," + end + local metatable = getmetatable(obj) + if metatable ~= nil and type(metatable.__index) == "table" then + for k, v in pairs(metatable.__index) do + str = str .. "[" .. serialize(k) .. "]=" .. serialize(v) .. "," + end + end + str = str .. "}" + elseif t == "nil" then + str = "nil" + else + error("can not serialize a " .. t .. " type.") + end + return str +end + +function luaCallback(param) + return param + 1 +end + +function testAwesomeCat() + local a = AwesomeCat.new ("BINGO") + for key,value in pairs(getmetatable(a)) do + print(key, value) + end + + a:setAge(2); + print(a) + a:eat({"fish", "milk", "cookie", "rice"}); + print(a) + print("cat test: send params to c++: (0:0, 1:1, 2:2, 3:3, 4:4)"); + a:test(0, 1, 2, 3, 4) + a:speak("Thanks!") + if not WITHOUT_CPP_STDLIB then + print(a:testFunctor1(99999, 88888)) + print(a:testFunctor2(77777, 66666)) + a:testfunctor(luaCallback) + end + + a.say = "I am a cat!"; + a.age = 12 + print("=================== a.age:", a.age) + a.name = "HeroCat"; + print("=================== a.name:", a.name) + a.prop1 = "white"; + print("=================== a.prop1:", a.prop1) + if not WITHOUT_CPP_STDLIB then + a.prop2 = 9999123; + print("=================== a.prop2:", a.prop2) + a.prop3 = { 'aaa', 'bbb', 'ccc', 'ddd' }; + print("=================== a.prop3:", serialize(a.prop3)) + a.prop4 = 1.234; + print("=================== a.prop3:", a.prop4) + end + +end + +function testAwesomeMod() + print("===================before assign AwesomeMod.notexists:", AwesomeMod.notexists2) + AwesomeMod.notexists2 = "asdadsasda"; + print("=================== after assign AwesomeMod.notexists:", AwesomeMod.notexists2) + + AwesomeMod.prop1 = "white"; + print("=================== AwesomeMod.prop1:", AwesomeMod.prop1) + if not WITHOUT_CPP_STDLIB then + AwesomeMod.prop2 = 9999123; + print("=================== AwesomeMod.prop2:", AwesomeMod.prop2) + AwesomeMod.prop3 = "abcdefg"; + print("=================== AwesomeMod.prop3:", serialize(AwesomeMod.prop3)) + AwesomeMod.prop4 = 1.234; + print("=================== AwesomeMod.prop4:", AwesomeMod.prop4) + end + + print ("AwesomeMod.cint:" .. AwesomeMod.cint) + print ("AwesomeMod.cstr:" .. AwesomeMod.cstr) + print ("AwesomeMod.dict:") + for k,v in pairs(AwesomeMod.dict) do + print(tostring(k) .. "=" .. tostring(v)) + end + + print ("-------- AwesomeMod.testSet() --------") + AwesomeMod.testSet({11, 12, "13", 14, "15", 16, 17, 18, "2019", "2020"}, {5, 4, 3, 2, 1}); + + + print ("-------- AwesomeMod.testSetSet() --------") + AwesomeMod.testSetSet({ + {}, + {"what", "who", "where"}, + {797, 454, 828, "something"}, + {"alpha, beta", "gamma"} + }); + + print ("-------- AwesomeMod.testMapMap() --------") + AwesomeMod.testMapMap({ + animal = { + dog = "woof", + cat = "meow", + cow = "moo" + }, + rank = { + first = "Tom", + second = "Lee", + third = "Mike" + } + }); + + if not WITHOUT_CPP_STDLIB then + print("-------- AwesomeMod.testTuple() --------") + local values = AwesomeMod.testTuple({"a duck", 999, 1.234}) + print("Lua got multiple values from c++:") + for i = 1, #values do + print("[" .. i .. "]" .. values[i]) + end + + -- AwesomeMod.testTuple2() accept only empty tuple + local values2 = AwesomeMod.testTuple2({"a duck", 999, 1.234}) + print("Lua got empty tuple from c++.") + for k,v in pairs(values2) do + print("[" .. tostring(k) .. "]" .. tostring(v)) + end + end + + print("-------- AwesomeMod.testMultipleParams() --------") + AwesomeMod.testMultipleParams(0,1,"two",3.3,44.44) + + print("-------- AwesomeMod.testPosition() --------") + local positionA = { x = 100, y = 200, z = 300 } + local positionB = { x = 11, y = 22, z = 33 } + local result = AwesomeMod.testPosition(positionA, positionB) + print("positionA["..serialize(positionA).."] + positionB["..serialize(positionB).."] = "..serialize(result)) + + if not WITHOUT_CPP_STDLIB then + print("-------- AwesomeMod.testFunctor --------") + print(AwesomeMod.testFunctor1(123, 456.78)) + print(AwesomeMod.testFunctor2(789, 111.11)) + end + +end + + +function testCallback () + local f = function(a, b, c) + print ("lua testCallback:") + print (" param a:" .. tostring (a)) + print (" param b:" .. tostring (b)) + print (" param c:" .. tostring (c)) + print (" return b * b(" .. tostring(b * b) ..") as result to c++.\n") + return b * b; + end + + AwesomeMod.testCallback(f, 5555, "lua text") +end + +function testCallbackFunctor () + if not WITHOUT_CPP_STDLIB then + local f = function(a, b, c) + print ("lua testCallbackFunctor:") + print (" param a:" .. tostring (a)) + print (" param b:" .. tostring (b)) + print (" param c:" .. tostring (c)) + print (" return b * b(" .. tostring(b * b) ..") as result to c++.\n") + return b * b; + end + AwesomeMod.testCallbackFunctor(f, 8888, "lua text from testCallbackFunctor") + end + +end + +function testAutoGC () + local cat = AwesomeCat.new("IWILLLEAVE"); + cat:speak("I will leave ...") + cat = nil; + collectgarbage () +end + + +function testSingletonAndGC() + local world = SingletonWorld.new("chaos"); + print("new world tag:"..world:getTag()) + world = nil + collectgarbage() + + local world = SingletonWorld.getInstance(); + print("singleton world tag:"..world:getTag()) + world = nil + collectgarbage() + + + local world = SingletonWorld.newInstance("new instance"); + print("new world instance tag:"..world:getTag()) + world = nil + collectgarbage() + + local world=SingletonWorld.managedInstance("managed instance"); + print("managed world instance tag:"..world:getTag()) + world = nil + collectgarbage() +end + + +function testClassInheritance() + SpecialCat = luaaa:extend(AwesomeCat, {value = 1}) + + function SpecialCat:onlyInSpecial() + print(self:getName() .. " has a special cat function") + print(self:getName() .. " has value:" .. self.value) + end + + function SpecialCat:speak(text) + print("Special cat[" .. self:getName() .. "] says: " .. text) + end + + sss = SpecialCat:new("sss") + sss:onlyInSpecial() + sss:speak("I am Special Cat!") + print("call base class's method speak():") + luaaa:base(sss):speak("I am Special and Awesome Cat!") + +end + +print ("\nLUAAA_WITHOUT_CPP_STDLIB:", WITHOUT_CPP_STDLIB); + +print ("\n\n-- 1 --. Test auto GC\n") +testAutoGC(); + +print ("\n\n-- 2 --. Test AwesomeCat class\n") +testAwesomeCat(); + +print ("\n\n-- 3 --. Test AwesomeMod module\n") +testAwesomeMod (); + +print ("\n\n-- 4 --. Test others\n") +print ("pi = " .. pi .. "\n") + +print ("\n\n-- 5 --. Test Callback\n") +testCallback(); + +print ("\n\n-- 6 --. Test CallbackFunctor\n") +testCallbackFunctor(); + +print ("\n\n-- 7 --. Test Class Inheritance\n") +testClassInheritance(); + +print ("\n>>>>" .. collectgarbage ("count")) +collectgarbage () +print ("\n<<<<" .. collectgarbage ("count")) + +print("\n\n-- 8 --. Test Singleton and GC\n") +testSingletonAndGC() + +print("\n>>>>"..collectgarbage("count")) +collectgarbage() +print("\n<<<<"..collectgarbage("count")) + diff --git a/third/luaaa/luaaa.hpp b/third/luaaa/luaaa.hpp new file mode 100644 index 00000000..6ea435ef --- /dev/null +++ b/third/luaaa/luaaa.hpp @@ -0,0 +1,3362 @@ + +/* + Copyright (c) 2019 gengyong + https://github.com/gengyong/luaaa + licensed under MIT License. +*/ + +#ifndef HEADER_LUAAA_HPP +#define HEADER_LUAAA_HPP + +#define LUAAA_NS luaaa +#define LUAAA_VER_MAJOR (1) +#define LUAAA_VER_MINOR (4) + +/// if you want to disable C++ std libs, set to 1 +#ifndef LUAAA_WITHOUT_CPP_STDLIB +#define LUAAA_WITHOUT_CPP_STDLIB 0 +#endif + +#ifndef LUAAA_DEBUG +#define LUAAA_DEBUG 0 +#endif + +/// enable to check LuaClass constructor name conflict +/// exposed constructor should have unique name, otherwise the early one will be overwriten. +#ifndef LUAAA_CHECK_CONSTRUCTOR_NAME_CONFLICT +#define LUAAA_CHECK_CONSTRUCTOR_NAME_CONFLICT 1 +#endif + +#ifndef LUAAA_FEATURE_PROPERTY +#define LUAAA_FEATURE_PROPERTY 1 +#endif + +extern "C" +{ +#include "lua.h" +#include "lualib.h" +#include "lauxlib.h" +} + +#if !defined LUA_VERSION_NUM || LUA_VERSION_NUM <= 501 +inline void luaL_setfuncs(lua_State * L, const luaL_Reg * l, int nup) { + luaL_checkstack(L, nup + 1, "too many upvalues"); + for (; l->name != nullptr; l++) { + int i; + lua_pushstring(L, l->name); + for (i = 0; i < nup; i++) + lua_pushvalue(L, -(nup + 1)); + lua_pushcclosure(L, l->func, nup); + lua_settable(L, -(nup + 3)); + } + lua_pop(L, nup); +} + +inline void luaL_setmetatable(lua_State * L, const char * tname) { + luaL_getmetatable(L, tname); + lua_setmetatable(L, -2); +} +#endif + +#if defined(LUA_VERSION_NUM) && LUA_VERSION_NUM > 501 && !defined(LUA_COMPAT_MODULE) +# define USE_NEW_MODULE_REGISTRY 1 +#else +# define USE_NEW_MODULE_REGISTRY 0 +#endif + +#include +#include +#include + +#if defined(_MSC_VER) +# define RTTI_CLASS_NAME(a) typeid(a).name() //vc always has this operator even if RTTI was disabled. +#elif __GXX_RTTI +# define RTTI_CLASS_NAME(a) typeid(a).name() +#elif _HAS_STATIC_RTTI +# define RTTI_CLASS_NAME(a) typeid(a).name() +#else +# define RTTI_CLASS_NAME(a) "?" +#endif + +#if LUAAA_WITHOUT_CPP_STDLIB +# include +# include +#else +# if defined(__GNUC__) +# include +# endif +# include +# include +#endif + +#if LUAAA_DEBUG +inline size_t LUAAA_DUMP_OBJECT(char* buffer, size_t buflen, lua_State * L, int idx, int indent=0) { + char prefix[32] = {0}; + if (indent > sizeof(prefix) - 1) { + indent = sizeof(prefix) - 1; + } + for (int i = 0; i < indent; i++) { + prefix[i] = '\t'; + } + switch (lua_type(L, idx)) { + default: + return snprintf(buffer, buflen, "<%s>(%p)", luaL_typename(L, idx), lua_topointer(L, idx)); + case LUA_TNUMBER: + case LUA_TSTRING: + return snprintf(buffer, buflen, "\"%s\"", lua_tostring(L, idx)); + case LUA_TBOOLEAN: + return snprintf(buffer, buflen, "%s", (lua_toboolean(L, idx) ? "true" : "false")); + case LUA_TNIL: + return snprintf(buffer, buflen, "%s", "nil"); + case LUA_TTABLE: + int ret = 0; + if (luaL_getmetafield(L, idx, "__name")) { + ret = snprintf(buffer, buflen, "<%s>(%p):", lua_tostring(L, -1), lua_topointer(L, idx)); + lua_pop(L, 1); + } else { + ret = snprintf(buffer, buflen, "<%s>(%p):", luaL_typename(L, idx), lua_topointer(L, idx)); + } + if (ret > 0) { + size_t wrote = ret; + lua_pushnil(L); + while (lua_next(L, idx)) { + const int top = lua_gettop(L); + if (buflen > wrote) { + ret = snprintf(buffer + wrote, buflen - wrote, "\n%s", prefix); + if (ret > 0) { + wrote += ret; + } + } + + if (buflen > wrote) { + lua_pushvalue(L, top - 1); + ret = snprintf(buffer + wrote, buflen - wrote, "\"%s\":", lua_tostring(L, -1)); + lua_pop(L, 1); + if (ret > 0) { + wrote += ret; + } + } + + if (buflen > wrote) { + if (lua_topointer(L, top) == lua_topointer(L, idx)) { + ret = snprintf(buffer + wrote, buflen - wrote, "(%p)", lua_topointer(L, top)); + } else { + if (indent < 3) + { + ret = LUAAA_DUMP_OBJECT(buffer + wrote, buflen - wrote, L, top, indent + 1); + } + else + { + ret = snprintf(buffer + wrote, buflen - wrote, "..."); + } + } + if (ret > 0) { + wrote += ret; + } + } + lua_pop(L, 1); + } + //lua_pop(L, 0); + return wrote; + } + } + return 0; +} + +inline void LUAAA_DUMP(lua_State * L, const char * name = "") { + printf(">>>>>>>>>>>>>>>>>>>>>>>>>[%s]\n", name); + char buffer[4096] = {0}; + int top = lua_gettop(L); + for (int i = 1; i <= top; i++) { + LUAAA_DUMP_OBJECT(buffer, sizeof(buffer) - 1, L, i, 1); + printf("%d\t%s\n", i, buffer); + } + printf("<<<<<<<<<<<<<<<<<<<<<<<<<\n"); +} +#else +# define LUAAA_DUMP(L,...) +#endif + +#if LUAAA_CHECK_CONSTRUCTOR_NAME_CONFLICT +# define luaaa_check_constructor_name_conflict(ctorName) { \ + lua_getglobal(m_state, (LuaClass::klassName)); \ + if (!lua_isnil(m_state, -1)) { \ + lua_pushstring(m_state, ctorName); \ + lua_gettable(m_state, -2); \ + if (!lua_isnil(m_state, -1)) { \ + printf("Error: LuaClass<%s>::ctor has duplicated name:`%s`\n", LuaClass::klassName, ctorName);\ + } \ + lua_pop(m_state, 1); \ + } \ + lua_pop(m_state, 1); \ + } +#else +# define luaaa_check_constructor_name_conflict(ctorName) +#endif + +namespace LUAAA_NS +{ +#if !LUAAA_WITHOUT_CPP_STDLIB + // to_function + template + struct function_traits : public function_traits {}; + + template + struct function_traits + { + using function_type = std::function; + }; + + template + using function_type_t = typename function_traits::function_type; + + template + function_type_t to_function(F& f) + { + return static_cast>(f); + } + + // to_class_getter_function + template + struct class_getter_function_traits : public class_getter_function_traits {}; + + template + struct class_getter_function_traits + { + static_assert((sizeof...(ARGS) == 0) && (std::is_same::type, typename std::decay::type>::value), "Error: property getter does not accept param except current Class reference."); + using function_type = std::function; + }; + + template + struct class_getter_function_traits + { + using function_type = std::function; + }; + + template + using class_getter_function_type_t = typename class_getter_function_traits::function_type; + + template + class_getter_function_type_t to_class_getter_function(F& f) + { + return static_cast>(f); + } + + // to_class_setter_function + template + struct class_setter_function_traits : public class_setter_function_traits {}; + + + template + struct class_setter_function_traits + { + static_assert((sizeof...(ARGS) == 0) || ((sizeof...(ARGS) == 1) && std::is_same::type, typename std::decay::type>::value), "Error: property setter accepts only [1 value] or [self instance and 1 value]."); + using function_type = std::function; + }; + + template + struct class_setter_function_traits + { + using function_type = std::function; + }; + + template + using class_setter_function_type_t = typename class_setter_function_traits::function_type; + + template + class_setter_function_type_t to_class_setter_function(F& f) + { + return static_cast>(f); + } + + // to_module_getter_function + template + struct module_getter_function_traits : public module_getter_function_traits {}; + + template + struct module_getter_function_traits + { + static_assert((sizeof...(ARGS) == 0), "Error: property getter does not accept param."); + using function_type = std::function; + }; + + template + struct module_getter_function_traits + { + static_assert((sizeof...(ARGS) == 0), "Error: property getter does not accept param."); + using function_type = std::function; + }; + + template + using module_getter_function_type_t = typename module_getter_function_traits::function_type; + + template + module_getter_function_type_t to_module_getter_function(F& f) + { + return static_cast>(f); + } + + // to_module_setter_function + template + struct module_setter_function_traits : public module_setter_function_traits {}; + + template + struct module_setter_function_traits + { + static_assert((sizeof...(ARGS) == 0), "Error: property setter accepts only 1 value."); + using function_type = std::function; + }; + + template + struct module_setter_function_traits + { + static_assert((sizeof...(ARGS) == 0), "Error: property setter accepts only 1 value."); + using function_type = std::function; + }; + + template + using module_setter_function_type_t = typename module_setter_function_traits::function_type; + + template + module_setter_function_type_t to_module_setter_function(F& f) + { + return static_cast>(f); + } +#endif + + //======================================================== + // Lua Class + //======================================================== + + template struct LuaClass; + + //======================================================== + // Lua stack operator + //======================================================== + + template struct LuaStack + { + inline static T& get(lua_State * state, int idx) + { +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(state, LuaClass::klassName != nullptr, 1, "cpp class not export"); +#else + luaL_argcheck(state, LuaClass::klassName != nullptr, 1, (std::string("cpp class `") + RTTI_CLASS_NAME(T) + "` not export").c_str()); +#endif + if (lua_istable(state, idx)) { +#if !defined LUA_VERSION_NUM || LUA_VERSION_NUM <= 502 + if (lua_getmetatable(state, idx)) { + lua_getfield(state, LUA_REGISTRYINDEX, LuaClass::klassName); + if (lua_rawequal(state, -1, -2)) { + lua_getfield(state, idx, "@"); + if (lua_type(state, -1) == LUA_TUSERDATA) { + T ** t = (T**)luaL_checkudata(state, -1, LuaClass::klassName); + luaL_argcheck(state, t != nullptr && *t != nullptr, 1, "invalid user data"); + return (**t); + } + } + } +#else + if (luaL_getmetafield(state, idx, "__name") == LUA_TSTRING) { + if (LuaClass::klassName && strcmp(lua_tostring(state, -1), LuaClass::klassName) == 0) { + if (lua_getfield(state, idx, "@") == LUA_TUSERDATA) { + T ** t = (T**)luaL_checkudata(state, -1, LuaClass::klassName); + luaL_argcheck(state, t != nullptr && *t != nullptr, 1, "invalid user data"); + return (**t); + } + } + } +#endif + } + T ** t = (T**)luaL_checkudata(state, idx, LuaClass::klassName); + luaL_argcheck(state, t != nullptr && *t != nullptr, 1, "invalid user data"); + return (**t); + } + + inline static void put(lua_State * L, T * t) + { + lua_pushlightuserdata(L, t); + } + }; + + template struct LuaStack : public LuaStack {}; + template struct LuaStack : public LuaStack {}; + template struct LuaStack : public LuaStack {}; + + template struct LuaStack : public LuaStack + { + inline static void put(lua_State * L, volatile T & t) + { + LuaStack::put(L, const_cast(t)); + } + }; + + template struct LuaStack : public LuaStack + { + inline static void put(lua_State * L, const volatile T & t) + { + LuaStack::put(L, const_cast(t)); + } + }; + + template struct LuaStack : public LuaStack + { + inline static void put(lua_State * L, T && t) + { + LuaStack::put(L, std::forward(t)); + } + }; + + template struct LuaStack + { + inline static T * get(lua_State * state, int idx) + { + if (lua_islightuserdata(state, idx)) + { + T * t = (T*)lua_touserdata(state, idx); + return t; + } + else if (lua_isuserdata(state, idx)) + { + if (LuaClass::klassName != nullptr) + { + T ** t = (T**)luaL_checkudata(state, idx, LuaClass::klassName); + luaL_argcheck(state, t != nullptr && *t != nullptr, 1, "invalid user data"); + return *t; + } + if (LuaClass::klassName != nullptr) + { + T ** t = (T**)luaL_checkudata(state, idx, LuaClass::klassName); + luaL_argcheck(state, t != nullptr && *t != nullptr, 1, "invalid user data"); + return *t; + } + } + return nullptr; + } + + inline static void put(lua_State * L, T * t) + { + lua_pushlightuserdata(L, t); + } + }; + + template<> + struct LuaStack + { + inline static float get(lua_State * L, int idx) + { + if (lua_isnumber(L, idx) || lua_isstring(L, idx)) + { + return float(lua_tonumber(L, idx)); + } + else + { + luaL_checktype(L, idx, LUA_TNUMBER); + } + return 0; + } + + inline static void put(lua_State * L, const float & t) + { + lua_pushnumber(L, t); + } + }; + + template<> + struct LuaStack + { + inline static double get(lua_State * L, int idx) + { + if (lua_isnumber(L, idx) || lua_isstring(L, idx)) + { + return double(lua_tonumber(L, idx)); + } + else + { + luaL_checktype(L, idx, LUA_TNUMBER); + } + return 0; + } + + inline static void put(lua_State * L, const double & t) + { + lua_pushnumber(L, t); + } + }; + + template<> + struct LuaStack + { + inline static int get(lua_State * L, int idx) + { + if (lua_isnumber(L, idx) || lua_isstring(L, idx)) + { + return int(lua_tointeger(L, idx)); + } + else + { + luaL_checktype(L, idx, LUA_TNUMBER); + } + return 0; + } + + inline static void put(lua_State * L, const int & t) + { + lua_pushinteger(L, t); + } + }; + + template<> + struct LuaStack + { + inline static bool get(lua_State * L, int idx) + { + luaL_checktype(L, idx, LUA_TBOOLEAN); + return lua_toboolean(L, idx) != 0; + } + + inline static void put(lua_State * L, const bool & t) + { + lua_pushboolean(L, t); + } + }; + + template<> + struct LuaStack + { + inline static const char * get(lua_State * L, int idx) + { + switch (lua_type(L, idx)) + { + case LUA_TBOOLEAN: + return (lua_toboolean(L, idx) ? "true" : "false"); + case LUA_TNUMBER: + return lua_tostring(L, idx); + case LUA_TSTRING: + return lua_tostring(L, idx); + default: + luaL_checktype(L, idx, LUA_TSTRING); + break; + } + return ""; + } + + inline static void put(lua_State * L, const char * s) + { + lua_pushstring(L, s); + } + }; + + template<> + struct LuaStack + { + inline static char * get(lua_State * L, int idx) + { + return const_cast(LuaStack::get(L, idx)); + } + + inline static void put(lua_State * L, const char * s) + { + LuaStack::put(L, s); + } + }; + +#if !LUAAA_WITHOUT_CPP_STDLIB + template<> + struct LuaStack + { + inline static std::string get(lua_State * L, int idx) + { + return LuaStack::get(L, idx); + } + + inline static void put(lua_State * L, const std::string& s) + { + LuaStack::put(L, s.c_str()); + } + }; +#endif + + template<> + struct LuaStack + { + inline static lua_State * get(lua_State * L, int) + { + return L; + } + + inline static void put(lua_State *, lua_State *) + { + // do thing here. + } + }; + + // push ret data to stack + template + inline void LuaStackReturn(lua_State * L, T t) + { + lua_settop(L, 0); + LuaStack::put(L, t); + } + + +#define IMPLEMENT_CALLBACK_INVOKER(CALLCONV) \ + template \ + struct LuaStack \ + { \ + typedef RET(CALLCONV*FTYPE)(ARGS...); \ + inline static FTYPE get(lua_State * L, int idx) \ + { \ + static lua_State * cacheLuaState = nullptr; \ + static int cacheLuaFuncId = 0; \ + struct HelperClass \ + { \ + static RET CALLCONV f_callback(ARGS... args) \ + { \ + lua_rawgeti(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); \ + if (lua_isfunction(cacheLuaState, -1)) \ + { \ + int initParams[] = { (LuaStack::put(cacheLuaState, args), 0)..., 0 }; (void)initParams; \ + if (lua_pcall(cacheLuaState, sizeof...(ARGS), 1, 0) != 0) \ + { \ + lua_error(cacheLuaState); \ + } \ + luaL_unref(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); \ + } \ + else \ + { \ + lua_pushnil(cacheLuaState); \ + } \ + return LuaStack::get(cacheLuaState, lua_gettop(cacheLuaState)); \ + } \ + }; \ + if (lua_isfunction(L, idx)) \ + { \ + cacheLuaState = L; \ + lua_pushvalue(L, idx); \ + cacheLuaFuncId = luaL_ref(L, LUA_REGISTRYINDEX); \ + return HelperClass::f_callback; \ + } \ + return nullptr; \ + } \ + inline void put(lua_State * L, FTYPE f) \ + { \ + lua_pushcfunction(L, NonMemberFunctionCaller(f)); \ + } \ + }; \ + template \ + struct LuaStack \ + { \ + typedef void(CALLCONV*FTYPE)(ARGS...); \ + inline static FTYPE get(lua_State * L, int idx) \ + { \ + static lua_State * cacheLuaState = nullptr; \ + static int cacheLuaFuncId = 0; \ + struct HelperClass \ + { \ + static void CALLCONV f_callback(ARGS... args) \ + { \ + lua_rawgeti(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); \ + if (lua_isfunction(cacheLuaState, -1)) \ + { \ + int initParams[] = { (LuaStack::put(cacheLuaState, args), 0)..., 0 }; (void)initParams; \ + if (lua_pcall(cacheLuaState, sizeof...(ARGS), 1, 0) != 0) \ + { \ + lua_error(cacheLuaState); \ + } \ + luaL_unref(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); \ + } \ + return; \ + } \ + }; \ + if (lua_isfunction(L, idx)) \ + { \ + cacheLuaState = L; \ + lua_pushvalue(L, idx); \ + cacheLuaFuncId = luaL_ref(L, LUA_REGISTRYINDEX); \ + return HelperClass::f_callback; \ + } \ + return nullptr; \ + } \ + inline void put(lua_State * L, FTYPE f) \ + { \ + lua_pushcfunction(L, NonMemberFunctionCaller(f)); \ + } \ + }; + +#if !LUAAA_WITHOUT_CPP_STDLIB + template + struct LuaStack> + { + typedef std::function FTYPE; + inline static FTYPE get(lua_State * L, int idx) + { + static lua_State * cacheLuaState = nullptr; + static int cacheLuaFuncId = 0; + struct HelperClass + { + static RET f_callback(ARGS... args) + { + lua_rawgeti(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); + if (lua_isfunction(cacheLuaState, -1)) + { + int initParams[] = { (LuaStack::put(cacheLuaState, args), 0)..., 0 }; (void)initParams; + if (lua_pcall(cacheLuaState, sizeof...(ARGS), 1, 0) != 0) + { + lua_error(cacheLuaState); + } + luaL_unref(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); + } + else + { + lua_pushnil(cacheLuaState); + } + return LuaStack::get(cacheLuaState, lua_gettop(cacheLuaState)); + } + }; + if (lua_isfunction(L, idx)) + { + cacheLuaState = L; + lua_pushvalue(L, idx); + cacheLuaFuncId = luaL_ref(L, LUA_REGISTRYINDEX); + return HelperClass::f_callback; + } + return nullptr; + } + inline void put(lua_State * L, FTYPE f) + { + lua_pushcfunction(L, NonMemberFunctionCaller(f)); + } + }; + + template + struct LuaStack> + { + typedef std::function FTYPE; + inline static FTYPE get(lua_State * L, int idx) + { + static lua_State * cacheLuaState = nullptr; + static int cacheLuaFuncId = 0; + struct HelperClass + { + static void f_callback(ARGS... args) + { + lua_rawgeti(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); + if (lua_isfunction(cacheLuaState, -1)) + { + int initParams[] = { (LuaStack::put(cacheLuaState, args), 0)..., 0 }; + if (lua_pcall(cacheLuaState, sizeof...(ARGS), 1, 0) != 0) + { + lua_error(cacheLuaState); + } + luaL_unref(cacheLuaState, LUA_REGISTRYINDEX, cacheLuaFuncId); + } + return; + } + }; + if (lua_isfunction(L, idx)) + { + cacheLuaState = L; + lua_pushvalue(L, idx); + cacheLuaFuncId = luaL_ref(L, LUA_REGISTRYINDEX); + return HelperClass::f_callback; + } + return nullptr; + } + inline void put(lua_State * L, FTYPE f) + { + lua_pushcfunction(L, NonMemberFunctionCaller(f)); + } + }; +#endif + + //======================================================== + // index generation helper + //======================================================== + template + struct indices + { + using next = indices; + }; + + template + struct make_indices + { + using type = typename make_indices::type::next; + }; + + template<> + struct make_indices<0> + { + using type = indices<>; + }; + + //======================================================== + // non-member function caller & static member function caller + //======================================================== + template + TRET LuaInvokeImpl(lua_State* state, void* calleePtr, size_t skip, indices) + { + return (*(FTYPE*)(calleePtr))(LuaStack::get(state, Ns + 1 + skip)...); + } + + template + inline TRET LuaInvoke(lua_State* state, void* calleePtr, size_t skip) + { + return LuaInvokeImpl(state, calleePtr, skip, typename make_indices::type()); + } + + +#define IMPLEMENT_FUNCTION_CALLER(CALLERNAME, CALLCONV, SKIPPARAM) \ + template \ + lua_CFunction CALLERNAME(TRET(CALLCONV*func)(ARGS...)) \ + { \ + typedef decltype(func) FTYPE; (void)(func); \ + struct HelperClass \ + { \ + static int Invoke(lua_State* state) \ + { \ + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); \ + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); \ + if (calleePtr) \ + { \ + LuaStackReturn(state, LuaInvoke(state, calleePtr, SKIPPARAM)); \ + return 1; \ + } \ + return 0; \ + } \ + }; \ + return HelperClass::Invoke; \ + } \ + template \ + lua_CFunction CALLERNAME(void(CALLCONV*func)(ARGS...)) \ + { \ + typedef decltype(func) FTYPE; (void)(func); \ + struct HelperClass \ + { \ + static int Invoke(lua_State* state) \ + { \ + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); \ + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); \ + if (calleePtr) \ + { \ + LuaInvoke(state, calleePtr, SKIPPARAM); \ + } \ + return 0; \ + } \ + }; \ + return HelperClass::Invoke; \ + } + +#if defined(_MSC_VER) + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, __cdecl, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, __cdecl, 1); + IMPLEMENT_CALLBACK_INVOKER(__cdecl); + +# ifdef _M_CEE + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, __clrcall, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, __clrcall, 1); + IMPLEMENT_CALLBACK_INVOKER(__clrcall); +# endif + +# if defined(_M_IX86) && !defined(_M_CEE) + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, __fastcall, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, __fastcall, 1); + IMPLEMENT_CALLBACK_INVOKER(__fastcall); +# endif + +# ifdef _M_IX86 + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, __stdcall, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, __stdcall, 1); + IMPLEMENT_CALLBACK_INVOKER(__stdcall); +# endif + +# if ((defined(_M_IX86) && _M_IX86_FP >= 2) || defined(_M_X64)) && !defined(_M_CEE) + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, __vectorcall, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, __vectorcall, 1); + IMPLEMENT_CALLBACK_INVOKER(__vectorcall); +# endif +#elif defined(__clang__) +# define _NOTHING + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, _NOTHING, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, _NOTHING, 1); + IMPLEMENT_CALLBACK_INVOKER(_NOTHING); +# undef _NOTHING +#elif defined(__GNUC__) +# define _NOTHING + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, _NOTHING, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, _NOTHING, 1); + IMPLEMENT_CALLBACK_INVOKER(_NOTHING); +# undef _NOTHING +#else +# define _NOTHING + IMPLEMENT_FUNCTION_CALLER(NonMemberFunctionCaller, _NOTHING, 0); + IMPLEMENT_FUNCTION_CALLER(MemberFunctionCaller, _NOTHING, 1); + IMPLEMENT_CALLBACK_INVOKER(_NOTHING); +# undef _NOTHING +#endif + + //======================================================== + // member function invoker + //======================================================== + template + TRET LuaInvokeInstanceMemberImpl(lua_State* state, void* calleePtr, indices) + { + return (LuaStack::get(state, 1).**(FTYPE*)(calleePtr))(LuaStack::get(state, Ns + 2)...); + } + + template + inline TRET LuaInvokeInstanceMember(lua_State* state, void* calleePtr) + { + return LuaInvokeInstanceMemberImpl(state, calleePtr, typename make_indices::type()); + } + + + template + lua_CFunction MemberFunctionCaller(TRET(TCLASS::*func)(ARGS...)) + { + typedef decltype(func) FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaStackReturn(state, LuaInvokeInstanceMember(state, calleePtr)); + return 1; + } + return 0; + } + }; + return HelperClass::Invoke; + } + + template + lua_CFunction MemberFunctionCaller(TRET(TCLASS::*func)(ARGS...)const) + { + typedef decltype(func) FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaStackReturn(state, LuaInvokeInstanceMember(state, calleePtr)); + return 1; + } + return 0; + } + }; + return HelperClass::Invoke; + } + + template + lua_CFunction MemberFunctionCaller(void(TCLASS::*func)(ARGS...)) + { + typedef decltype(func) FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaInvokeInstanceMember(state, calleePtr); + } + return 0; + } + }; + return HelperClass::Invoke; + } + + template + lua_CFunction MemberFunctionCaller(void(TCLASS::*func)(ARGS...)const) + { + typedef decltype(func) FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaInvokeInstanceMember(state, calleePtr); + } + return 0; + } + }; + return HelperClass::Invoke; + } + +#if !LUAAA_WITHOUT_CPP_STDLIB + template + lua_CFunction MemberFunctionCaller(const std::function& func) + { + typedef std::function FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaStackReturn(state, LuaInvoke(state, calleePtr, 1)); + return 1; + } + return 0; + } + }; + return HelperClass::Invoke; + } + + template + lua_CFunction MemberFunctionCaller(const std::function& func) + { + typedef std::function FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaInvoke(state, calleePtr, 1); + } + return 0; + } + }; + return HelperClass::Invoke; + } + + template + lua_CFunction NonMemberFunctionCaller(const std::function& func) + { + typedef std::function FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaStackReturn(state, LuaInvoke(state, calleePtr, 0)); + return 1; + } + return 0; + } + }; + return HelperClass::Invoke; + } + + template + lua_CFunction NonMemberFunctionCaller(const std::function& func) + { + typedef std::function FTYPE; (void)(func); + struct HelperClass + { + static int Invoke(lua_State* state) + { + void * calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, calleePtr, 1, "cpp closure function not found."); + if (calleePtr) + { + LuaInvoke(state, calleePtr, 0); + } + return 0; + } + }; + return HelperClass::Invoke; + } +#endif + + //======================================================== + // constructor invoker + //======================================================== + template + struct PlacementConstructorCaller + { + static TCLASS * Invoke(lua_State * state, void * mem, size_t skip) + { + return InvokeImpl(state, mem, typename make_indices::type(), skip); + } + + private: + template + static TCLASS * InvokeImpl(lua_State * state, void * mem, indices, size_t skip) + { + return new(mem) TCLASS(LuaStack::get(state, Ns + 1 + skip)...); + } + }; + + //======================================================== + // Destructor invoker + //======================================================== + template::value> + struct DestructorCaller + { + static void Invoke(TCLASS * obj) + { + delete obj; + } + }; + + template + struct DestructorCaller + { + static void Invoke(TCLASS * obj) + { + // do thing here. + } + }; + + //======================================================== + // export class + //======================================================== + template + struct LuaClass + { + friend struct DestructorCaller; + template friend struct LuaStack; + friend struct LuaModule; + + typedef struct _UserDataDetail { + TCLASS * obj; + int (*dtor)(_UserDataDetail*); + void* free_func; + } UserDataDetail; + + public: + LuaClass(lua_State * state, const char * name, const luaL_Reg * functions = nullptr) + : m_state(state) + { + assert(state != nullptr); + assert(klassName == nullptr); + +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(state, (klassName == nullptr), 1, "LuaCalss name conflict, use LuaClass to identify them"); +#else + luaL_argcheck(state, (klassName == nullptr), 1, (std::string("C++ class `") + RTTI_CLASS_NAME(TCLASS) + "` bind to conflict lua name `" + name + "`, origin name: `" + klassName + "`. use use LuaClass to identify them.").c_str()); +#endif + + struct HelperClass { + static int f__clsgc(lua_State*) { + LuaClass::klassName = nullptr; + return 0; + } + + static int f__objgc(lua_State* state) { + if (lua_isuserdata(state, -1)) { + auto uData = (UserDataDetail*)luaL_checkudata(state, -1, (LuaClass::klassName)); + if (uData) + { + lua_getmetatable(state, -1); + lua_getfield(state, -1, "!__gc"); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 0, 0); + } + + if (uData->dtor) + { + return (uData->dtor)(uData); + } + } + } + return 0; + } + +#if LUAAA_FEATURE_PROPERTY + static int f_internal_index(lua_State* state) + { + const char* key = luaL_checkstring(state, 2); + if (!key) + { + lua_pushnil(state); + return 1; + } + + lua_getmetatable(state, 1); + lua_getfield(state, -1, key); + if (!lua_isnil(state, -1)) + { + return 1; + } + + lua_pop(state, 1); + + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), "<%s", key); + + lua_getfield(state, -1, internal_name); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 1, 0); + } + else if (lua_isnil(state, -1)) + { + // check if user defined __index method + lua_pop(state, 1); + lua_getfield(state, -1, "!__index"); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 0, 0); + } + else if (lua_istable(state, -1)) + { + lua_replace(state, 1); + lua_pop(state, 1); + lua_rawget(state, 1); + } + else + { + lua_pop(state, 1); + snprintf(internal_name, sizeof(internal_name), ">%s", key); + lua_getfield(state, -1, internal_name); + if (lua_isfunction(state, -1)) + { + // Yes, there are something write-only, e.g., stdout, printer, digital io pin in output mode. + luaL_error(state, "attempt to read Write-Only property '%s' of '%s'", key, LuaClass::klassName); + } + else + { + // do nothing here. nil will be return. + // luaL_error(state, "attempt to access Non-existing property '%s' of '%s'", key, LuaClass::klassName); + } + } + } + return 1; + } + + static int f_internal_newindex(lua_State* state) + { + const char* key = luaL_checkstring(state, 2); + if (!key) + { + lua_pushnil(state); + return 1; + } + + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), ">%s", key); + + + lua_getmetatable(state, 1); + lua_getfield(state, -1, internal_name); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 0, 0); + } + else if (lua_istable(state, 1)) // if is extended lua class + { + lua_pop(state, 2); + lua_rawset(state, 1); + } + else + { + // check if user defined __newindex method + lua_pop(state, 1); + lua_getfield(state, -1, "!__newindex"); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 0, 0); + } + else if (lua_istable(state, -1)) + { + lua_replace(state, 1); + lua_pop(state, 1); + lua_rawset(state, 1); + } + else + { + lua_pop(state, 1); + snprintf(internal_name, sizeof(internal_name), "<%s", key); + lua_getfield(state, -1, internal_name); + if (lua_isfunction(state, -1)) + { + luaL_error(state, "attempt to write Read-Only property '%s' of '%s'", key, LuaClass::klassName); + } + else + { + luaL_error(state, "attempt to access Non-existing property '%s' of '%s'", key, LuaClass::klassName); + } + } + } + return 0; + } +#endif + }; + + size_t strBufLen = strlen(name) + 1; + klassName = reinterpret_cast(lua_newuserdata(state, strBufLen + 1)); + memcpy(klassName, name, strBufLen); + + klassName[strBufLen - 1] = '$'; + klassName[strBufLen] = 0; + luaL_newmetatable(state, klassName); + luaL_Reg clsgc[] = { { "__gc", HelperClass::f__clsgc }, { nullptr, nullptr } }; + luaL_setfuncs(state, clsgc, 0); + lua_setmetatable(state, -2); + + klassName[strBufLen - 1] = 0; + luaL_newmetatable(state, klassName); + luaL_Reg objgc[] = { + { "__gc", HelperClass::f__objgc }, +#if LUAAA_FEATURE_PROPERTY + { "__index", HelperClass::f_internal_index }, + { "__newindex", HelperClass::f_internal_newindex }, +#endif + { nullptr, nullptr } + }; + luaL_setfuncs(state, objgc, 0); + +#if !LUAAA_FEATURE_PROPERTY + // if not register __index function, uncomment below codes + lua_pushvalue(state, -1); + lua_setfield(state, -2, "__index"); +#endif + + lua_pushvalue(state, -2); + lua_setfield(state, -2, "$"); + + if (functions) + { + luaL_setfuncs(state, functions, 0); + } + + lua_pop(state, 2); + } + +#if !LUAAA_WITHOUT_CPP_STDLIB + LuaClass(lua_State * state, const std::string& name, const luaL_Reg * functions = nullptr) + : LuaClass(state, name.c_str(), functions) + {} +#endif + + template + inline LuaClass& ctor(const char * name = "new") + { + struct HelperClass { + static int f_dtor(typename LuaClass::UserDataDetail * uData) { + if (uData && uData->obj) + { + (uData->obj)->~TCLASS(); + } + return 0; + } + + static int f_new(lua_State* state) { + auto uData = (typename LuaClass::UserDataDetail*)lua_newuserdata(state, sizeof(LuaClass::UserDataDetail) + sizeof(TCLASS)); + if (uData) + { + TCLASS * obj = PlacementConstructorCaller::Invoke(state, (void*)(uData + 1), 0); + if (obj) + { + uData->obj = obj; + uData->dtor = HelperClass::f_dtor; + luaL_setmetatable(state, (LuaClass::klassName)); + return 1; + } + lua_pop(state, 1); + } + lua_pushnil(state); + return 1; + } + }; + + luaaa_check_constructor_name_conflict(name); + + luaL_Reg constructor[] = { { name, HelperClass::f_new }, { nullptr, nullptr } }; +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, klassName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + } + luaL_setfuncs(m_state, constructor, 0); + lua_setglobal(m_state, klassName); +#else + luaL_openlib(m_state, klassName, constructor, 0); +#endif + return (*this); + } + + template + inline LuaClass& ctor(const char * name, TCLASS*(*spawner)(ARGS...)) { + typedef decltype(spawner) SPAWNERFTYPE; + struct HelperClass { + static int f_dtor(typename LuaClass::UserDataDetail* uData) { + if (uData && uData->obj) + { + DestructorCaller::Invoke(uData->obj); + } + return 0; + } + + static int f_new(lua_State* state) { + void * spawner = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, spawner, 1, "cpp closure spawner not found."); + if (spawner) { + auto uData = (typename LuaClass::UserDataDetail*)lua_newuserdata(state, sizeof(LuaClass::UserDataDetail)); + if (uData) + { + auto obj = LuaInvoke(state, spawner, 0); + if (obj) + { + uData->obj = obj; + uData->dtor = HelperClass::f_dtor; + luaL_setmetatable(state, (LuaClass::klassName)); + return 1; + } + lua_pop(state, 1); + } + } + lua_pushnil(state); + return 1; + } + }; + + luaaa_check_constructor_name_conflict(name); + + luaL_Reg constructor[] = { { name, HelperClass::f_new }, { nullptr, nullptr } }; +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, klassName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + } +#endif + + SPAWNERFTYPE * spawnerPtr = (SPAWNERFTYPE*)lua_newuserdata(m_state, sizeof(SPAWNERFTYPE)); +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, spawnerPtr != nullptr, 1, "faild to alloc mem to store spawner for ctor"); +#else + luaL_argcheck(m_state, spawnerPtr != nullptr, 1, (std::string("faild to alloc mem to store spawner for ctor `") + name + "`").c_str()); +#endif + if (!spawnerPtr) + { + lua_pop(m_state, 1); + return (*this); + } + + memset(spawnerPtr, 0, sizeof(SPAWNERFTYPE)); + *spawnerPtr = spawner; + +#if USE_NEW_MODULE_REGISTRY + luaL_setfuncs(m_state, constructor, 1); + lua_setglobal(m_state, klassName); +#else + luaL_openlib(m_state, klassName, constructor, 1); +#endif + return (*this); + } + + template + inline LuaClass& ctor(const char * name, TCLASS*(*spawner)(ARGS...), TRET(*deleter)(TCLASS*)){ + typedef decltype(spawner) SPAWNERFTYPE; + typedef decltype(deleter) DELETERFTYPE; + + struct HelperClass { + static int f_dtor(typename LuaClass::UserDataDetail* uData) { + if (uData && uData->obj && uData->free_func) + { + (*(DELETERFTYPE*)(uData->free_func))(uData->obj); + } + return 0; + } + + static int f_new(lua_State* state) { + void * spawner = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, spawner, 1, "cpp closure spawner not found."); + + void * deleter = lua_touserdata(state, lua_upvalueindex(2)); + luaL_argcheck(state, deleter, 2, "cpp closure deleter not found."); + + if (spawner) { + auto uData = (typename LuaClass::UserDataDetail*)lua_newuserdata(state, sizeof(LuaClass::UserDataDetail)); + if (uData) + { + auto obj = LuaInvoke(state, spawner, 0); + if (obj) + { + uData->obj = obj; + uData->dtor = HelperClass::f_dtor; + uData->free_func = deleter; + luaL_setmetatable(state, (LuaClass::klassName)); + return 1; + } + lua_pop(state, 1); + } + } + lua_pushnil(state); + return 1; + } + }; + +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, klassName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + } +#endif + + SPAWNERFTYPE * spawnerPtr = (SPAWNERFTYPE*)lua_newuserdata(m_state, sizeof(SPAWNERFTYPE)); +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, spawnerPtr != nullptr, 0, ("faild to alloc mem to store spawner for ctor")); +#else + luaL_argcheck(m_state, spawnerPtr != nullptr, 0, (std::string("faild to alloc mem to store spawner for ctor `") + name + "`").c_str()); +#endif + if (!spawnerPtr) + { + lua_pop(m_state, 2); + return (*this); + } + + memset(spawnerPtr, 0, sizeof(SPAWNERFTYPE)); + *spawnerPtr = spawner; + + DELETERFTYPE * deleterPtr = (DELETERFTYPE*)lua_newuserdata(m_state, sizeof(DELETERFTYPE)); +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, deleterPtr != nullptr, 0, ("faild to alloc mem to store deleter for ctor")); +#else + luaL_argcheck(m_state, deleterPtr != nullptr, 0, (std::string("faild to alloc mem to store deleter for ctor `") + name + "`").c_str()); +#endif + if (!deleterPtr) + { + lua_pop(m_state, 3); + return (*this); + } + + memset(deleterPtr, 0, sizeof(DELETERFTYPE)); + *deleterPtr = deleter; + + luaL_Reg constructor[] = { { name, HelperClass::f_new }, { nullptr, nullptr } }; +#if USE_NEW_MODULE_REGISTRY + luaL_setfuncs(m_state, constructor, 2); + lua_setglobal(m_state, klassName); +#else + luaL_openlib(m_state, klassName, constructor, 2); +#endif + return (*this); + } + + template + inline LuaClass& ctor(const char * name, TCLASS*(*spawner)(ARGS...), std::nullptr_t) { + typedef decltype(spawner) SPAWNERFTYPE; + + struct HelperClass { + static int f_new(lua_State* state) { + void * spawner = lua_touserdata(state, lua_upvalueindex(1)); + luaL_argcheck(state, spawner, 1, "cpp closure spawner not found."); + if (spawner) { + auto uData = (typename LuaClass::UserDataDetail*)lua_newuserdata(state, sizeof(LuaClass::UserDataDetail)); + if (uData) + { + auto obj = LuaInvoke(state, spawner, 0); + if (obj) + { + uData->obj = obj; + uData->dtor = nullptr; + luaL_setmetatable(state, (LuaClass::klassName)); + return 1; + } + lua_pop(state, 1); + } + } + lua_pushnil(state); + return 1; + } + + }; + + luaaa_check_constructor_name_conflict(name); + +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, klassName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + } +#endif + SPAWNERFTYPE * spawnerPtr = (SPAWNERFTYPE*)lua_newuserdata(m_state, sizeof(SPAWNERFTYPE)); +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, spawnerPtr != nullptr, 1, "faild to alloc mem to store spawner for ctor of cpp class"); +#else + luaL_argcheck(m_state, spawnerPtr != nullptr, 1, (std::string("faild to alloc mem to store spawner for ctor `") + name + "`").c_str()); +#endif + if (!spawnerPtr) + { + lua_pop(m_state, 1); + return (*this); + } + + memset(spawnerPtr, 0, sizeof(SPAWNERFTYPE)); + *spawnerPtr = spawner; + + luaL_Reg constructor[] = { { name, HelperClass::f_new }, { nullptr, nullptr } }; +#if USE_NEW_MODULE_REGISTRY + luaL_setfuncs(m_state, constructor, 1); + lua_setglobal(m_state, klassName); +#else + luaL_openlib(m_state, klassName, constructor, 1); +#endif + return (*this); + } + + +#if !LUAAA_WITHOUT_CPP_STDLIB + template + inline LuaClass& ctor(const std::string& name) + { + return ctor(name.c_str()); + } + + template + inline LuaClass& ctor(const std::string& name, TCLASS*(*spawner)(ARGS...)) { + return ctor(name.c_str(), spawner); + } + + template + inline LuaClass& ctor(const std::string& name, TCLASS*(*spawner)(ARGS...), TRET(*deleter)(TCLASS*)) { + return ctor(name.c_str(), spawner, deleter); + } + + template + inline LuaClass& ctor(const std::string& name, TCLASS*(*spawner)(ARGS...), std::nullptr_t) { + return ctor(name.c_str(), spawner, nullptr); + } +#endif + + private: + template + inline LuaClass& _registerClassFunction(const char* name, lua_CFunction caller, F f) + { + luaL_getmetatable(m_state, klassName); + if (strcmp(name, "__gc") == 0) + { + lua_pushstring(m_state, "!__gc"); + } +#if LUAAA_FEATURE_PROPERTY + else if (strcmp(name, "__index") == 0) + { + lua_pushstring(m_state, "!__index"); + } + else if (strcmp(name, "__newindex") == 0) + { + lua_pushstring(m_state, "!__newindex"); + } +#endif + else + { + lua_pushstring(m_state, name); + } + + F* funPtr = (F*)lua_newuserdata(m_state, sizeof(F)); +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, funPtr != nullptr, 1, "faild to alloc mem to store function"); +#else + luaL_argcheck(m_state, funPtr != nullptr, 1, (std::string("faild to alloc mem to store function `") + name + "`").c_str()); +#endif + if (funPtr) + { + memset(funPtr, 0, sizeof(F)); + *funPtr = f; + lua_pushcclosure(m_state, caller, 1); + lua_settable(m_state, -3); + lua_pop(m_state, 1); + } + else + { + lua_pop(m_state, 2); + } + return (*this); + } + + private: + template + inline LuaClass& _funImpl(const char * name, F f) + { + return _registerClassFunction(name, MemberFunctionCaller(f), f); + } + + public: + template + inline LuaClass& fun(const char * name, FRET(FCLASS::*f)(FARGS...)) + { + return _funImpl(name, f); + } + + template + inline LuaClass& fun(const char * name, FRET(FCLASS::*f)(FARGS...) const) + { + return _funImpl(name, f); + } + + template + inline LuaClass& fun(const char * name, void(FCLASS::*f)(FARGS...)) + { + return _funImpl(name, f); + } + + template + inline LuaClass& fun(const char * name, void(FCLASS::*f)(FARGS...) const) + { + return _funImpl(name, f); + } + + template + inline LuaClass& fun(const char * name, FRET(*f)(FARGS...)) + { + return _funImpl(name, f); + } + + template + inline LuaClass& fun(const char * name, void(*f)(FARGS...)) + { + return _funImpl(name, f); + } + +#if !LUAAA_WITHOUT_CPP_STDLIB + // register lambdas as lua class function + template + inline LuaClass& fun(const char * name, const std::function& f) + { + return _funImpl>(name, f); + } + + template + inline LuaClass& fun(const char * name, const std::function& f) + { + return _funImpl>(name, f); + } + + template + inline LuaClass& fun(const char * name, F f) + { + return fun(name, to_function(f)); + } +#endif + + inline LuaClass& fun(const char * name, lua_CFunction f) + { + luaL_getmetatable(m_state, klassName); + if (strcmp(name, "__gc") == 0) + { + lua_pushstring(m_state, "!__gc"); + } +#if LUAAA_FEATURE_PROPERTY + else if (strcmp(name, "__index") == 0) + { + lua_pushstring(m_state, "!__index"); + } + else if (strcmp(name, "__newindex") == 0) + { + lua_pushstring(m_state, "!__newindex"); + } +#endif + else + { + lua_pushstring(m_state, name); + } + lua_pushcclosure(m_state, f, 0); + lua_settable(m_state, -3); + lua_pop(m_state, 1); + return (*this); + } + + template + inline LuaClass& def(const char * name, const V& val) + { + luaL_getmetatable(m_state, klassName); + lua_pushstring(m_state, name); + LuaStack::put(m_state, val); + lua_settable(m_state, -3); + lua_pop(m_state, 1); + return (*this); + } + + // disable cast from "const char [#]" to "char (*)[#]" + inline LuaClass& def(const char* name, const char* str) + { + luaL_getmetatable(m_state, klassName); + lua_pushstring(m_state, name); + LuaStack::put(m_state, str); + lua_settable(m_state, -3); + lua_pop(m_state, 1); + return (*this); + } + + private: + template + inline LuaClass& _getterImpl(const char* name, lua_CFunction invoker, F f) + { +#if LUAAA_FEATURE_PROPERTY + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), "<%s", name); + return _registerClassFunction(internal_name, invoker, f); +#else + return *this; +#endif + } + + template + inline LuaClass& _setterImpl(const char* name, lua_CFunction invoker, F f) + { +#if LUAAA_FEATURE_PROPERTY + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), ">%s", name); + return _registerClassFunction(internal_name, invoker, f); +#else + return *this; +#endif + } + + public: + template + inline LuaClass& get(const char* name, P(*f)()) + { + struct HelperClass { + typedef decltype(f) FTYPE; + static inline int Invoke(lua_State* state) { + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))()); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& get(const char* name, P(*f)(const TCLASS&)) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))(LuaStack::get(state, 1))); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& get(const char* name, P(FCLASS::*f)()const) + { + static_assert(std::is_same, std::decay>::value, "Error: prop function can be member function of only associated class"); + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (LuaStack::get(state, 1).**(FTYPE*)(calleePtr))()); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + + template + inline LuaClass& set(const char* name, TRET(*f)(P)) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& set(const char* name, TRET(FCLASS::* f)(P)) + { + static_assert(std::is_same, std::decay>::value, "prop function can be member function of only associated class"); + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (LuaStack::get(state, 1).**(FTYPE*)(calleePtr))(LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& set(const char* name, TRET(*f)(TCLASS&, P)) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack::get(state, 1), LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + + public: +#if !LUAAA_WITHOUT_CPP_STDLIB + // access prop from lambdas + template + inline LuaClass& get(const char* name, std::function f) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))()); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& get(const char* name, std::function f) + { + struct HelperClass { + + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))(LuaStack::get(state, 1))); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& get(const char* name, std::function f) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))(LuaStack::get(state, 1))); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& get(const char* name, F f) + { + return get(name, to_class_getter_function(f)); + } + + template + inline LuaClass& set(const char* name, std::function f) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& set(const char* name, std::function f) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack::get(state, 1), LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaClass& set(const char* name, std::function f) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack::get(state, 1), LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + //template + //inline LuaClass& set(const char* name, std::function f) + //{ + // //static_assert(false, "Error: invalid signature of setter function"); + // assert(!"Error: invalid signature of setter function"); + // return (*this); + //} + + template + inline LuaClass& set(const char* name, F f) + { + return set(name, to_class_setter_function(f)); + } +#endif + + public: +#if !LUAAA_WITHOUT_CPP_STDLIB + template + inline LuaClass& fun(const std::string& name, F f) + { + return fun(name.c_str(), f); + } + + template + inline LuaClass& def(const std::string& name, const V& val) + { + return def(name.c_str(), val); + } + + template + inline LuaClass& get(const std::string& name, F f) + { + return get(name.c_str(), f); + } + + template + inline LuaClass& set(const std::string& name, F f) + { + return set(name.c_str(), f); + } +#endif + + private: + lua_State * m_state; + + private: + static char * klassName; + }; + + template char * LuaClass::klassName = nullptr; + + + // ----------------------------------- + // export module + // ----------------------------------- + struct LuaModule + { + public: + LuaModule(lua_State * state, const char * name = "_G") + : m_state(state) + { + size_t strBufLen = strlen(name) + 1; + m_moduleName = new char[strBufLen]; + memcpy(m_moduleName, name, strBufLen); + def("__name", m_moduleName); + } + +#if !LUAAA_WITHOUT_CPP_STDLIB + LuaModule(lua_State * state, const std::string& name) + : LuaModule(state, name.empty() ? "_G" : name.c_str()) + {} +#endif + + ~LuaModule() + { + if (m_moduleName) { + delete[] m_moduleName; + m_moduleName = nullptr; + } + } + + private: + void _initMetaTable(lua_State * state, int idx) { + struct HelperClass { +#if LUAAA_FEATURE_PROPERTY + static int f_internal_index(lua_State* state) + { + const char* key = luaL_checkstring(state, 2); + if (!key) + { + lua_pushnil(state); + return 1; + } + // lookup module first + lua_pushstring(state, key); + lua_rawget(state, 1); + if (!lua_isnil(state, -1)) + { + return 1; + } + + lua_pop(state, 1); + + // then lookup registered property + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), "<%s", key); + + lua_getmetatable(state, 1); + lua_pushstring(state, internal_name); + lua_rawget(state, -2); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 1, 0); + } + else + { + // check if user defined __index method + lua_pop(state, 3); + lua_pushstring(state, "__index"); + lua_rawget(state, 1); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 1, 0); + } + else if (lua_istable(state, -1)) + { + lua_replace(state, 1); + lua_rawget(state, 1); + } + else + { + // no custom __index + lua_getmetatable(state, 1); + snprintf(internal_name, sizeof(internal_name), ">%s", key); + lua_pushstring(state, internal_name); + lua_rawget(state, -2); + if (lua_isfunction(state, -1)) + { + lua_pushstring(state, "__name"); + lua_rawget(state, -3); + luaL_error(state, "attempt to read Write-Only property '%s' of '%s'", luaL_optstring(state, -1, "?")); + } + else + { + // do nothing here. nil will be return. + // luaL_error(state, "attempt to access Non-existing property '%s' of '%s'", key, LuaClass::klassName); + } + } + } + return 1; + } + + static int f_internal_newindex(lua_State* state) + { + const char* key = luaL_checkstring(state, 2); + if (!key) + { + lua_pushnil(state); + return 1; + } + + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), ">%s", key); + + lua_getmetatable(state, 1); + lua_pushstring(state, internal_name); + lua_rawget(state, -2); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 0, 0); + } + else + { + lua_pop(state, 1); + snprintf(internal_name, sizeof(internal_name), "<%s", key); + lua_pushstring(state, internal_name); + lua_rawget(state, -2); + if (lua_isfunction(state, -1)) + { + luaL_error(state, "attempt to write Read-Only property '%s' of '?'", key); + } + else + { + lua_pop(state, 2); + // no associated property, lookup current module + if (lua_istable(state, 1)) + { + // check if user defined __newindex + lua_pushstring(state, "__newindex"); + lua_rawget(state, 1); + if (lua_isfunction(state, -1)) + { + lua_insert(state, 1); + lua_pcall(state, lua_gettop(state) - 1, 0, 0); + } + else if (lua_istable(state, -1)) + { + lua_replace(state, 1); + lua_rawset(state, 1); + } + else + { + // no custom __newindex + lua_pop(state, 1); + lua_rawset(state, 1); + } + } + } + } + return 0; + } +#endif + }; + + luaL_newmetatable(state, m_moduleName); + luaL_Reg objfunc[] = { +#if LUAAA_FEATURE_PROPERTY + { "__index", HelperClass::f_internal_index }, + { "__newindex", HelperClass::f_internal_newindex }, +#endif + { nullptr, nullptr } + }; + luaL_setfuncs(state, objfunc, 0); + lua_setmetatable(state, -2); + } + + template + inline LuaModule& _registerModuleFunction(const char* name, lua_CFunction caller, F f) { +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, m_moduleName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + _initMetaTable(m_state, -1); + } + + F* funPtr = (F*)lua_newuserdata(m_state, sizeof(F)); +# if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, funPtr != nullptr, 1, "faild to alloc mem to store function of module"); +# else + luaL_argcheck(m_state, funPtr != nullptr, 1, (std::string("faild to alloc mem to store function `") + name + "`").c_str()); +# endif + if (!funPtr) + { + lua_pop(m_state, 2); + return (*this); + } + + memset(funPtr, 0, sizeof(F)); + *funPtr = f; + + lua_pushvalue(m_state, -1); + lua_pushcclosure(m_state, caller, 1); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -4); + lua_pop(m_state, 1); + lua_setglobal(m_state, m_moduleName); +#else + luaL_Reg regtab[] = { { name, caller },{ nullptr, nullptr } }; + F* funPtr = (F*)lua_newuserdata(m_state, sizeof(F)); +# if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, funPtr != nullptr, 1, "faild to alloc mem to store function of module"); +# else + luaL_argcheck(m_state, funPtr != nullptr, 1, (std::string("faild to alloc mem to store function `") + name + "`").c_str()); +# endif + if (funPtr) + { + memset(funPtr, 0, sizeof(F)); + *funPtr = f; + luaL_openlib(m_state, m_moduleName, regtab, 1); + } +#endif + return (*this); + } + + template + inline LuaModule& _funImpl(const char * name, F f) + { + return _registerModuleFunction(name, NonMemberFunctionCaller(f), f); + } + + public: + template + inline LuaModule& fun(const char * name, FRET(*f)(FARGS...)) + { + return _funImpl(name, f); + } + + template + inline LuaModule& fun(const char * name, void(*f)(FARGS...)) + { + return _funImpl(name, f); + } + +#if !LUAAA_WITHOUT_CPP_STDLIB + template + inline LuaModule& fun(const char * name, const std::function& f) + { + return _funImpl>(name, f); + } + + template + inline LuaModule& fun(const char * name, const std::function& f) + { + return _funImpl>(name, f); + } + + template + inline LuaModule& fun(const char * name, F f) + { + return fun(name, to_function(f)); + } +#endif + + inline LuaModule& fun(const char * name, lua_CFunction f) + { + +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, m_moduleName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + _initMetaTable(m_state, -1); + } + lua_pushcclosure(m_state, f, 0); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); + lua_setglobal(m_state, m_moduleName); +#else + luaL_Reg regtab[] = { { name, f },{ nullptr, nullptr } }; + luaL_openlib(m_state, m_moduleName, regtab, 0); +#endif + return (*this); + } + + template + inline LuaModule& def(const char * name, const V& val) + { +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, m_moduleName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + _initMetaTable(m_state, -1); + } + LuaStack::put(m_state, val); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); + lua_setglobal(m_state, m_moduleName); +#else + luaL_Reg regtab = { nullptr, nullptr }; + luaL_openlib(m_state, m_moduleName, ®tab, 0); + LuaStack::put(m_state, val); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); +#endif + return (*this); + } + + template + inline LuaModule& def(const char* name, const luaaa::LuaClass&, const TCLASS* obj = nullptr, void(*deleter)(TCLASS*) = nullptr) + { + typename LuaClass::UserDataDetail userData{}; + if (obj) + { + userData.obj = const_cast(obj); + if (deleter) + { + struct HelperClass + { + static int f_dtor(typename LuaClass::UserDataDetail* uData) { + typedef decltype(deleter) DELETERFTYPE; + if (uData && uData->obj && uData->free_func) + { + ((DELETERFTYPE)(uData->free_func))(uData->obj); + uData->obj = nullptr; + } + return 0; + } + }; + + userData.dtor = HelperClass::f_dtor; + userData.free_func = (void*)(deleter); + } + else + { + userData.dtor = nullptr; + userData.free_func = nullptr; + } + } + else + { + struct HelperClass + { + static int f_dtor(typename LuaClass::UserDataDetail* uData) + { + if (uData && uData->obj) + { + delete uData->obj; + uData->obj = nullptr; + } + return 0; + } + }; + userData.obj = new TCLASS; + userData.dtor = HelperClass::f_dtor; + userData.free_func = nullptr; + } + +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, m_moduleName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + _initMetaTable(m_state, -1); + } + auto uData = (typename LuaClass::UserDataDetail*)lua_newuserdata(m_state, sizeof(typename LuaClass::UserDataDetail)); +#if LUAAA_WITHOUT_CPP_STDLIB + luaL_argcheck(m_state, uData != nullptr, 1, "faild to alloc mem to store object"); +#else + luaL_argcheck(m_state, uData != nullptr, 1, (std::string("faild to alloc mem to store object `") + name + "`").c_str()); +#endif + if (uData) + { + uData->obj = userData.obj; + uData->dtor = userData.dtor; + uData->free_func = userData.free_func; + luaL_setmetatable(m_state, (LuaClass::klassName)); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); + lua_setglobal(m_state, m_moduleName); + } + else + { + lua_pop(m_state, 2); + } +#else + luaL_Reg regtab = { nullptr, nullptr }; + luaL_openlib(m_state, m_moduleName, ®tab, 0); + auto uData = (typename LuaClass::UserDataDetail*)lua_newuserdata(m_state, sizeof(typename LuaClass::UserDataDetail)); + if (uData) + { + uData->obj = userData.obj; + uData->dtor = userData.dtor; + uData->free_func = userData.free_func; + luaL_setmetatable(m_state, (LuaClass::klassName)); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); + } + else + { + lua_pop(m_state, 1); + } +#endif + return (*this); + } + + template + inline LuaModule& def(const char * name, const V val[], size_t length) + { +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, m_moduleName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + _initMetaTable(m_state, -1); + } + lua_newtable(m_state); + for (size_t idx = 0; idx < length; ++idx) + { + LuaStack::put(m_state, val[idx]); + lua_rawseti(m_state, -2, idx + 1); + } + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); + lua_setglobal(m_state, m_moduleName); +#else + luaL_Reg regtab = { nullptr, nullptr }; + luaL_openlib(m_state, m_moduleName, ®tab, 0); + lua_newtable(m_state); + for (size_t idx = 0; idx < length; ++idx) + { + LuaStack::put(m_state, val[idx]); + lua_rawseti(m_state, -2, idx + 1); + } + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); +#endif + return (*this); + } + + // disable the cast from "const char [#]" to "char (*)[#]" + inline LuaModule& def(const char * name, const char * str) + { +#if USE_NEW_MODULE_REGISTRY + lua_getglobal(m_state, m_moduleName); + if (lua_isnil(m_state, -1)) + { + lua_pop(m_state, 1); + lua_newtable(m_state); + _initMetaTable(m_state, -1); + } + LuaStack::put(m_state, str); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); + lua_setglobal(m_state, m_moduleName); +#else + luaL_Reg regtab = { nullptr, nullptr }; + luaL_openlib(m_state, m_moduleName, ®tab, 0); + LuaStack::put(m_state, str); + lua_pushstring(m_state, name); + lua_insert(m_state, -2); + lua_rawset(m_state, -3); +#endif + return (*this); + } + +#if !LUAAA_WITHOUT_CPP_STDLIB + template + inline LuaModule& fun(const std::string& name, F f) + { + return fun(name.c_str(), f); + } + + template + inline LuaModule& def(const std::string& name, const V& val) + { + return def(name.c_str(), val); + } +#endif + + private: + template + inline LuaModule& _getterImpl(const char* name, lua_CFunction invoker, F f) + { +#if LUAAA_FEATURE_PROPERTY + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), "<%s", name); + return _registerModuleFunction(internal_name, invoker, f); +#else + return *this; +#endif + } + + template + inline LuaModule& _setterImpl(const char* name, lua_CFunction invoker, F f) + { +#if LUAAA_FEATURE_PROPERTY + char internal_name[256]; + snprintf(internal_name, sizeof(internal_name), ">%s", name); + return _registerModuleFunction(internal_name, invoker, f); +#else + return *this; +#endif + } + + public: + template + inline LuaModule& get(const char* name, P(*f)()) + { + static_assert(!std::is_void

::value, "Error: getter function must return a value."); + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))()); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + template + inline LuaModule& set(const char* name, TRET(*f)(P)) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + public: +#if !LUAAA_WITHOUT_CPP_STDLIB + // access prop from lambdas + template + inline LuaModule& get(const char* name, std::function f) + { + static_assert(!std::is_void

::value, "Error: getter function must return a value."); + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + LuaStackReturn

(state, (*(FTYPE*)(calleePtr))()); + } + else + { + lua_pushnil(state); + } + return 1; + } + }; + return _getterImpl(name, HelperClass::Invoke, f); + } + + // template + // inline LuaModule& get(const char* name, std::function f) + // { + // //static_assert(false, "Error: invalid signature of getter function"); + // assert(!"Error: invalid signature of getter function"); + // return (*this); + // } + + template + inline LuaModule& get(const char* name, F f) + { + return get(name, to_module_getter_function(f)); + } + + template + inline LuaModule& set(const char* name, std::function f) + { + struct HelperClass { + static inline int Invoke(lua_State* state) { + typedef decltype(f) FTYPE; + void* calleePtr = lua_touserdata(state, lua_upvalueindex(1)); + if (calleePtr) + { + (*(FTYPE*)(calleePtr))(LuaStack

::get(state, 3)); + } + return 0; + } + }; + return _setterImpl(name, HelperClass::Invoke, f); + } + + // template + // inline LuaModule& set(const char* name, std::function f) + // { + // //static_assert(std::false_type::value, "Error: invalid signature of setter function"); + // //assert(!"Error: invalid signature of setter function"); + // return (*this); + // } + + template + inline LuaModule& set(const char* name, F f) + { + return set(name, to_module_setter_function(f)); + } + + template + inline LuaModule& get(const std::string& name, F f) + { + return get(name.c_str(), f); + } + + template + inline LuaModule& set(const std::string& name, F f) + { + return set(name.c_str(), f); + } +#endif + + private: + lua_State * m_state; + char * m_moduleName; + }; + +} + + + +#if !LUAAA_WITHOUT_CPP_STDLIB + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace LUAAA_NS +{ + // array + template + struct LuaStack> + { + typedef std::array Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + int index = 0; + lua_pushnil(L); + while (0 != lua_next(L, idx) && index < N) + { + result[index++] = LuaStack::get(L, lua_gettop(L)); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // vector + template + struct LuaStack> + { + typedef std::vector Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.push_back(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // deque + template + struct LuaStack> + { + typedef std::deque Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.push_back(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // list + template + struct LuaStack> + { + typedef std::list Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.push_back(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // forward_list + template + struct LuaStack> + { + typedef std::forward_list Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.push_back(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // set + template + struct LuaStack> + { + typedef std::set Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.insert(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // multiset + template + struct LuaStack> + { + typedef std::multiset Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.insert(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // unordered_set + template + struct LuaStack> + { + typedef std::unordered_set Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.insert(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // unordered_multiset + template + struct LuaStack> + { + typedef std::unordered_multiset Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + result.insert(LuaStack::get(L, lua_gettop(L))); + lua_pop(L, 1); + } + } + return result; + } + + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + int index = 1; + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, *it); + lua_rawseti(L, -2, index++); + } + } + }; + + // map + template + struct LuaStack> + { + typedef std::map Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + const int top = lua_gettop(L); + result[LuaStack::get(L, top - 1)] = LuaStack::get(L, top); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, it->first); + LuaStack::put(L, it->second); + lua_rawset(L, -3); + } + } + }; + + // multimap + template + struct LuaStack> + { + typedef std::multimap Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + const int top = lua_gettop(L); + result[LuaStack::get(L, top - 1)] = LuaStack::get(L, top); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, it->first); + LuaStack::put(L, it->second); + lua_rawset(L, -3); + } + } + }; + + // unordered_map + template + struct LuaStack> + { + typedef std::unordered_map Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + const int top = lua_gettop(L); + result[LuaStack::get(L, top - 1)] = LuaStack::get(L, top); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, it->first); + LuaStack::put(L, it->second); + lua_rawset(L, -3); + } + } + }; + + // unordered_multimap + template + struct LuaStack> + { + typedef std::unordered_multimap Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + while (0 != lua_next(L, idx)) + { + const int top = lua_gettop(L); + result[LuaStack::get(L, top - 1)] = LuaStack::get(L, top); + lua_pop(L, 1); + } + } + return result; + } + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + for (auto it = s.begin(); it != s.end(); ++it) + { + LuaStack::put(L, it->first); + LuaStack::put(L, it->second); + lua_rawset(L, -3); + } + } + }; + + // std::pair + template + struct LuaStack> + { + typedef std::pair Container; + inline static Container get(lua_State * L, int idx) + { + Container result; + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + result.first = LuaStack::get(L, idx + 1); + result.second = LuaStack::get(L, idx + 2); + } + return result; + } + + inline static void put(lua_State * L, const Container& s) + { + lua_newtable(L); + LuaStack::put(L, s.first); + lua_rawseti(L, -2, 1); + LuaStack::put(L, s.second); + lua_rawseti(L, -2, 2); + } + }; + + // std::tuple +#if __cplusplus >= 201402 || _MSVC_LANG >= 201402 + template struct is_tuple : std::false_type {}; + template struct is_tuple> : std::true_type {}; + + template::value>::type> + inline void load_tuple_from_lua_table(lua_State* L, int idx, Tuple& tuple, std::index_sequence) + { + luaL_argcheck(L, lua_istable(L, idx), 1, "required table not found on stack."); + if (lua_istable(L, idx)) + { + lua_pushnil(L); + (void)std::initializer_list{( + lua_next(L, idx) && (std::get(tuple) = LuaStack(tuple))>::get(L, lua_gettop(L)), 1) && (lua_pop(L, 1), 1), + 0)...}; + } + } + + template::value>::type> + inline void save_tuple_to_lua_table(lua_State* L, const Tuple& tuple, std::index_sequence) + { + lua_newtable(L); + (void)std::initializer_list{( + LuaStack(tuple))>::put(L, std::get(tuple)), + lua_rawseti(L, -2, Index + 1), + 0)...}; + } + + template + struct LuaStack> + { + typedef std::tuple Container; + inline static Container get(lua_State* L, int idx) + { + Container result; + load_tuple_from_lua_table(L, idx, result, std::make_index_sequence::value>{}); + return result; + } + + inline static void put(lua_State* L, const Container& s) + { + save_tuple_to_lua_table(L, s, std::make_index_sequence::value>{}); + } + }; +#elif __cplusplus + template + struct TupleAccessor + { + static void get(lua_State* L, int idx, T& tuple) + { + TupleAccessor::get(L, idx, tuple); + if (lua_next(L, idx)) + { + const int top = lua_gettop(L); + std::get(tuple) = LuaStack::type>::get(L, top); + lua_pop(L, 1); + } + } + + static void put(lua_State* L, const T& tuple) { + TupleAccessor::put(L, tuple); + LuaStack::type>::put(L, std::get(tuple)); + lua_rawseti(L, -2, N); + } + }; + + template + struct TupleAccessor + { + static void get(lua_State* L, int idx, T& tuple) + { + if (lua_next(L, idx)) + { + const int top = lua_gettop(L); + std::get<0>(tuple) = LuaStack(tuple))>::get(L, top); + lua_pop(L, 1); + } + } + + static void put(lua_State* L, const T& tuple) { + LuaStack::type>::put(L, std::get<0>(tuple)); + lua_rawseti(L, -2, 1); + } + }; + + template + struct TupleAccessor + { + static void get(lua_State*, int, T&) {} + static void put(lua_State*, const T&) {} + }; + + template + struct LuaStack> + { + typedef std::tuple Container; + inline static Container get(lua_State* L, int idx) + { + Container result; + lua_pushnil(L); + TupleAccessor::value>::get(L, idx, result); + return result; + } + + inline static void put(lua_State* L, const Container& s) + { + lua_newtable(L); + TupleAccessor::value>::put(L, s); + } + }; +#endif + +} + +#endif //#if !LUAAA_WITHOUT_CPP_STDLIB + +#endif +