ソースを参照

More examples about methods

Ole Krüger 10 年 前
コミット
6eb70ed87a
共有3 個のファイルを変更した82 個の追加3 個の削除を含む
  1. 5 3
      examples/Makefile
  2. 70 0
      examples/methods.cpp
  3. 7 0
      examples/methods.lua

+ 5 - 3
examples/Makefile

@@ -3,7 +3,7 @@ RM              = rm -rf
 EXEC            = exec
 
 # Artifacts
-OBJS            = functions.out
+OBJS            = functions.out methods.out
 DEPS            = $(OBJS:%=%.d)
 
 # Compiler
@@ -13,8 +13,10 @@ CXXFLAGS        += -std=c++14 -O2 -fno-exceptions -fno-rtti -fmessage-length=0 -
 LDLIBS          += -llua
 
 # Default Targets
-all: $(OBJS)
-	$(foreach OBJ,$(OBJS),$(EXEC) ./$(OBJ))
+all: $(OBJS) $(foreach obj,$(OBJS),exec-$(obj))
+
+exec-%: %
+	$(EXEC) ./$<
 
 clean:
 	$(RM) $(DEPS) $(OBJS)

+ 70 - 0
examples/methods.cpp

@@ -0,0 +1,70 @@
+#include <lua.hpp>
+#include <luwra.hpp>
+
+#include <iostream>
+
+struct Point {
+	// Luwra needs the MetatableName field in order to add a meta table to the Lua registry
+	static constexpr
+	const char* MetatableName = "Point";
+
+	lua_Number x, y;
+
+	Point(lua_Number x, lua_Number y):
+		x(x), y(y)
+	{
+		std::cout << "Construct Point(" << x << ", " << y << ")" << std::endl;
+	}
+
+	~Point() {
+		std::cout << "Destruct Point(" << x << ", " << y << ")" << std::endl;
+	}
+
+	void scale(lua_Number f) {
+		x *= f;
+		y *= f;
+	}
+
+	std::string toString() {
+		return "<Point(" + std::to_string(x) + ", " + std::to_string(y) + ")>";
+	}
+};
+
+int main() {
+	lua_State* state = luaL_newstate();
+	luaL_openlibs(state);
+
+	// Register the metatable for our Point type.
+	// This function also registers a garbage-collector hook and a string representation function.
+	// Both can be overwritten using the third parameter, which lets you add custom meta methods.
+	luwra::register_type_metatable<Point>(
+		state,
+		// Methods which shall be availabe in the Lua user data, need to be declared here
+		{
+			{"scale", luwra::WrapMethod<Point, void(lua_Number), &Point::scale>},
+		},
+		// Meta methods may be registered aswell
+		{
+			{"__tostring", luwra::WrapMethod<Point, std::string(), &Point::toString>}
+		}
+	);
+
+	// What's left, is register a constructor for our type.
+	// We have to specify which parameters our constructor takes, because there might be more than
+	// one constructor to deal with.
+	auto wrapped_ctor = luwra::WrapConstructor<Point, lua_Number, lua_Number>;
+	lua_pushcfunction(state, wrapped_ctor);
+	lua_setglobal(state, "Point");
+
+	// Invoke the attached script
+	if (luaL_loadfile(state, "methods.lua") != 0 || lua_pcall(state, 0, LUA_MULTRET, 0) != 0) {
+		const char* error_msg = lua_tostring(state, -1);
+		std::cerr << "An error occured: " << error_msg << std::endl;
+
+		lua_close(state);
+		return 1;
+	} else {
+		lua_close(state);
+		return 0;
+	}
+}

+ 7 - 0
examples/methods.lua

@@ -0,0 +1,7 @@
+-- Instantiate type
+local p = Point(13, 37)
+print("p =", p)
+
+-- Invoke 'scale' method
+p:scale(2)
+print("p =", p)