script.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. #include "lua.hpp"
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. int main ()
  5. {
  6. int status, result, i;
  7. double sum;
  8. lua_State *L;
  9. /*
  10. * All Lua contexts are held in this structure. We work with it almost
  11. * all the time.
  12. */
  13. L = luaL_newstate();
  14. luaL_openlibs(L); /* Load Lua libraries */
  15. /* Load the file containing the script we are going to run */
  16. status = luaL_loadfile(L, "hello.lua");
  17. if (status)
  18. {
  19. /* If something went wrong, error message is at the top of */
  20. /* the stack */
  21. fprintf(stderr, "Couldn't load file: %s\n", lua_tostring(L, -1));
  22. exit(1);
  23. }
  24. /*
  25. * Ok, now here we go: We pass data to the lua script on the stack.
  26. * That is, we first have to prepare Lua's virtual stack the way we
  27. * want the script to receive it, then ask Lua to run it.
  28. */
  29. lua_newtable(L); /* We will pass a table */
  30. /*
  31. * To put values into the table, we first push the index, then the
  32. * value, and then call lua_rawset() with the index of the table in the
  33. * stack. Let's see why it's -3: In Lua, the value -1 always refers to
  34. * the top of the stack. When you create the table with lua_newtable(),
  35. * the table gets pushed into the top of the stack. When you push the
  36. * index and then the cell value, the stack looks like:
  37. *
  38. * <- [stack bottom] -- table, index, value [top]
  39. *
  40. * So the -1 will refer to the cell value, thus -3 is used to refer to
  41. * the table itself. Note that lua_rawset() pops the two last elements
  42. * of the stack, so that after it has been called, the table is at the
  43. * top of the stack.
  44. */
  45. for (i = 1; i <= 5; i++)
  46. {
  47. lua_pushnumber(L, i); /* Push the table index */
  48. lua_pushnumber(L, i*2); /* Push the cell value */
  49. lua_rawset(L, -3); /* Stores the pair in the table */
  50. }
  51. /* By what name is the script going to reference our table? */
  52. lua_setglobal(L, "foo");
  53. /* Ask Lua to run our little script */
  54. result = lua_pcall(L, 0, LUA_MULTRET, 0);
  55. if (result) {
  56. fprintf(stderr, "Failed to run script: %s\n", lua_tostring(L, -1));
  57. exit(1);
  58. }
  59. /* Get the returned value at the top of the stack (index -1) */
  60. sum = lua_tonumber(L, -1);
  61. printf("Script returned: %.0f\n", sum);
  62. lua_pop(L, 1); /* Take the returned value out of the stack */
  63. lua_close(L); /* Cya, Lua */
  64. return 0;
  65. }