stack.cpp 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. #include <catch.hpp>
  2. #include <lua.hpp>
  3. #include <luwra.hpp>
  4. static
  5. int test_function_1(int a, int b) {
  6. return a - b;
  7. }
  8. static
  9. int test_function_2(int a, int b, int c) {
  10. return a + b * c;
  11. }
  12. static
  13. void test_function_3(int) {
  14. }
  15. TEST_CASE("stack_interaction") {
  16. lua_State* state = luaL_newstate();
  17. luwra::push(state, 1);
  18. luwra::push(state, 2);
  19. luwra::push(state, 4);
  20. // Redundant function
  21. luwra::apply(state, test_function_3);
  22. // Absolute index
  23. REQUIRE(luwra::apply(state, test_function_1) == -1);
  24. REQUIRE(luwra::apply(state, 1, test_function_1) == -1);
  25. REQUIRE(luwra::apply(state, test_function_2) == 9);
  26. REQUIRE(luwra::apply(state, 1, test_function_2) == 9);
  27. // Relative index
  28. REQUIRE(luwra::apply(state, -2, test_function_1) == -2);
  29. REQUIRE(luwra::apply(state, -3, test_function_1) == -1);
  30. REQUIRE(luwra::apply(state, -3, test_function_2) == 9);
  31. lua_close(state);
  32. }
  33. TEST_CASE("stack_setGlobal") {
  34. lua_State* state = luaL_newstate();
  35. luwra::setGlobal(state, "test", 1338);
  36. REQUIRE(luaL_dostring(state, "return test") == LUA_OK);
  37. REQUIRE(luwra::read<int>(state, -1) == 1338);
  38. lua_close(state);
  39. }
  40. TEST_CASE("stack_setFields") {
  41. lua_State* state = luaL_newstate();
  42. lua_newtable(state);
  43. luwra::setFields(
  44. state, -1,
  45. "test", 1338,
  46. 123, 456
  47. );
  48. lua_setglobal(state, "test");
  49. REQUIRE(luaL_dostring(state, "return test.test, test[123]") == LUA_OK);
  50. REQUIRE(luwra::read<int>(state, -2) == 1338);
  51. REQUIRE(luwra::read<int>(state, -1) == 456);
  52. lua_close(state);
  53. }