Explorar o código

Add functions example

Ole Krüger %!s(int64=10) %!d(string=hai) anos
pai
achega
800486484f
Modificáronse 2 ficheiros con 21 adicións e 6 borrados
  1. 11 6
      examples/functions.cpp
  2. 10 0
      examples/functions.lua

+ 11 - 6
examples/functions.cpp

@@ -22,6 +22,7 @@ Integer my_function_3(Integer a, Integer b) {
 
 int main() {
 	lua_State* state = luaL_newstate();
+	luaL_openlibs(state);
 
 	// Register 'my_function_1'
 	auto wrapped_1 = WrapFunction<void(), my_function_1>;
@@ -39,10 +40,14 @@ int main() {
 	lua_setglobal(state, "my_function_3");
 
 	// Invoke the attached script
-	luaL_loadfile(state, "functions.lua");
-	lua_call(state, 0, LUA_MULTRET);
-
-	lua_close(state);
-
-	return 0;
+	if (luaL_loadfile(state, "functions.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;
+	}
 }

+ 10 - 0
examples/functions.lua

@@ -0,0 +1,10 @@
+-- Invoke 'my_function_1'
+my_function_1()
+
+-- Invoke 'my_function_2'
+local result2 = my_function_2()
+print("my_function_2() = " .. result2)
+
+-- Invoke 'my_function_3'
+local result3 = my_function_3(13, 37)
+print("my_function_3(13, 38) = " .. result3)