types.cpp 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #include <lua.hpp>
  2. #include <luwra.hpp>
  3. #include <iostream>
  4. namespace luwra {
  5. // You may add custom specializations of luwra::Value in order to retrieve them from the stack.
  6. template <>
  7. struct Value<char> {
  8. /**
  9. * Retrieve the value at position `n`.
  10. */
  11. static inline
  12. char read(lua_State* state, int n) {
  13. auto str = Value<std::string>::read(state, n);
  14. if (str.length() < 1) {
  15. luaL_argerror(state, n, "Given empty string instead of character");
  16. }
  17. return str[0];
  18. }
  19. /**
  20. * push the value onto the stack.
  21. */
  22. static inline
  23. size_t push(lua_State* state, char val) {
  24. if (val == 0)
  25. return 0;
  26. lua_pushlstring(state, &val, 1);
  27. return 1;
  28. }
  29. };
  30. }
  31. static
  32. void read_chars(char a, char b) {
  33. std::cout << "Got '" << a << b << "'" << std::endl;
  34. }
  35. int main() {
  36. lua_State* state = luaL_newstate();
  37. luaL_openlibs(state);
  38. // Build stack
  39. luwra::push(state, 'H');
  40. luwra::push(state, 'i');
  41. // apply function to stack values
  42. luwra::apply(state, read_chars);
  43. lua_pop(state, 2);
  44. // Build stack again
  45. luwra::push(state, 'Y', 'o');
  46. luwra::apply(state, read_chars);
  47. lua_close(state);
  48. return 0;
  49. }