Advertisement
cwchen

Call Lua from String

Jan 18th, 2017
540
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.90 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include "lua5.2/lua.h"
  4. #include "lua5.2/lualib.h"
  5. #include "lua5.2/lauxlib.h"
  6.  
  7. // Our main function
  8. void my_main(lua_State*);
  9.  
  10. // Vector class
  11. void vector(lua_State*);
  12.  
  13. // Error handling
  14. void bail(lua_State*, const char*);
  15.  
  16. int main() {
  17.   // Init Lua
  18.   lua_State* Lua = luaL_newstate();
  19.  
  20.   // Call Lua base library
  21.   luaopen_base(Lua);
  22.  
  23.   // Call Lua auxiliary library
  24.   luaL_openlibs(Lua);
  25.  
  26.   // Load Vector class
  27.   vector(Lua);
  28.  
  29.   // Load our main function
  30.   my_main(Lua);
  31.  
  32.   // Clean up Lua state
  33.   lua_close(Lua);
  34.  
  35.   return 0;
  36. }
  37.  
  38. // Our main function
  39. void my_main(lua_State* L) {
  40.   int state =
  41.     luaL_dostring(L,
  42.                   "v = Vector:from_table({1, 2, 3, 4});"
  43.                   "assert(#v == 4);"
  44.                   "assert(v[1] == 1);");
  45.   if (state != LUA_OK) {
  46.     bail(L, "Failed to load main block\n");
  47.   }
  48. }
  49.  
  50. // Vector class
  51. void vector(lua_State* L) {
  52.   int state =
  53.     luaL_dostring(L,
  54.                   "Vector = {};"
  55.                   "Vector.__index = Vector;"
  56.                   "function Vector:new(size);"
  57.                   "    local self = {};"
  58.                   "    for i = 1, size do;"
  59.                   "        table.insert(self, 0);"
  60.                   "    end;"
  61.                   "    setmetatable(self, Vector);"
  62.                   "    return self;"
  63.                   "end;"
  64.                   "function Vector:from_table(t);"
  65.                   "    local v = Vector:new(#t);"
  66.                   "    for i = 1, #t do;"
  67.                   "        v[i] = t[i];"
  68.                   "    end;"
  69.                   "    return v;"
  70.                   "end;");
  71.     if (state != LUA_OK) {
  72.       bail(L, "Failed to load Vector class\n");
  73.     }
  74. }
  75.  
  76. void bail(lua_State* L, const char* msg) {
  77.   fprintf(stderr, "ERROR: %s: %s\n",
  78.           msg, lua_tostring(L, -1));
  79.   lua_close(L);
  80.   exit(EXIT_FAILURE);
  81. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement